# xChatBot Integration

### Overview

This document details the integration between the xFlow system and the xChatbot system via REST API. The integration includes communication protocols, data structures, and the sequence of interactions. All communication follows the CloudEvent specification and is conducted in JSON format.

### Communication Protocol

* **Protocol**: REST API
* **Data Format**: JSON, following CloudEvent specification
* **Request Initiator**: xChatbot system
* **Response Receiver**: xChatbot system (via webhook)

#### API Endpoints

* **Request Endpoint**: `https://xfai/api/aiQuery/query`
* **Response Webhook Endpoint**: `https://xchatbot/api/aiagent/reply`

### Integration Flow Details

#### Detailed Integration Flow

<figure><img src="https://www.mermaidchart.com/raw/9ac72f36-e946-489e-b968-df3ebea92970?theme=light&#x26;version=v0.1&#x26;format=svg" alt="" width="563"><figcaption><p>xChatbot and xFlow Integration Flow</p></figcaption></figure>

1. **Initialization and Request Construction**:
   * The xChatbot system prepares a request to the xFlow system whenever a user poses a question or provides a reply.
   * This request is structured according to the CloudEvent specification and includes key attributes, extensions, and data. The main content of the request is a JSON object containing the user's message. (See detail in [CloudEvent Request Structure](#cloudevent-request-structure))
2. **Sending the Request**:
   * The constructed CloudEvent request is sent from the xChatbot system to the xFlow system using the endpoint `https://xfai/api/aiQuery/query`.
   * The xFlow system acknowledges receipt of the request and begins processing.
3. **Processing the Request**:
   * The xFlow system identifies the appropriate agent workflow using the `agentcode` provided in the request.
   * The xFlow system processes the request based on the logic defined in the serverless workflow associated with the `agentcode`.
4. **Handling Different Response Scenarios**:
   * **Final Answer or Informative Response**:
     * If the AI agent determines that it can provide a final answer or needs to inform the user, xFlow prepares a response event. (See details in [CloudEvent Response Structure](#cloudevent-response-structure))
     * This response does not include `subconversationid` and `subconversationtype`.
     * The response is sent back to xChatbot via the webhook endpoint `https://xchatbot/api/aiagent/reply`.
   * **Request for More Information**:
     * If the AI agent requires additional information from the user, it initiates a new sub-conversation.
     * The response event includes newly created `subconversationid` and `subconversationtype`.  (See details in [CloudEvent Response Structure](#cloudevent-response-structure))
     * The response is sent back to xChatbot via the webhook endpoint `https://xchatbot/api/aiagent/reply`, and the AI agent waits for the user's reply.
5. **Subconversation Handling**:
   * When a new subconversation is initiated, xChatbot handles the user interaction until the required information is gathered.
   * The new messages are sent to xFlow using the same request format but include the `subconversationid` and `subconversationtype` to maintain the context.

### Data Structures and Properties

#### CloudEvent Request Structure

**Attributes**

<table><thead><tr><th>Property</th><th width="141">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>Unique identifier for the event</td></tr><tr><td>source</td><td>string</td><td>Event source URL</td></tr><tr><td>specversion</td><td>string</td><td>CloudEvent specification version</td></tr><tr><td>type</td><td>string</td><td>Event type (<code>com.a4b.xfai.ai.query.model.AskQuestionQuery</code>)</td></tr></tbody></table>

**Extensions**

<table><thead><tr><th>Property</th><th width="138">Type</th><th>Description</th></tr></thead><tbody><tr><td>agentcode</td><td>string</td><td>The agent code that xChatbot intends to use corresponds to the ID of a serverless workflow definition in the xFlow system.</td></tr><tr><td>conversationid</td><td>string</td><td>The unique identifier for the conversation between the chatbot and the user</td></tr><tr><td>subconversationid</td><td>string</td><td>(Optional) The unique identifier of the sub-conversation created by the AI agent to gather more information from the user.</td></tr><tr><td>subconversationtype</td><td>string</td><td>(Optional) The type of sub-conversation, used by the AI agent to classify the conversation.</td></tr><tr><td>{extension_key}</td><td>various</td><td><p>Other information that xChatbot wants to return in the response event will be added as extensions in the request CloudEvent. xFlow will include all of them in the response event with the convention:</p><ul><li>Added as extensions in the response event.</li><li>The extension name will be the original extension key prefixed by "req": <code>req{extension_key}</code></li></ul></td></tr></tbody></table>

**Data**

| Property | Type   | Description                                                    |
| -------- | ------ | -------------------------------------------------------------- |
| message  | string | String data representing the user's question or reply message. |

#### CloudEvent Response Structure

**Attributes**

| Property    | Type   | Description                                                        |
| ----------- | ------ | ------------------------------------------------------------------ |
| id          | string | Unique identifier for the event                                    |
| source      | string | Event source URL                                                   |
| specversion | string | CloudEvent specification version                                   |
| type        | string | Event type (`com.a4b.xfai.ai.query.model.JsonNodeAiQueryResponse`) |

**Extensions**

| Property                      | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| conversationid                | string  | The unique identifier for the conversation between the chatbot and the user.                                                                                                                                                                                                                                                                                                                          |
| subconversationid             | string  | (Optional) The unique identifier of the sub-conversation created by the AI agent to gather more information from the user.                                                                                                                                                                                                                                                                            |
| subconversationtype           | string  | (Optional) The type of sub-conversation, used by the AI agent to classify the conversation.                                                                                                                                                                                                                                                                                                           |
| req{original\_extension\_key} | various | <p>Other information that xChatbot wants to return in the response event will be added as extensions in the request CloudEvent. xFlow will include all of them in the response event with the convention:</p><ul><li>Added as extensions in the response event.</li><li>The extension name will be the original extension key prefixed by "req": <code>req{original\_extension\_key}</code></li></ul> |

**Data**

| Property | Type   | Description                                                                                                                             |
| -------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| message  | string | String data representing the response message from the AI agent to the user.                                                            |
| images   | array  | (Optional): A list of media contents included with the text message. Each media content structure defined in **Image Object Structure** |

**Image Object Structure**

| Property    | Type   | Description                                          |
| ----------- | ------ | ---------------------------------------------------- |
| uuid        | string | The unique identifier of media content.              |
| url         | string | The URL where xChatbot can access the media content. |
| base64Data  | string | The media content in base64 format.                  |
| mimeType    | string | The MIME type of the content.                        |
| description | string | The description of media content.                    |

### Example Requests and Responses

#### Example CloudEvent Request

**Request:**

```json
{
  "id": "12345",
  "source": "https://cloudevents.a4b.com/ms-chatbot",
  "specversion": "1.0",
  "type": "com.a4b.xfai.ai.query.model.AskQuestionQuery",
  "agentcode": "agent123",
  "conversationid": "conv001",
  "subconversationid": "subconv001",
  "subconversationtype": "USER_PROXY_AGENT",
  "data": {
    "message": "What is the weather like today?"
  }
}
```

#### Example CloudEvent Response (Final Answer)

**Response:**

```json
{
  "id": "54321",
  "source": "https://cloudevents.a4b.com/xplatform/xfai",
  "specversion": "1.0",
  "type": "com.a4b.xfai.ai.query.model.JsonNodeAiQueryResponse",
  "conversationid": "conv001",
  "data": {
    "message": "The weather is sunny today.",
    "images": [
      {
        "uuid": "5e388fd7-871f-4500-8c3b-b0363eb907c1",
        "url": "https://example.com/weather_image.jpg",
        "base64Data": null,
        "mimeType": "image/jpeg",
        "description": null
      }
    ]
  }
}
```

#### Example CloudEvent Response (Request for More Information)

**Response:**

```json
{
  "id": "54321",
  "source": "https://cloudevents.a4b.com/xplatform/xfai",
  "specversion": "1.0",
  "type": "com.a4b.xfai.ai.query.model.JsonNodeAiQueryResponse",
  "conversationid": "conv001",
  "subconversationid": "subconv002",
  "subconversationtype": "USER_PROXY_AGENT",
  "data": {
    "message": "Could you please specify the city for the weather information?"
  }
}
```

### xChatBot configuration

For each chatbot, xChatbot allows users to define the AI Agent to answer user questions. This AI Agent is configured with the integration details with xFlow, including the `xpApiKey` and `agentCode` to map to a serverless workflow that implements the detailed logic of the AI Agent. Below is a screenshot of the configuration screen in the xChatbot application:

<figure><img src="https://162762817-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2uToCxc5uYz2vl8eLUIH%2Fuploads%2Ff10Gg1FhtliBbQkvfsPB%2Fimage%20(1).png?alt=media&#x26;token=7eb98e05-c922-4b74-917e-8aa7bf20064a" alt="" width="563"><figcaption><p>AI Agent Configuration Screen</p></figcaption></figure>

By following this detailed documentation, developers can ensure a smooth integration between the xFlow system and the xChatbot system, enabling efficient orchestration and execution of AI-driven tasks while maintaining structured and standardized communication.
