> 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/api-integration/conversations-and-messages.md).

# 建立對話與訊息

以 API 建立對話、送出訊息，再由 Webhook 接收 Agent 回覆的串接流程；欄位定義見 API 文件。

以 API 串接對話分兩步：先建立對話取得對話 ID，再對這個對話送出訊息；Agent 的回覆會以 Webhook 推送給您。本頁說明流程與注意事項，每個欄位的型別與必填規則以 API 文件為準。

## 建立對話 <a href="#create-conversation" id="create-conversation"></a>

建立一個新的對話。

**端點：** `https://api.maiagent.ai/api/v1/conversations/`

**請求方法：** `POST`

**請求標頭：**

```
Authorization: Api-Key <您的API金鑰>
Content-Type: application/json
```

**請求內容：**

必填 `webChat`（Web Chat ID：在後台 <mark style="color:blue;">客服對話</mark> → <mark style="color:blue;">對話平台</mark> → 編輯該 Agent 的 API 平台 → <mark style="color:blue;">串接與登入</mark> → <mark style="color:blue;">Webhook 設定</mark> 最下方的 <mark style="color:blue;">API 資訊</mark> 卡複製，見使用者手冊[對話平台基本設定](https://docs.maiagent.ai/build/conversation-settings/platform-settings/basic-settings#web-chat-id)；也可用 `GET /api/v1/web-chats/` 取得）。要讓對話歸屬某位訪客時，另帶 `contact`（聯絡人 ID，須屬於同一個對話平台，取得方式見[聯絡人身分同步與 Token 更新](/tech/serve/contacts/contact-credentials-sync.md)）；不帶 `contact` 時，對話的聯絡人是 API 金鑰所屬的使用者，用同一把金鑰建立的對話都會歸在這位聯絡人底下。欄位定義見 API 文件[建立新的對話](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-create)。

**請求範例：**

```python
import requests

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

**回應內容：**

串接訊息時，記下回應中的 `id`（對話 ID）即可：取得對話中的所有訊息、辨識訊息 Webhook 屬於哪一個對話，都用這個 ID。設定 Webhook 需要的對話平台 ID 在 `inbox.id`。回應欄位見 API 文件[建立新的對話](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-create)。

***

## 傳送訊息 <a href="#send-message" id="send-message"></a>

建立一則新訊息

**端點：** `https://api.maiagent.ai/api/v1/messages/`

**請求方法：** `POST`

**請求標頭：**

```
Authorization: Api-Key 您的API金鑰
Content-Type: application/json
```

**請求內容：**

必填 `conversation`（對話 ID）；訊息文字放在 `content`，附件放在 `attachments`（預設為空陣列）。欄位定義見 API 文件[發送訊息 (建立)](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-create)。

附件物件要先建立再帶入，建立方式見 [Presigned 檔案上傳模式：建立訊息附件](/tech/api-integration/api_knowledge.md#message-attachments)；把建立附件時回應的物件（`type`、`filename`、`file`）原樣放進 `attachments`。

**請求範例：**

Python 範例

```python
import requests

response = requests.post(
    url='https://api.maiagent.ai/api/v1/messages/',
    headers={
        'Authorization': 'Api-Key 您的API金鑰'
    },
    json={
        'conversation': '對話ID',
        'content': '訊息內容',
        'attachments': [
            {
                "id": "附件ID",
                "type": "附件類型",
                "filename": "附件檔案名稱",
                "file": "附件檔案的 URL"
            }
        ]
    }
)

```

cURL 範例

```bash
curl -X POST 'https://api.maiagent.ai/api/v1/messages/' \
-H 'Authorization: Api-Key 您的API金鑰' \
-H 'Content-Type: application/json' \
-d '{
    "conversation": "對話ID",
    "content": "訊息內容",
    "attachments": [
        {
            "id": "附件ID",
            "type": "附件類型",
            "filename": "附件檔案名稱",
            "file": "附件檔案的 URL"
        }
    ]
}'

```

**回應格式：**

收到回應代表訊息建立成功，回應內容是剛建立的這則訊息，不含 Agent 的回覆；回覆會以 Webhook 推送，見 [Webhook](/tech/serve/webhook.md)。回應欄位見 API 文件[發送訊息 (建立)](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-create)。

**回應範例：**

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

### 訊息類型說明 <a href="#message-types" id="message-types"></a>

* `incoming`: 收到的訊息
* `outgoing`: 發送的訊息

### 訊息內容中的圖片 <a href="#images-in-content" id="images-in-content"></a>

`content` 是純文字，平台原樣儲存、不解析其中的網址。要在對話中呈現圖片有兩種方式：

| 方式                               | 適用                        | 說明                                                                                                        |
| -------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------- |
| `attachments`                    | 使用者上傳圖片給 Agent 辨識、以檔案形式保存 | 平台負責儲存與到期管理，是支援的正式做法；建立方式見 [Presigned 檔案上傳模式](/tech/api-integration/api_knowledge.md#message-attachments) |
| Markdown 圖片語法 `![說明](https://…)` | Agent 回覆或工具結果要「顯示」一張外部圖片  | Web Chat 與 MaiGPT 以 Markdown 渲染訊息，瀏覽器會直接向該網址抓圖，網址（含查詢字串）原樣保留                                              |

使用 Markdown 圖片時要注意：

* 圖片由**使用者的瀏覽器**載入，網址必須可從公網不經認證存取；平台不會代為下載或轉存。
* 帶簽章且會到期的網址（例如 Azure SAS、S3 presigned）寫進訊息後不會更新，到期後舊訊息裡的圖片就無法顯示。需要長期可看時，請提供不會過期的網址，或由您的系統提供固定網址再轉導。
* 請用 Markdown 語法，不要依賴 HTML 標籤；HTML 的處理方式依前端渲染器而定，不在契約內。
* 回應中引用節點的 `imageUrl` 是知識庫段落的圖片，與訊息內容的圖片無關。
* 自訂 API 工具回傳圖片網址時的兩段式流程，見 [API 工具工程指南：回應怎麼回給模型](/tech/api-integration/api-tool-engineering-guide.md#response-to-model)。

***

## 訊息回饋 <a href="#message-feedback" id="message-feedback"></a>

訊息回應中的 `feedback` 是唯讀欄位：沒有回饋時為 `null`，有回饋時是物件 `{"id": "…", "type": "like", "suggestion": "…", "updatedAt": "…"}`。建立訊息的請求不接受 `feedback`，要對一則 AI 回覆按讚或倒讚，用獨立的端點：

```http
POST /api/v1/messages/{messagePk}/feedback/
Authorization: Api-Key <您的API金鑰>
Content-Type: application/json

{"type": "dislike", "suggestion": "答案沒有提到退貨期限"}
```

* `type` 必填，只接受 `like` 或 `dislike`；`suggestion` 選填，可為空字串。
* 修改用 `PATCH /api/v1/messages/{messagePk}/feedback/{id}/`，取消用 `DELETE`，`{id}` 是回饋物件的 `id`。
* 回饋會出現在 AgentOps 的對話記錄中，欄位見 API 文件[建立訊息回饋](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#messages-feedback-create)。

## 刪除對話 <a href="#delete-conversation" id="delete-conversation"></a>

`DELETE /api/v1/conversations/{id}/` 刪除一般對話，成功回 `204`。這是軟刪除：對話從列表與查詢中消失、無法再延續，平台保留資料供稽核。需要同時清掉對話附件的檔案時，請另外呼叫[對話附件管理 API](/tech/api-integration/endpoint-behaviors/conversation-attachments.md)。見 API 文件[刪除對話](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi#conversations-destroy)。

### 引用節點的頁碼欄位 <a href="#citation-page-number" id="citation-page-number"></a>

Agent 回覆的 `citationNodes[]` 每筆帶一個 `chatbotTextNode`（被引用的段落），其中的頁碼欄位：

| 欄位                    | 意思                                    |
| --------------------- | ------------------------------------- |
| `pageStart`、`pageEnd` | 這個段落在來源文件中的起訖頁，**從 1 起算**；段落沒有跨頁時兩者相同 |
| `pageNumber`          | 等於 `pageStart`，為相容舊串接而保留              |

只有解析器能對應到真實頁面的文件（主要是 PDF，以及以 PDF 方式解析的 Office 文件）才有頁碼；`.txt`、`.md`、CSV／Excel、HTML、爬蟲匯入的網頁、音訊逐字稿等沒有分頁的來源，這三個欄位都是 `null`（欄位仍會出現，不是省略）。顯示引用時請先判斷 `null` 再組「第 N 頁」的文字或帶 `#page=N` 的檔案連結。[知識庫檢索 API](/tech/api-integration/knowledge-base-api.md#search-response) 回傳的段落使用相同的欄位與規則。


---

# 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/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.
