# Conversations and Messages

### Send Message (Stream) <a href="#undefined" id="undefined"></a>

POST `/api/chatbots/{chatbotId}/completions/`

#### Parameters

| Parameter Name | Required | Type   | Description |
| -------------- | -------- | ------ | ----------- |
| `chatbotId`    | ✅        | string |             |

#### Request Body

**Request Parameters**

| Field                  | Type                                                                  | Required | Description                                                                                          |
| ---------------------- | --------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| conversation           | string (uuid)                                                         | No       | The unique identifier for the conversation. If empty, a new conversation will be created (optional). |
| message                | object (with 5 properties: content, contentPayload, queryMetadata...) | Yes      | The message content to be sent.                                                                      |
| message.content        | string                                                                | Yes      | The text content of the message.                                                                     |
| message.contentPayload | object                                                                | No       | Additional payload for the message, in JSON format (optional).                                       |
| message.queryMetadata  | object                                                                | No       | Query metadata, in JSON format (optional).                                                           |
| message.attachments    | array\[AttachmentInput]                                               | No       | A list of attachments for the message (optional).                                                    |
| message.sender         | string (uuid)                                                         | No       | The Contact ID of the sender (optional).                                                             |
| isStreaming            | boolean                                                               | No       | Whether to use streaming mode for the response. Defaults to false (optional).                        |

**Request Structure Example**

```typescript
{
  "conversation"?: string (uuid) // The unique identifier for the conversation. If empty, a new conversation will be created (optional).
  "message":  // The message content to be sent.
  {
    "content": string // The text content of the message.
    "contentPayload"?: object // Additional content payload for the message, in JSON format (optional).
    "queryMetadata"?: object // Query metadata, in JSON format (optional).
    "attachments"?: [ // List of attachments for the message (optional).
      {
        "id": string (uuid) // The unique identifier for the attachment.
        "type":  // Attachment type. Possible values: image, video (in development, not yet supported), audio, sticker (in development, not yet supported), other.

* `image` - Image
* `video` - Video
* `audio` - Audio
* `sticker` - Sticker
* `other` - Other
        {
        }
        "filename": string // The filename of the attachment.
        "file": string (uri) // The URL address of the attachment file.
      }
    ]
    "sender"?: string (uuid) // The Contact ID of the sender (optional).
  }
  "isStreaming"?: boolean // Whether to respond in streaming mode, defaults to false (optional).
}
```

**Request Example Value**

```json
{
  "conversation": "550e8400-e29b-41d4-a716-446655440000",
  "message": {
    "content": "Hello! I would like to get product information.",
    "contentPayload": null,
    "queryMetadata": null,
    "attachments": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "type": {},
        "filename": "document.pdf",
        "file": "https://example.com/file.jpg"
      }
    ],
    "sender": "550e8400-e29b-41d4-a716-446655440000"
  },
  "isStreaming": true
}
```

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X POST --no-buffer "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation": "550e8400-e29b-41d4-a716-446655440000",
    "message": {
      "content": "Hello! I would like to get some product information.",
      "contentPayload": null,
      "queryMetadata": null,
      "attachments": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "filename": "document.pdf",
          "file": "https://example.com/file.jpg"
        }
      ],
      "sender": "550e8400-e29b-41d4-a716-446655440000"
    },
    "isStreaming": true
  }'

# Please make sure to replace YOUR_API_KEY and verify the request data before execution.

# Note: This API returns streaming data, which can be handled in the following ways:
# Method 1: Use jq to process each JSON data chunk
# Example: curl -X POST --no-buffer "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation": "550e8400-e29b-41d4-a716-446655440000",
    "message": {
      "content": "Hello! I would like to get some product information.",
      "contentPayload": null,
      "queryMetadata": null,
      "attachments": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "filename": "document.pdf",
          "file": "https://example.com/file.jpg"
        }
      ],
      "sender": "550e8400-e29b-41d4-a716-446655440000"
    },
    "isStreaming": true
  }' | jq -r .

# Method 2: Use a pipe to write the output to a file
# Example: curl -X POST --no-buffer "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation": "550e8400-e29b-41d4-a716-446655440000",
    "message": {
      "content": "Hello! I would like to get some product information.",
      "contentPayload": null,
      "queryMetadata": null,
      "attachments": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "filename": "document.pdf",
          "file": "https://example.com/file.jpg"
        }
      ],
      "sender": "550e8400-e29b-41d4-a716-446655440000"
    },
    "isStreaming": true
  }' > response.json
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  responseType: 'stream' // Set to streaming response mode
};

// Request payload
const data = {
    "conversation": "550e8400-e29b-41d4-a716-446655440000",
    "message": {
      "content": "Hello! I would like to know more about the product.",
      "contentPayload": null,
      "queryMetadata": null,
      "attachments": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "filename": "document.pdf",
          "file": "https://example.com/file.jpg"
        }
      ],
      "sender": "550e8400-e29b-41d4-a716-446655440000"
    },
    "isStreaming": true
  };

axios.post("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/", data, config)
  .then(response => {
    console.log('Streaming response started:');
    
    let completeResponse = '';
    
    // Listen for data chunks
    response.data.on('data', (chunk) => {
      // Convert Buffer to string
      const chunkText = chunk.toString('utf8');
      console.log(`Received chunk: ${chunkText}`);
      
      completeResponse += chunkText;
      
      // Try to parse JSON data chunks
      try {
        // Check if it is a complete JSON object
        if (chunkText.trim().startsWith('{') && chunkText.trim().endsWith('}')) {
          const chunkData = JSON.parse(chunkText);
          console.log('Parsed chunk data:', JSON.stringify(chunkData, null, 2));
        }
      } catch (err) {
        // This might be a partial chunk that cannot be parsed as JSON
      }
    });
    
    // Handle stream end event
    response.data.on('end', () => {
      console.log('\nComplete accumulated response:');
      console.log(completeResponse);
    });
  })
  .catch(error => {
    console.error('Error occurred during streaming request:');
    console.error(error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

url = "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request payload
data = {
      "conversation": "550e8400-e29b-41d4-a716-446655440000",
      "message": {
        "content": "Hello! I would like to know more about the product information.",
        "contentPayload": None,
        "queryMetadata": None,
        "attachments": [
          {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "type": {},
            "filename": "document.pdf",
            "file": "https://example.com/file.jpg"
          }
        ],
        "sender": "550e8400-e29b-41d4-a716-446655440000"
      },
      "isStreaming": True  # Enable streaming mode
    }

# Process the response using streaming
try:
    with requests.post(url, json=data, headers=headers, stream=True) as response:
        print("Streaming response reception started:")
        
        # Variable to accumulate the complete response
        complete_response = ""
        
        # Receive data chunk by chunk
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:  # Filter out keep-alive new chunks
                # Try to decode
                chunk_text = chunk.decode('utf-8', errors='replace')
                print(f"Received chunk: {chunk_text}")
                
                complete_response += chunk_text
                
                # Try to parse the JSON data chunk
                try:
                    # Check if it is a complete JSON object
                    if chunk_text.strip().startswith('{') and chunk_text.strip().endswith('}'):
                        chunk_data = json.loads(chunk_text)
                        print(f"Parsed chunk data: {json.dumps(chunk_data, indent=2, ensure_ascii=False)}")
                except json.JSONDecodeError:
                    # This is a partial chunk and cannot be parsed as JSON alone
                    pass
        
        print("\nComplete accumulated response:")
        print(complete_response)
        
except Exception as e:
    print("An error occurred during the streaming request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    // Use streaming option
    $response = $client->post("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/completions/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => {
            "conversation": "550e8400-e29b-41d4-a716-446655440000",
            "message": {
                "content": "Hello! I would like to know more about the product information.",
                "contentPayload": null,
                "queryMetadata": null,
                "attachments": [
                    {
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "type": {},
                        "filename": "document.pdf",
                        "file": "https://example.com/file.jpg"
                    }
                ],
                "sender": "550e8400-e29b-41d4-a716-446655440000"
            },
            "isStreaming": true
        },
        'stream' => true  // Enable streaming
    ]);
    
    echo "Stream response receiving started:\n";
    
    // Variable to accumulate the complete response
    $completeResponse = "";
    
    // Get the response body as a stream
    $body = $response->getBody();
    
    // Read the stream data chunk by chunk
    while (!$body->eof()) {
        $chunk = $body->read(1024);  // Read 1KB of data
        
        if ($chunk) {
            echo "Received chunk: " . $chunk . "\n";
            
            $completeResponse .= $chunk;
            
            // Try to parse the JSON data chunk
            if (preg_match('/^\s*{.*}\s*$/', $chunk)) {
                try {
                    // Try to parse as JSON
                    $chunkData = json_decode($chunk, true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                        echo "Parsed chunk data:\n";
                        print_r($chunkData);
                    }
                } catch (Exception $parseError) {
                    // Cannot parse as JSON, might be a partial chunk
                }
            }
        }
    }
    
    echo "\nComplete accumulated response:\n";
    echo $completeResponse;
    
} catch (Exception $e) {
    echo 'Stream request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

| Status Code | Description                                                                                            |
| ----------- | ------------------------------------------------------------------------------------------------------ |
| 200         | Dialogue response content, or an event stream if streaming.                                            |
| 400         | Request parameter error. Possible reasons include: the Contact ID does not belong to the organization. |

***

### Send Message (Create) <a href="#undefined" id="undefined"></a>

POST `/api/messages/`

#### Request Body

**Request Parameters**

| Field             | Type                          | Required | Description |
| ----------------- | ----------------------------- | -------- | ----------- |
| conversation      | string (uuid)                 | Yes      |             |
| type              | string                        | No       |             |
| content           | string                        | No       |             |
| contentPayload    | object                        | No       |             |
| attachments       | array\[AttachmentCreateInput] | No       |             |
| canvas            | object                        | No       |             |
| canvas.name       | string                        | Yes      |             |
| canvas.canvasType | object                        | Yes      |             |
| canvas.title      | string                        | Yes      |             |
| canvas.content    | string                        | Yes      |             |
| queryMetadata     | object                        | No       |             |

**Request Structure Example**

```typescript
{
  "conversation": string (uuid)
  "type"?: string // Optional
  "content"?: string // Optional
  "contentPayload"?: object // Optional
  "attachments"?: [ // Optional
    {
      "type"?:  // Optional
      {
      }
      "filename": string
      "file": string (uri)
      "conversation"?: string (uuid) // Optional
    }
  ]
  "canvas"?: { // Optional
  {
    "name": string
    "canvasType": 
    {
    }
    "title": string
    "content": string
  }
  }
  "queryMetadata"?: object // Optional
}
```

**Request Example Value**

````json
{
  "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
  "sender": {
    "id": 2.992461161002561e+38,
    "name": "jessiekuo",
    "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
  },
  "type": "incoming",
  "content": "This is a test message",
  "contentPayload": {
    "content": "This is a test message",
    "items": [
      {
        "type": "text",
        "text": "This is a test message",
        "startTimestamp": null,
        "citations": []
      }
    ],
    "metadata": null
  },
  "feedback": "like",
  "createdAt": "1748314926000",
  "attachments": [],
  "citations": [],
  "citationNodes": [],
  "canvas": {
    "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
    "name": "system-architecture-diagram",
    "canvasType": "markdown",
    "title": "System Architecture Diagram",
    "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
    "createdAt": "1748314926000"
  }
}
````

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

````bash
# Call API Example (Shell)
curl -X POST "https://api.maiagent.ai/api/messages/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
    "sender": {
      "id": 2.992461161002561e+38,
      "name": "jessiekuo",
      "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
    },
    "type": "incoming",
    "content": "This is a test message",
    "contentPayload": {
      "content": "This is a test message",
      "items": [
        {
          "type": "text",
          "text": "This is a test message",
          "startTimestamp": null,
          "citations": []
        }
      ],
      "metadata": null
    },
    "feedback": "like",
    "createdAt": "1748314926000",
    "attachments": [],
    "citations": [],
    "citationNodes": [],
    "canvas": {
      "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
      "name": "system-architecture-diagram",
      "canvasType": "markdown",
      "title": "System Architecture Diagram",
      "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
      "createdAt": "1748314926000"
    }
  }'

# Please replace YOUR_API_KEY and verify the request data before execution.
````

{% endtab %}

{% tab title="JavaScript" %}

````javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request payload
const data = {
    "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
    "sender": {
      "id": 2.992461161002561e+38,
      "name": "jessiekuo",
      "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
    },
    "type": "incoming",
    "content": "This is a test message",
    "contentPayload": {
      "content": "This is a test message",
      "items": [
        {
          "type": "text",
          "text": "This is a test message",
          "startTimestamp": null,
          "citations": []
        }
      ],
      "metadata": null
    },
    "feedback": "like",
    "createdAt": "1748314926000",
    "attachments": [],
    "citations": [],
    "citationNodes": [],
    "canvas": {
      "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
      "name": "system-architecture-diagram",
      "canvasType": "markdown",
      "title": "System Architecture Diagram",
      "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
      "createdAt": "1748314926000"
    }
  };

axios.post("https://api.maiagent.ai/api/messages/", data, config)
  .then(response => {
    console.log('Successfully received response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred during the request:');
    console.error(error.response?.data || error.message);
  });
````

{% endtab %}

{% tab title="Python" %}

````python
import requests

url = "https://api.maiagent.ai/api/messages/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request payload
data = {
      "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
      "sender": {
        "id": 2.992461161002561e+38,
        "name": "jessiekuo",
        "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
      },
      "type": "incoming",
      "content": "This is a test message",
      "contentPayload": {
        "content": "This is a test message",
        "items": [
          {
            "type": "text",
            "text": "This is a test message",
            "startTimestamp": null,
            "citations": []
          }
        ],
        "metadata": null
      },
      "feedback": "like",
      "createdAt": "1748314926000",
      "attachments": [],
      "citations": [],
      "citationNodes": [],
      "canvas": {
        "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
        "name": "system-architecture-diagram",
        "canvasType": "markdown",
        "title": "System Architecture Diagram",
        "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
        "createdAt": "1748314926000"
      }
    }

response = requests.post(url, json=data, headers=headers)
try:
    print("Successfully received response:")
    print(response.json())
except Exception as e:
    print("Request failed:", e)
````

{% endtab %}

{% tab title="PHP" %}

````php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/messages/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => {
            "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
            "sender": {
                "id": 2.992461161002561e+38,
                "name": "jessiekuo",
                "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
            },
            "type": "incoming",
            "content": "This is a test message",
            "contentPayload": {
                "content": "This is a test message",
                "items": [
                    {
                        "type": "text",
                        "text": "This is a test message",
                        "startTimestamp": null,
                        "citations": []
                    }
                ],
                "metadata": null
            },
            "feedback": "like",
            "createdAt": "1748314926000",
            "attachments": [],
            "citations": [],
            "citationNodes": [],
            "canvas": {
                "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
                "name": "system-architecture-diagram",
                "canvasType": "markdown",
                "title": "System Architecture Diagram",
                "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
                "createdAt": "1748314926000"
            }
        }
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully received response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
````

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 201**

**Response Schema Example**

```typescript
{
  "id": string (uuid)
  "conversation": string (uuid)
  "sender": 
  {
    "id": string (uuid)
    "name": string
    "avatar": string
    "email"?: string (email) // Optional
    "phoneNumber"?: string // Optional
  }
  "type"?: string // Optional
  "content"?: string // Optional
  "contentPayload"?: object // Optional
  "feedback": 
  {
    "id": string (uuid)
    "type": 
    {
    }
    "suggestion"?: string // Optional
    "updatedAt": string (timestamp)
  }
  "createdAt": string (timestamp)
  "attachments"?: [ // Optional
    {
      "id": string (uuid)
      "type"?:  // Optional
      {
      }
      "filename": string
      "file": string (uri)
      "conversation"?: string (uuid) // Optional
    }
  ]
  "citations": [
    {
      "id": string (uuid)
      "filename": string // File name
      "file": string (uri) // File to upload
      "fileType": string
      "knowledgeBase"?:  // Optional
      {
        "id": string (uuid)
        "name": string
      }
      "size": integer
      "status": 
      {
      }
      "parser": {
      {
        "id": string (uuid)
        "name": string
        "provider": 
        {
        }
        "order"?: integer // Optional
      }
      }
      "labels"?: [ // Optional
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // Optional
      "createdAt": string (timestamp)
    }
  ]
  "citationNodes": [
    {
      "chatbotTextNode": {
      {
        "id": string (uuid)
        "charactersCount": integer
        "hitsCount": integer
        "text": string
        "updatedAt": string (timestamp)
        "filename": string
        "chatbotFile": string (uuid)
        "pageNumber": integer
      }
      }
      "score"?: number (double) // Optional
      "displayScore": integer
    }
  ]
  "canvas"?: { // Optional
  {
    "id": string (uuid)
    "name": string
    "canvasType": 
    {
    }
    "title": string
    "content": string
    "createdAt": string (timestamp)
  }
  }
  "queryMetadata"?: object // Optional
}
```

**Response Example Value**

````json
{
  "conversation": "c96a0fb9-d106-4b16-8706-3906533bafa2",
  "sender": {
    "id": 2.992461161002561e+38,
    "name": "jessiekuo",
    "avatar": "https://autox-media-dev.playma.app/static/images/default-user-avatar.png"
  },
  "type": "incoming",
  "content": "This is a test message",
  "contentPayload": {
    "content": "This is a test message",
    "items": [
      {
        "type": "text",
        "text": "This is a test message",
        "startTimestamp": null,
        "citations": []
      }
    ],
    "metadata": null
  },
  "feedback": "like",
  "createdAt": "1748314926000",
  "attachments": [],
  "citations": [],
  "citationNodes": [],
  "canvas": {
    "id": "034eecd7-e0f4-46e9-88cb-4fefdb5b7ddd",
    "name": "system-architecture-diagram",
    "canvasType": "markdown",
    "title": "System Architecture Diagram",
    "content": "```mermaid\ngraph TD\n    A[User] --> B[Frontend Interface]\n    B --> C[API Layer]\n    C --> D[Database]\n```",
    "createdAt": "1748314926000"
  }
}
````

***

### Create a new conversation <a href="#undefined" id="undefined"></a>

POST `/api/conversations/`

#### Request Body

**Parameters**

| Field   | Type          | Required | Description |
| ------- | ------------- | -------- | ----------- |
| webChat | string (uuid) | Yes      |             |

**Request Structure Example**

```typescript
{
  "webChat": string (uuid)
}
```

**Request Example Value**

```json
{
  "webChat": "550e8400-e29b-41d4-a716-446655440000"
}
```

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X POST "https://api.maiagent.ai/api/conversations/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "webChat": "550e8400-e29b-41d4-a716-446655440000"
  }'

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request payload
const data = {
    "webChat": "550e8400-e29b-41d4-a716-446655440000"
  };

axios.post("https://api.maiagent.ai/api/conversations/", data, config)
  .then(response => {
    console.log('Successfully received response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/conversations/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request payload
data = {
      "webChat": "550e8400-e29b-41d4-a716-446655440000"
    }

response = requests.post(url, json=data, headers=headers)
try:
    print("Successfully received response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/conversations/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => {
            "webChat": "550e8400-e29b-41d4-a716-446655440000"
        }
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully received response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 201**

**Response Schema Example**

```typescript
{
  "id": string (uuid)
  "contact": { // Lightweight Contact Serializer for Conversation List view

Only includes fields necessary for the List view, removes inboxes and mcp_credentials
to avoid N+1 query issues
  {
    "id": string (uuid)
    "name": string
    "avatar"?: string (uri) // Optional
    "sourceId"?: string // Optional
  }
  }
  "inbox": {
  {
    "id": string (uuid)
    "name": string
    "channelType": string (enum: line, telegram, web, messenger) // * `line` - LINE
* `telegram` - Telegram
* `web` - Web
* `messenger` - Messenger
    "unreadConversationsCount"?: integer // Optional
    "signAuth"?:  // Optional
    {
      "id": string (uuid)
      "signSource": string (uuid)
      "signParams": {
      {
        "keycloak": 
        {
          "clientId": string
          "url": string
          "realm": string
        }
        "line": 
        {
          "liffId": string
        }
        "ad": 
        {
          "saml": string
        }
      }
      }
    }
  }
  }
  "title": string
  "lastMessage"?: { // Optional
  {
    "id": string (uuid)
    "type"?: string // Optional
    "content"?: string // Optional
    "contentPayload"?: object // Optional
    "feedback": 
    {
      "id": string (uuid)
      "type": 
      {
      }
      "suggestion"?: string // Optional
      "updatedAt": string (timestamp)
    }
    "createdAt": string (timestamp)
    "queryMetadata"?: object // Optional
  }
  }
  "lastMessageCreatedAt": string (timestamp)
  "unreadMessagesCount": integer
  "autoReplyEnabled": boolean
  "isAutoReplyNow": boolean
  "lastReadAt": string (timestamp)
  "createdAt": string (timestamp)
  "isGroupChat": boolean
  "enableGroupMention"?: boolean // Optional
  "enableLoadingAnimation"?: boolean // Optional
  "queryMetadata"?: object // Optional
  "toolMask"?: object // Records the enabled/disabled status of each tool {tool_id: bool} (Optional)
  "llm": string (uuid)
  "ipAddress": string
  "ipRecordedAt": string (timestamp)
}
```

**Response Example Value**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "contact": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response String",
    "avatar": "https://example.com/file.jpg",
    "sourceId": "Response String"
  },
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response String",
    "channelType": "line",
    "unreadConversationsCount": 456,
    "signAuth": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "signSource": "550e8400-e29b-41d4-a716-446655440000",
      "signParams": {
        "keycloak": {
          "clientId": "Response String",
          "url": "Response String",
          "realm": "Response String"
        },
        "line": {
          "liffId": "Response String"
        },
        "ad": {
          "saml": "Response String"
        }
      }
    }
  },
  "title": "Response String",
  "lastMessage": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "Response String",
    "content": "Response String",
    "contentPayload": null,
    "feedback": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "type": {},
      "suggestion": "Response String",
      "updatedAt": "Response String"
    },
    "createdAt": "Response String",
    "queryMetadata": null
  },
  "lastMessageCreatedAt": "Response String",
  "unreadMessagesCount": 456,
  "autoReplyEnabled": false,
  "isAutoReplyNow": false,
  "lastReadAt": "Response String",
  "createdAt": "Response String",
  "isGroupChat": false,
  "enableGroupMention": false,
  "enableLoadingAnimation": false,
  "queryMetadata": null,
  "toolMask": null,
  "llm": "550e8400-e29b-41d4-a716-446655440000",
  "ipAddress": "Response String",
  "ipRecordedAt": "Response String"
}
```

***

### Get Message List <a href="#undefined" id="undefined"></a>

GET `/api/messages/`

#### Parameters

| Parameter Name | Required | Type    | Description                           |
| -------------- | -------- | ------- | ------------------------------------- |
| `conversation` | ✅        | string  | Conversation ID                       |
| `cursor`       | ❌        | string  | The pagination cursor value.          |
| `pageSize`     | ❌        | integer | Number of results to return per page. |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X GET "https://api.maiagent.ai/api/messages/?conversation=example&cursor=example&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/messages/?conversation=example&cursor=example&pageSize=1", config)
  .then(response => {
    console.log('Successfully received response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/messages/?conversation=example&cursor=example&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully retrieved response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/messages/?conversation=example&cursor=example&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully retrieved response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    {
      "id": string (uuid)
      "conversation": string (uuid)
      "sender": 
      {
        "id": string (uuid)
        "name": string
        "avatar": string
        "email"?: string (email) // Optional
        "phoneNumber"?: string // Optional
      }
      "type"?: string // Optional
      "content"?: string // Optional
      "contentPayload"?: object // Optional
      "feedback": 
      {
        "id": string (uuid)
        "type": 
        {
        }
        "suggestion"?: string // Optional
        "updatedAt": string (timestamp)
      }
      "createdAt": string (timestamp)
      "attachments"?: [ // Optional
        {
          "id": string (uuid)
          "type"?:  // Optional
          {
          }
          "filename": string
          "file": string (uri)
          "conversation"?: string (uuid) // Optional
        }
      ]
      "citations": [
        {
          "id": string (uuid)
          "filename": string // File name
          "file": string (uri) // File to upload
          "fileType": string
          "knowledgeBase"?:  // Optional
          {
            "id": string (uuid)
            "name": string
          }
          "size": integer
          "status": 
          {
          }
          "parser": {
          {
            "id": string (uuid)
            "name": string
            "provider": 
            {
            }
            "order"?: integer // Optional
          }
          }
          "labels"?: [ // Optional
            {
              "id": string (uuid)
              "name": string
            }
          ]
          "rawUserDefineMetadata"?: object // Optional
          "createdAt": string (timestamp)
        }
      ]
      "citationNodes": [
        {
          "chatbotTextNode": {
          {
            "id": string (uuid)
            "charactersCount": integer
            "hitsCount": integer
            "text": string
            "updatedAt": string (timestamp)
            "filename": string
            "chatbotFile": string (uuid)
            "pageNumber": integer
          }
          }
          "score"?: number (double) // Optional
          "displayScore": integer
        }
      ]
      "canvas"?: { // Optional
      {
        "id": string (uuid)
        "name": string
        "canvasType": 
        {
        }
        "title": string
        "content": string
        "createdAt": string (timestamp)
      }
      }
      "queryMetadata"?: object // Optional
    }
  ]
}
```

**Response Example Value**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "conversation": "550e8400-e29b-41d4-a716-446655440000",
      "sender": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String",
        "avatar": "Response String",
        "email": "response@example.com",
        "phoneNumber": "Response String"
      },
      "type": "Response String",
      "content": "Response String",
      "contentPayload": null,
      "feedback": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "type": {},
        "suggestion": "Response String",
        "updatedAt": "Response String"
      },
      "createdAt": "Response String",
      "attachments": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "filename": "Response String",
          "file": "https://example.com/file.jpg",
          "conversation": "550e8400-e29b-41d4-a716-446655440000"
        }
      ],
      "citations": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "filename": "Response String",
          "file": "https://example.com/file.jpg",
          "fileType": "Response String",
          "knowledgeBase": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "Response String"
          },
          "size": 456,
          "status": {},
          "parser": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "Response String",
            "provider": {},
            "order": 456
          },
          "labels": [
            {
              "id": "550e8400-e29b-41d4-a716-446655440000",
              "name": "Response String"
            }
          ],
          "rawUserDefineMetadata": null,
          "createdAt": "Response String"
        }
      ],
      "citationNodes": [
        {
          "chatbotTextNode": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "charactersCount": 456,
            "hitsCount": 456,
            "text": "Response String",
            "updatedAt": "Response String",
            "filename": "Response String",
            "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
            "pageNumber": 456
          },
          "score": 456,
          "displayScore": 456
        }
      ],
      "canvas": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String",
        "canvasType": {},
        "title": "Response String",
        "content": "Response String",
        "createdAt": "Response String"
      },
      "queryMetadata": null
    }
  ]
}
```

***

### Get a specific message <a href="#undefined" id="undefined"></a>

GET `/api/messages/{id}/`

#### Parameters

| Parameter Name | Required | Type   | Description                             |
| -------------- | -------- | ------ | --------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this message. |
| `conversation` | ✅        | string | Conversation ID                         |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# Call API Example (Shell)
curl -X GET "https://api.maiagent.ai/api/messages/550e8400-e29b-41d4-a716-446655440000/?conversation=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/messages/550e8400-e29b-41d4-a716-446655440000/?conversation=example", config)
  .then(response => {
    console.log('Successfully retrieved response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/messages/550e8400-e29b-41d4-a716-446655440000/?conversation=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully retrieved response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/messages/550e8400-e29b-41d4-a716-446655440000/?conversation=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully retrieved response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "id": string (uuid)
  "conversation": string (uuid)
  "sender": 
  {
    "id": string (uuid)
    "name": string
    "avatar": string
    "email"?: string (email) // Optional
    "phoneNumber"?: string // Optional
  }
  "type"?: string // Optional
  "content"?: string // Optional
  "contentPayload"?: object // Optional
  "feedback": 
  {
    "id": string (uuid)
    "type": 
    {
    }
    "suggestion"?: string // Optional
    "updatedAt": string (timestamp)
  }
  "createdAt": string (timestamp)
  "attachments"?: [ // Optional
    {
      "id": string (uuid)
      "type"?:  // Optional
      {
      }
      "filename": string
      "file": string (uri)
      "conversation"?: string (uuid) // Optional
    }
  ]
  "citations": [
    {
      "id": string (uuid)
      "filename": string // File name
      "file": string (uri) // File to upload
      "fileType": string
      "knowledgeBase"?:  // Optional
      {
        "id": string (uuid)
        "name": string
      }
      "size": integer
      "status": 
      {
      }
      "parser": {
      {
        "id": string (uuid)
        "name": string
        "provider": 
        {
        }
        "order"?: integer // Optional
      }
      }
      "labels"?: [ // Optional
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // Optional
      "createdAt": string (timestamp)
    }
  ]
  "citationNodes": [
    {
      "chatbotTextNode": {
      {
        "id": string (uuid)
        "charactersCount": integer
        "hitsCount": integer
        "text": string
        "updatedAt": string (timestamp)
        "filename": string
        "chatbotFile": string (uuid)
        "pageNumber": integer
      }
      }
      "score"?: number (double) // Optional
      "displayScore": integer
    }
  ]
  "canvas"?: { // Optional
  {
    "id": string (uuid)
    "name": string
    "canvasType": 
    {
    }
    "title": string
    "content": string
    "createdAt": string (timestamp)
  }
  }
  "queryMetadata"?: object // Optional
}
```

**Response Example Value**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "conversation": "550e8400-e29b-41d4-a716-446655440000",
  "sender": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response String",
    "avatar": "Response String",
    "email": "response@example.com",
    "phoneNumber": "Response String"
  },
  "type": "Response String",
  "content": "Response String",
  "contentPayload": null,
  "feedback": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "type": {},
    "suggestion": "Response String",
    "updatedAt": "Response String"
  },
  "createdAt": "Response String",
  "attachments": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "type": {},
      "filename": "Response String",
      "file": "https://example.com/file.jpg",
      "conversation": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "citations": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "filename": "Response String",
      "file": "https://example.com/file.jpg",
      "fileType": "Response String",
      "knowledgeBase": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String"
      },
      "size": 456,
      "status": {},
      "parser": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String",
        "provider": {},
        "order": 456
      },
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "Response String"
        }
      ],
      "rawUserDefineMetadata": null,
      "createdAt": "Response String"
    }
  ],
  "citationNodes": [
    {
      "chatbotTextNode": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "charactersCount": 456,
        "hitsCount": 456,
        "text": "Response String",
        "updatedAt": "Response String",
        "filename": "Response String",
        "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
        "pageNumber": 456
      },
      "score": 456,
      "displayScore": 456
    }
  ],
  "canvas": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response String",
    "canvasType": {},
    "title": "Response String",
    "content": "Response String",
    "createdAt": "Response String"
  },
  "queryMetadata": null
}
```

***

### Get Conversation List <a href="#undefined" id="undefined"></a>

GET `/api/conversations/`

#### Parameters

| Parameter Name | Required | Type    | Description                           |
| -------------- | -------- | ------- | ------------------------------------- |
| `cursor`       | ❌        | string  | The pagination cursor value.          |
| `inbox`        | ✅        | string  | Conversation platform ID              |
| `keyword`      | ❌        | string  | Keyword search                        |
| `pageSize`     | ❌        | integer | Number of results to return per page. |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# Call API Example (Shell)
curl -X GET "https://api.maiagent.ai/api/conversations/?cursor=example&inbox=example&keyword=example&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/conversations/?cursor=example&inbox=example&keyword=example&pageSize=1", config)
  .then(response => {
    console.log('Successfully retrieved response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/conversations/?cursor=example&inbox=example&keyword=example&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully retrieved response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/conversations/?cursor=example&inbox=example&keyword=example&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully retrieved response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'An error occurred during the request: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    {
      "id": string (uuid)
      "contact": { // Lightweight Contact Serializer, for Conversation List view

Only includes necessary fields for List view, removes inboxes and mcp_credentials
to avoid N+1 query issues
      {
        "id": string (uuid)
        "name": string
        "avatar"?: string (uri) // Optional
        "sourceId"?: string // Optional
      }
      }
      "inbox": {
      {
        "id": string (uuid)
        "name": string
        "channelType": string (enum: line, telegram, web, messenger) // * `line` - LINE
* `telegram` - Telegram
* `web` - Web
* `messenger` - Messenger
        "unreadConversationsCount"?: integer // Optional
        "signAuth"?:  // Optional
        {
          "id": string (uuid)
          "signSource": string (uuid)
          "signParams": {
          {
            "keycloak": 
            {
              "clientId": string
              "url": string
              "realm": string
            }
            "line": 
            {
              "liffId": string
            }
            "ad": 
            {
              "saml": string
            }
          }
          }
        }
      }
      }
      "title": string
      "lastMessage"?: { // Optional
      {
        "id": string (uuid)
        "type"?: string // Optional
        "content"?: string // Optional
        "contentPayload"?: object // Optional
        "feedback": 
        {
          "id": string (uuid)
          "type": 
          {
          }
          "suggestion"?: string // Optional
          "updatedAt": string (timestamp)
        }
        "createdAt": string (timestamp)
        "queryMetadata"?: object // Optional
      }
      }
      "lastMessageCreatedAt": string (timestamp)
      "unreadMessagesCount": integer
      "autoReplyEnabled": boolean
      "isAutoReplyNow": boolean
      "lastReadAt": string (timestamp)
      "createdAt": string (timestamp)
      "isGroupChat": boolean
      "enableGroupMention"?: boolean // Optional
      "enableLoadingAnimation"?: boolean // Optional
      "queryMetadata"?: object // Optional
      "toolMask"?: object // Records the enabled/disabled status of each tool {tool_id: bool} (Optional)
      "llm": string (uuid)
      "ipAddress": string
      "ipRecordedAt": string (timestamp)
    }
  ]
}
```

**Response Example Value**

```json
{
  "next": "http://api.example.org/accounts/?cursor=cD00ODY%3D\"",
  "previous": "http://api.example.org/accounts/?cursor=cj0xJnA9NDg3",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "contact": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String",
        "avatar": "https://example.com/file.jpg",
        "sourceId": "Response String"
      },
      "inbox": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response String",
        "channelType": "line",
        "unreadConversationsCount": 456,
        "signAuth": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "signSource": "550e8400-e29b-41d4-a716-446655440000",
          "signParams": {
            "keycloak": {
              "clientId": "Response String",
              "url": "Response String",
              "realm": "Response String"
            },
            "line": {
              "liffId": "Response String"
            },
            "ad": {
              "saml": "Response String"
            }
          }
        }
      },
      "title": "Response String",
      "lastMessage": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "type": "Response String",
        "content": "Response String",
        "contentPayload": null,
        "feedback": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "type": {},
          "suggestion": "Response String",
          "updatedAt": "Response String"
        },
        "createdAt": "Response String",
        "queryMetadata": null
      },
      "lastMessageCreatedAt": "Response String",
      "unreadMessagesCount": 456,
      "autoReplyEnabled": false,
      "isAutoReplyNow": false,
      "lastReadAt": "Response String",
      "createdAt": "Response String",
      "isGroupChat": false,
      "enableGroupMention": false,
      "enableLoadingAnimation": false,
      "queryMetadata": null,
      "toolMask": null,
      "llm": "550e8400-e29b-41d4-a716-446655440000",
      "ipAddress": "Response String",
      "ipRecordedAt": "Response String"
    }
  ]
}
```

***

### Get a specific conversation <a href="#undefined" id="undefined"></a>

GET `/api/conversations/{id}/`

#### Parameters

| Parameter Name | Required | Type   | Description                                  |
| -------------- | -------- | ------ | -------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this conversation. |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X GET "https://api.maiagent.ai/api/conversations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/conversations/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('Successfully retrieved response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/conversations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully got response:")
    print(response.json())
except Exception as e:
    print("Request failed:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/conversations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully retrieved response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "id": string (uuid)
  "contact": { // Lightweight Contact Serializer for Conversation List view

Only includes fields necessary for the List view, removes inboxes and mcp_credentials
to avoid N+1 query issues
  {
    "id": string (uuid)
    "name": string
    "avatar"?: string (uri) // Optional
    "sourceId"?: string // Optional
  }
  }
  "inbox": {
  {
    "id": string (uuid)
    "name": string
    "channelType": string (enum: line, telegram, web, messenger) // * `line` - LINE
* `telegram` - Telegram
* `web` - Web
* `messenger` - Messenger
    "unreadConversationsCount"?: integer // Optional
    "signAuth"?:  // Optional
    {
      "id": string (uuid)
      "signSource": string (uuid)
      "signParams": {
      {
        "keycloak": 
        {
          "clientId": string
          "url": string
          "realm": string
        }
        "line": 
        {
          "liffId": string
        }
        "ad": 
        {
          "saml": string
        }
      }
      }
    }
  }
  }
  "title": string
  "lastMessage"?: { // Optional
  {
    "id": string (uuid)
    "type"?: string // Optional
    "content"?: string // Optional
    "contentPayload"?: object // Optional
    "feedback": 
    {
      "id": string (uuid)
      "type": 
      {
      }
      "suggestion"?: string // Optional
      "updatedAt": string (timestamp)
    }
    "createdAt": string (timestamp)
    "queryMetadata"?: object // Optional
  }
  }
  "lastMessageCreatedAt": string (timestamp)
  "unreadMessagesCount": integer
  "autoReplyEnabled": boolean
  "isAutoReplyNow": boolean
  "lastReadAt": string (timestamp)
  "createdAt": string (timestamp)
  "isGroupChat": boolean
  "enableGroupMention"?: boolean // Optional
  "enableLoadingAnimation"?: boolean // Optional
  "queryMetadata"?: object // Optional
  "toolMask"?: object // Records the enabled/disabled status of each tool {tool_id: bool} (Optional)
  "llm": string (uuid)
  "ipAddress": string
  "ipRecordedAt": string (timestamp)
}
```

**Response Example Value**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "contact": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response string",
    "avatar": "https://example.com/file.jpg",
    "sourceId": "Response string"
  },
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response string",
    "channelType": "line",
    "unreadConversationsCount": 456,
    "signAuth": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "signSource": "550e8400-e29b-41d4-a716-446655440000",
      "signParams": {
        "keycloak": {
          "clientId": "Response string",
          "url": "Response string",
          "realm": "Response string"
        },
        "line": {
          "liffId": "Response string"
        },
        "ad": {
          "saml": "Response string"
        }
      }
    }
  },
  "title": "Response string",
  "lastMessage": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "Response string",
    "content": "Response string",
    "contentPayload": null,
    "feedback": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "type": {},
      "suggestion": "Response string",
      "updatedAt": "Response string"
    },
    "createdAt": "Response string",
    "queryMetadata": null
  },
  "lastMessageCreatedAt": "Response string",
  "unreadMessagesCount": 456,
  "autoReplyEnabled": false,
  "isAutoReplyNow": false,
  "lastReadAt": "Response string",
  "createdAt": "Response string",
  "isGroupChat": false,
  "enableGroupMention": false,
  "enableLoadingAnimation": false,
  "queryMetadata": null,
  "toolMask": null,
  "llm": "550e8400-e29b-41d4-a716-446655440000",
  "ipAddress": "Response string",
  "ipRecordedAt": "Response string"
}
```

***

### Get AI Assistant Conversation Records <a href="#ai" id="ai"></a>

GET `/api/chatbots/{chatbotPk}/records/`

#### Parameters

| Parameter Name | Required | Type    | Description                                                 |
| -------------- | -------- | ------- | ----------------------------------------------------------- |
| `chatbotPk`    | ✅        | string  | A UUID string identifying this Chatbot ID                   |
| `botMessage`   | ❌        | string  | Filter for bot replies containing specific content          |
| `endDate`      | ✅        | string  | End date (required, format: YYYY-MM-DD, e.g., 2025-01-31)   |
| `page`         | ❌        | integer | A page number within the paginated result set.              |
| `pageSize`     | ❌        | integer | Number of results to return per page.                       |
| `startDate`    | ✅        | string  | Start date (required, format: YYYY-MM-DD, e.g., 2025-01-01) |
| `userMessage`  | ❌        | string  | Filter for user messages containing specific content        |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X GET "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/?botMessage=example&endDate=example&page=1&pageSize=1&startDate=example&userMessage=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and check the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/?botMessage=example&endDate=example&page=1&pageSize=1&startDate=example&userMessage=example", config)
  .then(response => {
    console.log('Successfully retrieved response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/?botMessage=example&endDate=example&page=1&pageSize=1&startDate=example&userMessage=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully retrieved response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/?botMessage=example&endDate=example&page=1&pageSize=1&startDate=example&userMessage=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully received response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    {
      "id": string (uuid)
      "senderName": string // Returns the name of the user message sender
      "feedback": 
      {
        "id": string (uuid)
        "type": 
        {
        }
        "suggestion"?: string // Optional
        "updatedAt": string (timestamp)
      }
      "inputMessage": string
      "condenseMessage": string // The user's message, refined after synthesizing chat history and context
      "outputMessage": string
      "faithfulnessScore": number (double) // Determines if the chatbot's response aligns with the database content and avoids hallucination
      "displayFaithfulnessScore": integer
      "answerRelevancyScore": number (double) // Determines if the chatbot's response is relevant to the user's question
      "displayAnswerRelevancyScore": integer
      "contextPrecisionScore": number (double) // Determines if the chatbot's response is relevant to the reference material
      "displayContextPrecisionScore": integer
      "answerCorrectnessScore": number (double) // Determines if the chatbot's response is correct (requires a ground truth answer)
      "displayAnswerCorrectnessScore": integer
      "answerSimilarityScore": number (double) // Determines if the chatbot's response is similar to the ground truth answer
      "displayAnswerSimilarityScore": integer
      "contextRecallScore": number (double) // Determines if the chatbot's response can recall relevant information from the reference material
      "displayContextRecallScore": integer
      "replyTime": string
      "createdAt": string (timestamp)
      "error": string // Stores error messages from the execution process
      "processingTime": object // Returns time statistics for each processing stage
      "usage": object // Returns usage statistics, including word count and token count
      "citationNodes": [
        {
          "id": string
          "text": string
        }
      ]
      "context": string
    }
  ]
}
```

**Response Example Value**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "senderName": "Response String",
      "feedback": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "type": {},
        "suggestion": "Response String",
        "updatedAt": "Response String"
      },
      "inputMessage": "Response String",
      "condenseMessage": "Response String",
      "outputMessage": "Response String",
      "faithfulnessScore": 456,
      "displayFaithfulnessScore": 456,
      "answerRelevancyScore": 456,
      "displayAnswerRelevancyScore": 456,
      "contextPrecisionScore": 456,
      "displayContextPrecisionScore": 456,
      "answerCorrectnessScore": 456,
      "displayAnswerCorrectnessScore": 456,
      "answerSimilarityScore": 456,
      "displayAnswerSimilarityScore": 456,
      "contextRecallScore": 456,
      "displayContextRecallScore": 456,
      "replyTime": "Response String",
      "createdAt": "Response String",
      "error": "Response String",
      "processingTime": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response Example Name",
        "description": "Response Example Description"
      },
      "usage": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Response Example Name",
        "description": "Response Example Description"
      },
      "citationNodes": [
        {
          "id": "Response String",
          "text": "Response String"
        }
      ],
      "context": "Response String"
    }
  ]
}
```

***

### Export Chat Records as Excel File <a href="#excel" id="excel"></a>

GET `/api/chatbots/{chatbotPk}/records/export-excel/`

#### Parameters

| Parameter Name | Required | Type   | Description                                                 |
| -------------- | -------- | ------ | ----------------------------------------------------------- |
| `chatbotPk`    | ✅        | string | A UUID string identifying this Chatbot ID                   |
| `botMessage`   | ❌        | string | Filter bot messages containing specific content             |
| `endDate`      | ✅        | string | End date (Required, format: YYYY-MM-DD, e.g., 2025-01-31)   |
| `startDate`    | ✅        | string | Start date (Required, format: YYYY-MM-DD, e.g., 2025-01-01) |
| `userMessage`  | ❌        | string | Filter user messages containing specific content            |

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API Call Example (Shell)
curl -X GET "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/export-excel/?botMessage=example&endDate=example&startDate=example&userMessage=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Please replace YOUR_API_KEY and verify the request data before execution.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/export-excel/?botMessage=example&endDate=example&startDate=example&userMessage=example", config)
  .then(response => {
    console.log('Successfully received response:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/export-excel/?botMessage=example&endDate=example&startDate=example&userMessage=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Successfully received response:")
    print(response.json())
except Exception as e:
    print("An error occurred during the request:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/chatbots/550e8400-e29b-41d4-a716-446655440000/records/export-excel/?botMessage=example&endDate=example&startDate=example&userMessage=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Successfully got response:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

| Status Code | Description         |
| ----------- | ------------------- |
| 200         | Excel file download |

***


---

# 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://docs.maiagent.ai/api/api-doc-en/api-reference/dui-hua-he-xun-xi.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.
