# API

### Xero API Documentation

The Xero AI Assistant is accessible via a RESTful API, which allows for conversational interaction and retrieval of information. The API uses a proxy endpoint built on top of the ROMA framework.

***

#### Base URL

All API requests should be sent to the base proxy URL:

`https://api-sentient-roma-rex.ddnsfree.com/proxy`

***

#### Authentication 🔑

Access to the Xero API is secured with a Bearer API Key.

* Status: The Xero API is currently in Beta mode.
* Key Requirement: An API key is required for all requests.
* How to Obtain: To test out Xero and obtain an API key, please contact the development team at:
  * Email: `xero.dev.ai@gmail.com`

Authentication Header Example:

Your API key must be included in the Authorization header of every request:

HTTP

```
Authorization: Bearer <YOUR_API_KEY>
```

***

#### API Endpoints

The Xero API currently offers two main endpoints:

**1. System Health Check**

| Method | Endpoint  | Description                                        |
| ------ | --------- | -------------------------------------------------- |
| `GET`  | `/health` | Checks the operational status of the Xero service. |

Example Request:

Bash

```bash
curl -X GET 'https://api-sentient-roma-rex.ddnsfree.com/proxy/health'
```

Example Successful Response (JSON):

JSON

```json
{
  "status": "ok",
  "service": "Xero AI • Powered By ROMA",
  "model_status": "operational"
}
```

***

**2. Conversational Query (/research)**

This is the primary endpoint for submitting user queries and receiving AI-generated responses. It is designed to handle a chat-like context.

| Method | Endpoint    | Description                                          |
| ------ | ----------- | ---------------------------------------------------- |
| `POST` | `/research` | Sends a conversation context to Xero for a response. |

Request Body Structure (JSON):

The request body must contain a single field, `topic`, which is a formatted string representing the conversation history.

| Field   | Type     | Description                                                                                                   |
| ------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `topic` | `string` | A newline-separated string of the conversation history, where each message is formatted as `[ROLE]: CONTENT`. |

Conversation Formatting Logic:

Xero uses an array of message objects to build the `topic` string. The roles are `SYSTEM`, `USER`, and `ASSISTANT/XERO`.

1. System Prompt (Required): Always start with the system instruction to define Xero's persona.
2. Conversation History (Optional): Include the last user and Xero messages to maintain context for a multi-turn conversation.
3. Current User Message (Required): End with the current user query.

Example `topic` String for a new conversation:

```
[SYSTEM]: You are Xero, a general-purpose AI agent powered by ROMA and built by Rex. You are helpful, knowledgeable, and conversational. Keep your responses clear and concise. Attached here is a conversation flow between 2 roles, you (Xero) and the user who wants response to his query (user)

[USER]: What is the ROMA technology platform?
```

Example `topic` String for a follow-up conversation:

```
[SYSTEM]: You are Xero, a general-purpose AI agent powered by ROMA and built by Rex. You are helpful, knowledgeable, and conversational. Keep your responses clear and concise. Attached here is a conversation flow between 2 roles, you (Xero) and the user who wants response to his query (user)

[USER]: What is the ROMA technology platform?

[XERO]: The ROMA technology platform is the underlying AI/ML stack that powers Xero's reasoning and language capabilities. It is the proprietary foundation built by Rex.

[USER]: Can you tell me more about Rex?
```

Example Request:

Bash

```bash
curl -X POST 'https://api-sentient-roma-rex.ddnsfree.com/proxy/research' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <YOUR_API_KEY>' \
-d '{
    "topic": "[SYSTEM]: You are Xero...[USER]: What is the ROMA technology platform?"
}'
```

Example Successful Response (JSON):

The response will contain the AI's generated reply, typically within a `response` field.

JSON

```json
{
  "final_output": "The ROMA technology platform is the underlying AI/ML stack that powers Xero's reasoning and language capabilities. It is the proprietary foundation built by Rex."
}

```

***

## Javascript Examples

**Checking Health Request**

Javascript

```javascript
const PROXY_URL = 'https://api-sentient-roma-rex.ddnsfree.com/proxy';

async function checkXeroHealth() {
  try {
    const response = await fetch(`${PROXY_URL}/health`, {
      method: 'GET'
    });

    const data = await response.json();
    console.log('Xero Health Status:', data);
    // Expected output: { "status": "ok", "service": "Xero AI Assistant", "model_status": "operational" }

  } catch (error) {
    console.error('Error checking Xero health:', error);
  }
}

// checkXeroHealth();
```

**Sending A Query**

JavaScript Example (Sending a Query):

This example demonstrates how to build the conversation string (`topic`) and send the request.

```javascript
    // NOTE: Replace this with your actual API key
    const API_KEY = 'your_actual_api_key'; 
    const PROXY_RESEARCH_URL = 'https://api-sentient-roma-rex.ddnsfree.com/proxy/research';

    // Function to construct the 'topic' string from messages
    function formatMessages(messages) {
        return messages
            .map(msg => `[${msg.role.toUpperCase()}]: ${msg.content}`)
            .join('\n\n');
    }

    async function getXeroResponse(currentMessage, lastUserMessage = '', lastXeroMessage = '') {
        // 1. Prepare conversation context
        const messages = [
            {
                role: 'system',
                content: 'You are Xero, a general-purpose AI agent. You are helpful, knowledgeable, and conversational. Keep your responses clear and concise. Attached here is a conversation flow between 2 roles, you (Xero) and the user who wants response to his query (user)'
            }
        ];

        // 2. Add previous turn for context (optional, for multi-turn chat)
        if (lastUserMessage && lastXeroMessage != null) {
            messages.push({ role: 'user', content: lastUserMessage });
            messages.push({ role: 'xero', content: lastXeroMessage });
        }

        // 3. Add the current query
        messages.push({ role: 'user', content: currentMessage });

        // 4. Format the context into the required 'topic' string
        const topic = formatMessages(messages);
        // console.log('Formatted Topic:\n', topic); // Use this to inspect the payload

        try {
            const response = await fetch(PROXY_RESEARCH_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}` // Authentication header
                },
                body: JSON.stringify({ topic }) // Sending the formatted topic string, the "topic" variable name shouldn't be changed. 
            });

            if (!response.ok) {
                // Throw error for non-200 responses (e.g., 401 Unauthorized, 500 Server Error)
                const errorData = await response.json();
                throw new Error(`HTTP error! Status: ${response.status}. Message: ${errorData.message || JSON.stringify(errorData)}`);
            }

            const data = await response.json();
            console.log(data);
            return data.final_output;

        } catch (error) {
            console.error('Error calling Xero API:', error.message);
            return `Failed to get response: ${error.message}`;
        }
    }

    // --- Example Usage ---

    // A. Single-turn query (no history)
    (async () => {
        const query = "What are the core features of Xero AI?";
        const xeroReply = await getXeroResponse(query);
        console.log(`\nUser: ${query}`);
        console.log(`Xero: ${xeroReply}`);
    })();

    // B. Multi-turn query (with one turn of history)
    (async () => {
        const lastUser = "Can you describe the ROMA Framework?";
        const lastXero = "The ROMA technology framework is the underlying AI/ML stack that powers Xero's reasoning and language capabilities.";
        const currentQuery = "Who is Rex?";

        const xeroReply = await getXeroResponse(currentQuery, lastUser, lastXero);
        console.log(`\nUser: ${currentQuery}`);
        console.log(`Xero: ${xeroReply}`);
    })();
```

***

#### Error Handling

If a request fails, the API will return an appropriate HTTP status code and a JSON response detailing the error.

| Status Code      | Description                                                                                      |
| ---------------- | ------------------------------------------------------------------------------------------------ |
| 401 Unauthorized | Missing or invalid API key in the `Authorization` header.                                        |
| 400 Bad Request  | The request body is missing or the JSON is incorrectly formatted.                                |
| 5xx Server Error | An issue occurred on the server-side while processing the request (e.g., ROMA platform is down). |

Example Error Response (401):

JSON

```
{
  "error": "Authentication Failed",
  "message": "Invalid or missing API key. Please check your Authorization header."
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://moulders.gitbook.io/xero-ai/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
