> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/en/api-integration/conversations-and-messages.md).

# Create Conversations and Messages

Create conversations and send messages through the API, then receive Agent replies via Webhook; see the API documentation for field definitions.

Integrating conversations through the API takes two steps: create a conversation to obtain its ID, then send messages to that conversation. Agent replies are pushed to you via Webhook. This page explains the workflow and considerations; refer to the API documentation for each field's type and required status.

## Create a Conversation <a href="#create-conversation" id="create-conversation"></a>

Create a new conversation.

**Endpoint:** `https://api.maiagent.ai/api/v1/conversations/`

**Request method:** `POST`

**Request headers:**

```
Authorization: Api-Key <your API key>
Content-Type: application/json
```

**Request body:**

`webChat` is required (Web Chat ID: in the admin console, go to <mark style="color:blue;">Customer Service Conversations</mark> → <mark style="color:blue;">Conversation Platforms</mark> → edit the Agent's API platform → <mark style="color:blue;">Integration and Login</mark> → <mark style="color:blue;">Webhook Settings</mark>, then copy it from the <mark style="color:blue;">API Information</mark> card at the bottom. See [Basic Conversation Platform Settings](https://docs.maiagent.ai/build/conversation-settings/platform-settings/basic-settings#web-chat-id) in the user manual. You can also retrieve it with `GET /api/v1/web-chats/`). To associate the conversation with a specific visitor, also include `contact` (the contact ID, which must belong to the same conversation platform; see [Contact Identity Synchronization and Token Updates](/tech/en/serve/contacts/contact-credentials-sync.md) for how to obtain it). If you omit `contact`, the conversation's contact is the user who owns the API key; all conversations created with that key belong to this contact. See [Create a New Conversation](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-create) in the API documentation for field definitions.

**Request example:**

```python
import requests

response = requests.post(
    url='https://api.maiagent.ai/api/v1/conversations/',
    headers={
        'Authorization': 'Api-Key <your API key>'
    },
    json={
        'webChat': 'your Web Chat ID'
    }
)
```

**Response body:**

For message integration, save the response's `id` (conversation ID): use it to retrieve all messages in the conversation and identify which conversation a message Webhook belongs to. The conversation platform ID needed to configure the Webhook is in `inbox.id`. See [Create a New Conversation](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-create) in the API documentation for response fields.

***

## Send a Message <a href="#send-message" id="send-message"></a>

Create a new message

**Endpoint:** `https://api.maiagent.ai/api/v1/messages/`

**Request method:** `POST`

**Request headers:**

```
Authorization: Api-Key your API key
Content-Type: application/json
```

**Request body:**

`conversation` (conversation ID) is required. Put the message text in `content` and attachments in `attachments` (an empty array by default). See [Send a Message (Create)](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-create) in the API documentation for field definitions.

Create attachment objects before including them in the request; see [Presigned File Upload Mode: Create Message Attachments](/tech/en/api-integration/api_knowledge.md#message-attachments). Place the objects returned when creating attachments (`type`, `filename`, `file`) into `attachments` unchanged.

**Request example:**

Python example

```python
import requests

response = requests.post(
    url='https://api.maiagent.ai/api/v1/messages/',
    headers={
        'Authorization': 'Api-Key your API key'
    },
    json={
        'conversation': 'conversation ID',
        'content': 'message content',
        'attachments': [
            {
                "id": "attachment ID",
                "type": "attachment type",
                "filename": "attachment filename",
                "file": "attachment file URL"
            }
        ]
    }
)

```

cURL example

```bash
curl -X POST 'https://api.maiagent.ai/api/v1/messages/' \
-H 'Authorization: Api-Key your API key' \
-H 'Content-Type: application/json' \
-d '{
    "conversation": "conversation ID",
    "content": "message content",
    "attachments": [
        {
            "id": "attachment ID",
            "type": "attachment type",
            "filename": "attachment filename",
            "file": "attachment file URL"
        }
    ]
}'

```

**Response format:**

Receiving a response means the message was created successfully. The response contains the newly created message, without the Agent's reply; replies are pushed via Webhook. See [Webhook](/tech/en/serve/webhook.md). See [Send a Message (Create)](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-create) in the API documentation for response fields.

**Response example:**

```json
{
    "id": "2491074a-6d23-4289-af45-caa12531420e",
    "conversation": "8e44604a-8278-4c96-96b5-3e5a0548d738",
    "sender": {
        "id": "f45d5b80-d44a-416e-885a-d720e2f7cb5b",
        "name": "AI Customer Service",
        "avatar": "https://whizchat-media-prod-django.playma.app/media/users/user/bb5f49ef-31ae-4ccf-bc0e-6fe8c5001721.png"
    },
    "type": "incoming",
    "content": "Hello",
    "feedback": null,
    "createdAt": "1732495353000",
    "attachments": [],
    "citations": [],
    "citationNodes": []
}
```

### Message Types <a href="#message-types" id="message-types"></a>

* `incoming`: Received messages
* `outgoing`: Sent messages

### Images in Message Content <a href="#images-in-content" id="images-in-content"></a>

`content` is plain text. The platform stores it unchanged and does not parse URLs within it. There are two ways to present images in a conversation:

| Method                                            | Use case                                                         | Description                                                                                                                                                                                                                      |
| ------------------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `attachments`                                     | Users upload images for Agent recognition and save them as files | The platform handles storage and expiration management. This is the officially supported approach; see [Presigned File Upload Mode](/tech/en/api-integration/api_knowledge.md#message-attachments) for how to create attachments |
| Markdown image syntax `![description](https://…)` | Agent replies or tool results need to display an external image  | Web Chat and MaiGPT render messages in Markdown. The browser fetches the image directly from the URL, which is preserved unchanged, including the query string                                                                   |

When using Markdown images, keep the following in mind:

* Images are loaded by **the user's browser**. The URL must be publicly accessible without authentication; the platform does not download or store a copy of the image for you.
* Signed URLs that expire (such as Azure SAS or S3 presigned URLs) are not updated after being written into messages. Once they expire, images in older messages can no longer be displayed. For long-term access, provide a URL that does not expire, or have your system provide a fixed URL that redirects.
* Use Markdown syntax rather than relying on HTML tags. HTML handling depends on the frontend renderer and is outside the contract.
* The `imageUrl` in response citation nodes refers to an image in a knowledge base passage and is unrelated to images in message content.
* For the two-step workflow when a custom API tool returns an image URL, see [API Tool Engineering Guide: Returning Responses to the Model](/tech/en/api-integration/api-tool-engineering-guide.md#response-to-model).

***

## Message Feedback <a href="#message-feedback" id="message-feedback"></a>

`feedback` in message responses is read-only: it is `null` when there is no feedback, or an object such as `{"id": "…", "type": "like", "suggestion": "…", "updatedAt": "…"}` when feedback exists. Requests to create messages do not accept `feedback`. To like or dislike an AI reply, use the separate endpoint:

```http
POST /api/v1/messages/{messagePk}/feedback/
Authorization: Api-Key <your API key>
Content-Type: application/json

{"type": "dislike", "suggestion": "The answer did not mention the return deadline"}
```

* `type` is required and accepts only `like` or `dislike`; `suggestion` is optional and may be an empty string.
* Use `PATCH /api/v1/messages/{messagePk}/feedback/{id}/` to update feedback and `DELETE` to remove it. `{id}` is the feedback object's `id`.
* Feedback appears in AgentOps conversation records. See [Create Message Feedback](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-feedback-create) in the API documentation for field definitions.

## Delete a Conversation <a href="#delete-conversation" id="delete-conversation"></a>

`DELETE /api/v1/conversations/{id}/` deletes a regular conversation and returns `204` on success. This is a soft deletion: the conversation disappears from lists and queries and can no longer be continued, while the platform retains the data for auditing. To also remove conversation attachment files, call the [Conversation Attachment Management API](/tech/en/api-integration/endpoint-behaviors/conversation-attachments.md) separately. See [Delete a Conversation](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-destroy) in the API documentation.

### Page Number Fields in Citation Nodes <a href="#citation-page-number" id="citation-page-number"></a>

Each entry in an Agent reply's `citationNodes[]` contains a `chatbotTextNode` (the cited passage) with the following page number fields:

| Field                  | Meaning                                                                                                                                 |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `pageStart`, `pageEnd` | The passage's start and end pages in the source document, **starting at 1**; both are equal if the passage does not span multiple pages |
| `pageNumber`           | Equal to `pageStart`; retained for compatibility with older integrations                                                                |

Page numbers are available only for documents whose parser can map content to actual pages (primarily PDF files and Office documents parsed as PDFs). For sources without pagination, such as `.txt`, `.md`, CSV/Excel, HTML, crawler-imported web pages, and audio transcripts, all three fields are `null` (the fields are still present, not omitted). When displaying citations, check for `null` before constructing text such as "Page N" or a file link with `#page=N`. Passages returned by the [Knowledge Base Retrieval API](/tech/en/api-integration/knowledge-base-api.md#search-response) use the same fields and rules.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/en/api-integration/conversations-and-messages.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
