> 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/dui-hua-yu-xun-xi-hui-fu-chuan-liu-tong-bu.md).

# 對話與訊息回覆（串流/同步）

呼叫 completions API 取得 Agent 回覆、回 202（非串流超過等待上限、附件還在處理）時的輪詢與 Webhook 接收，以及串流（SSE）每個事件的欄位、reset 處理與結束條件

向 Agent 發送訊息並取得回應。`isStreaming` 為 `false` 時，等回覆完成後一次回傳 JSON（回覆超過等待上限時改回 HTTP `202`，見[非串流回覆超過等待上限](#non-streaming-202)）；為 `true` 時，以 Server-Sent Events（SSE）邊產生邊回傳。這個對話還有附件在處理時：串流呼叫，以及帶 `waitForAttachments: false` 的非串流呼叫，立即回 HTTP `202`；非串流呼叫預設會在請求內等這次帶的附件處理完、回覆產生後回 `200`，等待上限內等不到，或這個對話先前訊息帶的附件還在處理，才回 `202`。這個行為的適用版本與細節見[附件還在處理](#accepted-202)。

收到 `202` 時：

* **`status: "processing"`，或 `status: "pending_attachments"` 且 `messageCreated` 為 `true`**：訊息已收下、回覆會自動產生（附件全部處理失敗等已確定失敗的情況，會查到 `failed`），**不要重送**，依回應標頭 `Location` 查詢回覆。
* **`status: "pending_attachments"` 且 `messageCreated` 為 `false`**：**這次的內容沒有被收下**，先取得前一則提問的回覆再送，見[附件處理中再送](#accepted-202-resend)。

```bash
curl -N -X POST \
  'https://api.maiagent.ai/api/v1/chatbots/{chatbot_id}/completions/' \
  -H 'Authorization: Api-Key YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "conversation": null,
    "message": {
      "content": "你好，請介紹你自己"
    },
    "isStreaming": true
  }'
```

**參數：**

* `chatbot_id` (路徑參數)：Agent ID
* `conversation` (請求內容)：對話 ID；帶 `null` 或不帶會建立新對話，帶入既有 ID 則延續該對話
* `message.content` (請求內容)：要發送的訊息內容
* `message.attachments` (請求內容)：附件陣列（可選），每筆帶上傳附件時回應的 `id`、`type`、`filename`、`file`，見[範例：非串流帶附件](#attachment-examples)
* `isStreaming` (請求內容)：是否使用串流回應，預設 `false`（也接受 `is_streaming`）
* `waitForAttachments` (請求內容)：非串流呼叫帶附件時是否在請求內等附件處理完再回應，預設 `true`；`false` 時附件還在處理就立即回 `202`，見[附件還在處理](#accepted-202)

其餘請求欄位（`queryMetadata`、`toolIds` 等）見 API 文件站的[對話與訊息](https://docs.maiagent.ai/api/api-reference/dui-hua-he-xun-xi)。

**回應（非串流）：**

```json
{
  "conversationId": "string",
  "content": "完整回覆內容",
  "done": true,
  "reset": false,
  "citations": null,
  "citationNodes": null,
  "contentPayload": {
    "content": "完整回覆內容",
    "items": [{ "type": "text", "text": "完整回覆內容" }],
    "metadata": null
  },
  "messageId": "string"
}
```

各欄位的意義與下方串流事件相同。

## 取得回覆的流程 <a href="#reply-flow" id="reply-flow"></a>

送出 completions 後，依狀態碼與回應內容決定下一步：

```mermaid
flowchart TD
    A[送出 completions] --> B{HTTP 狀態碼}
    B -- 200 --> C[回應就是完整回覆<br>messageId 為 null：已轉真人]
    B -- 202 --> D{status}
    D -- processing --> E[訊息已收下，不要重送<br>依 Location 查詢]
    D -- pending_attachments --> F{messageCreated}
    F -- true --> E
    F -- false --> G{userMessageId}
    G -- 有值 --> H[先依 Location 取得<br>前一則提問的結果]
    H --> I[再送這次的內容]
    G -- null --> J[隔幾秒再送這次的內容]
    E --> K{查詢結果的 status}
    K -- processing --> E
    K -- done --> C
    K -- failed --> L[依 code 處理<br>需要答案就重新送出]
```

| 收到的回應                                                         | 這次的訊息    | 下一步                                                          | 說明                                                                                                                                        |
| ------------------------------------------------------------- | -------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `200`                                                         | 已收下      | 直接使用回覆                                                       | 串流時是 SSE，見[串流回應格式](#streaming-format)。`messageId` 為 `null` 表示對話已轉真人，`content` 是排隊或轉接提示，不是 AI 回覆，見[收不到 AI 回覆推送的情況](#webhook-reply-missing) |
| `202`，`status: "processing"`                                  | 已收下      | 依 `Location` 查詢，**不要重送**                                     | [非串流回覆超過等待上限](#non-streaming-202)                                                                                                         |
| `202`，`status: "pending_attachments"`，`messageCreated: true`  | 已收下      | 依 `Location` 查詢，**不要重送**                                     | [附件還在處理](#accepted-202)                                                                                                                   |
| `202`，`status: "pending_attachments"`，`messageCreated: false` | **沒有收下** | `userMessageId` 有值：先依 `Location` 取得前一則提問的結果再送；為 `null`：隔幾秒再送 | [附件處理中再送](#accepted-202-resend)                                                                                                           |

不想輪詢時，可以在 API 對話平台設定 Outgoing Webhook，回覆存進對話後由平台推送給你（`200`、`202` 與串流都適用，例外見[收不到 AI 回覆推送的情況](#webhook-reply-missing)），見[用 Webhook 接收回覆](#webhook-reply)。

## 非串流回覆超過等待上限（HTTP 202） <a href="#non-streaming-202" id="non-streaming-202"></a>

非串流呼叫（`isStreaming` 未帶或為 `false`）會等 Agent 回覆完成才回應，但等待有上限。上限內完成，照上面的格式回 HTTP `200`；超過上限，平台先回 HTTP `202`，Agent 在背景繼續把回覆做完、存進對話，之後由你輪詢狀態資源取得結果。這樣請求不會被前面的負載平衡器或反向代理以閒置逾時切斷成 `504`。

* **等待上限**：由平台決定，可能依部署環境不同而調整。整合程式不要寫死秒數，收到 `202` 就照下面流程處理，並依 `Retry-After` 決定輪詢間隔。
* **不受影響的情況**：`isStreaming: true`（包括 Agent 設為 JSON 結構化輸出、只送一個 `done: true` 事件的情況）不套用等待上限。
* **帶附件的非串流呼叫**：在請求內等附件時用同一個等待上限。到上限時附件還在處理，回 `status: "pending_attachments"` 的 `202`（見[附件還在處理](#accepted-202)）；附件已處理完、回覆還在產生，回這裡的 `202`；回覆已確定失敗（例如附件全部處理失敗）時不等到上限，立即回這裡的 `202`，依 `Location` 會查到 `failed`。兩種 `202` 用同一個狀態資源查詢回覆。
* **點數**：轉為 `202` 不影響計費，背景完成的回覆跟一般回覆一樣只扣一次。

### 202 回應內容 <a href="#reply-accepted-response" id="reply-accepted-response"></a>

```http
HTTP/1.1 202 Accepted
Location: /api/v1/chatbots/{chatbot_id}/completions/{userMessageId}/
Retry-After: 5

{
  "status": "processing",
  "conversationId": "string",
  "userMessageId": "string"
}
```

| 項目                 | 說明                                                                                                                   |
| ------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `status`           | 固定為 `processing`                                                                                                     |
| `conversationId`   | 對話 ID，新對話也從這裡取得                                                                                                      |
| `userMessageId`    | 這次送出的使用者訊息 ID                                                                                                        |
| 本文**沒有** `content` | 用「有沒有 `content`」或狀態碼就能分辨這不是回覆                                                                                        |
| `Location` 標頭      | 狀態資源的**相對網址**，路徑前綴沿用你呼叫時用的（`/api/v1/…` 或 `/api/…`）；呼叫時帶了 `?inbox=` 或 `?conversation=` 查詢參數的，也會一併帶上。請以你呼叫的主機為基準組出完整網址 |
| `Retry-After` 標頭   | 建議的輪詢間隔秒數，目前為 `5`                                                                                                    |

### 輪詢狀態資源 <a href="#poll-reply-status" id="poll-reply-status"></a>

`GET /api/v1/chatbots/{chatbot_id}/completions/{userMessageId}/`，帶同一把 `Authorization: Api-Key` 標頭。HTTP 狀態碼都是 `200`，以本文的 `status` 判斷：

| `status`     | 意義                | 其他欄位                                                                                                                         | 下一步                      |
| ------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
| `processing` | 回覆還在產生（或附件還在處理）   | `conversationId`、`userMessageId`                                                                                             | 等 `Retry-After` 秒後再查     |
| `done`       | 回覆已完成             | 與非串流 `200` 回應**完全相同**的欄位（`conversationId`、`content`、`done`、`reset`、`citations`、`citationNodes`、`contentPayload`、`messageId`） | 用解析 `200` 的同一套程式取結果，停止輪詢 |
| `failed`     | 回覆沒有在期限內存下，**終態** | `conversationId`、`userMessageId`、`code`、`reason`（依請求語言的可讀說明）                                                                 | 停止輪詢；需要答案請重新送出訊息         |

`failed` 的固定代碼：

| `code`                    | 情況                                                                                                                               |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `reply_interrupted`       | 回覆在背景處理途中被中斷，沒有存下答案                                                                                                              |
| `reply_timed_out`         | 從送出訊息起，超過「Agent 執行逾時（團隊模式取 Agent 與團隊兩者較長者）＋ 60 秒」仍沒有存下答案；超過期限後才存下的答案也算 `failed`。等附件的提問從附件處理完成後才開始算，見[附件還在處理](#accepted-202-poll) |
| `reply_attachment_failed` | 等附件的提問，這則提問帶的附件全部處理失敗，不會產生回覆；請重新上傳檔案，或不帶附件再送出                                                                                    |

`done` 與 `failed` 一旦回出就固定不變，之後重複查詢都得到同樣結果，不會因為事後調整 Agent 逾時或晚到的回覆而翻轉。

沒有保留 `Location` 時，也可以用 `GET /api/v1/messages/?conversation={conversationId}` 查該對話的訊息，依 `createdAt` 取該提問之後的第一則 `outgoing` 訊息。

**錯誤回應**：

* 沒帶或帶錯 API Key：`401`。
* 其他組織的呼叫者、對這個 Agent 沒有對話權限、不是這段對話的呼叫者、訊息 ID 不存在、對話或回覆已被刪除：一律 `404`，不透露該 ID 是否存在。

### 輪詢範例 <a href="#poll-example" id="poll-example"></a>

以下 Python 範例送出非串流請求，收到 `202` 時依 `Retry-After` 輪詢，直到 `done` 或 `failed`。需要 `requests`（`pip install requests`）。

```python
import time
from urllib.parse import urljoin

import requests

BASE_URL = "https://api.maiagent.ai"
API_KEY = "YOUR_API_KEY"
CHATBOT_ID = "YOUR_CHATBOT_ID"
HEADERS = {"Authorization": f"Api-Key {API_KEY}"}


def ask(content: str, conversation_id: str | None = None, max_poll_seconds: int = 1800) -> dict:
    resp = requests.post(
        f"{BASE_URL}/api/v1/chatbots/{CHATBOT_ID}/completions/",
        headers=HEADERS,
        json={"conversation": conversation_id, "message": {"content": content}, "isStreaming": False},
        timeout=600,  # 留得比平台等待上限長，讓平台有機會先回 202
    )
    resp.raise_for_status()
    body = resp.json()
    if resp.status_code == 200:
        return body
    # 202：processing（超過等待上限）或 pending_attachments（附件還在處理），訊息已收下，不要重送
    if body.get("status") == "pending_attachments" and not body.get("messageCreated"):
        # 同一個對話先前提問的附件還在處理，這次的內容沒有被收下
        raise RuntimeError(f"not accepted, an earlier message is still waiting on attachments: {body}")

    status_url = urljoin(BASE_URL, resp.headers["Location"])
    deadline = time.monotonic() + max_poll_seconds
    while time.monotonic() < deadline:
        time.sleep(int(resp.headers.get("Retry-After", 5)))
        resp = requests.get(status_url, headers=HEADERS, timeout=30)
        resp.raise_for_status()
        body = resp.json()
        if body["status"] == "done":
            return body  # 欄位與非串流 200 相同
        if body["status"] == "failed":
            raise RuntimeError(f"{body['code']}: {body['reason']}")
    raise TimeoutError(f"still processing: {status_url}")


print(ask("你好，請介紹你自己")["content"])
```

用 curl 手動查詢時，把 `202` 的 `Location` 接在主機後面：

```bash
curl 'https://api.maiagent.ai/api/v1/chatbots/{chatbot_id}/completions/{userMessageId}/' \
  -H 'Authorization: Api-Key YOUR_API_KEY'
```

## 附件還在處理（HTTP 202：訊息已收下） <a href="#accepted-202" id="accepted-202"></a>

一般模式的 Agent 會先處理文件與音訊附件（建立索引），處理完才回答；圖片附件不需要先處理，不會因為它回 `202`。

非串流呼叫預設（`waitForAttachments` 未帶或為 `true`）會在請求內等這次帶的附件處理完、回覆產生，等到就回 `200`，內容與一般回應相同，不需要另外處理。以下情況才回 HTTP `202`、`status: "pending_attachments"`：

* 串流呼叫（`isStreaming: true`）。
* 非串流呼叫帶 `waitForAttachments: false`：附件還在處理就立即回。
* 非串流呼叫等到[等待上限](#non-streaming-202)時，附件還在處理。
* 這個對話先前的附件還在處理：不論 `waitForAttachments`，都立即回。

非串流呼叫等到等待上限時附件已處理完、回覆還在產生，回的是 `202`、`status: "processing"`；回覆已確定失敗（例如附件全部處理失敗）時不等到上限，立即回 `202`、`status: "processing"`。這兩種的處理方式見[非串流回覆超過等待上限](#non-streaming-202)。

{% hint style="info" %}
「非串流呼叫在請求內等附件、等到就回 `200`」的適用版本：

* **SaaS**：下次版本更新起套用。套用前，非串流呼叫在附件還在處理時仍立即回 `202`（不論 `waitForAttachments`）。
* **地端 2026.Q3**：`2026.Q3-11.09.2` 起提供，建議使用 `2026.Q3-11.10` 以後的版本；更早的 2026.Q3 版本，附件還在處理時一律立即回 `202`。
* 其他地端版本請洽服務窗口確認。

整合程式 `200` 與 `202` 都要能處理。
{% endhint %}

收到 `status: "pending_attachments"` 的 `202` 時，依 `messageCreated` 分兩種：

* **`messageCreated` 為 `true`（這次帶了要處理的附件）**：**這不是失敗**，提問已經建立，附件處理完會自動產生回覆。**不要重送同一則訊息**，否則對話裡會多一則重複的提問與第二則回覆。請依 `Location` 查詢回覆，方式與[輪詢狀態資源](#poll-reply-status)相同。
* **`messageCreated` 為 `false`（這個對話先前的附件還在處理）**：不論這次有沒有帶附件，這次的訊息都**沒有**建立，要由你再送一次，見[附件處理中再送](#accepted-202-resend)。

另外：

* 串流呼叫時，這個 `202` 在開始串流前就回，內容是 JSON，不是 SSE。
* Agent 模式（`replyMode: agent`）不會先處理附件，帶附件也直接回答，不會因為這次帶的附件回 `202`。但 Agent 可能在回答後才在背景處理它讀到的附件；這段期間在同一個對話再送，會回 `202`、`messageCreated: false`、`userMessageId: null`。
* 非串流呼叫在請求內等附件時，回應時間包含附件處理時間與回覆產生時間。呼叫端的請求逾時要留得比平台等待上限長，才收得到平台的回應（`200` 或 `202`）。呼叫端先逾時斷線時，訊息已經收下、回覆照常產生，**不要重送同一則訊息**，改用 [Webhook 推送](#webhook-reply)取得回覆。

### 回應內容 <a href="#accepted-202-body" id="accepted-202-body"></a>

```http
HTTP/1.1 202 Accepted
Location: /api/v1/chatbots/{chatbot_id}/completions/{userMessageId}/
Retry-After: 5

{
  "status": "pending_attachments",
  "messageCreated": true,
  "conversationId": "string",
  "userMessageId": "string",
  "message": "訊息已收下，附件仍在處理中。回覆會自動產生，請勿重送訊息，並從 Location 標頭取得回覆。",
  "pendingAttachments": ["string"],
  "attachmentIds": ["string"]
}
```

| 項目                   | 說明                                                                                                                                                 |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`             | 固定為 `pending_attachments`                                                                                                                          |
| `messageCreated`     | 這次請求的訊息有沒有收下。`true`：已建立提問，回覆會自動產生；`false`：同一個對話先前的附件還在處理，這次的內容**沒有**收下，見[附件處理中再送](#accepted-202-resend)                                            |
| `conversationId`     | 對話 ID，新對話也從這裡取得                                                                                                                                    |
| `userMessageId`      | 等待回覆的提問訊息 ID。`messageCreated` 為 `false` 時指向先前還在等附件的那則提問；沒有這樣的提問時為 `null`                                                                           |
| `message`            | 說明文字，依請求語言回傳。文字可能調整，程式請以 `status` 與 `messageCreated` 判斷，不要比對文字                                                                                     |
| `pendingAttachments` | 這段對話裡還在處理的檔案在知識庫中的 ID，保留給既有整合使用；**不是**上傳附件時拿到的 ID                                                                                                  |
| `attachmentIds`      | 同一批檔案在[上傳附件](https://docs.maiagent.ai/api/api-reference/fu-jian-he-dang-an)時拿到的附件 ID，與 `pendingAttachments` 逐筆對應（同一個位置是同一個檔案）；不是經上傳附件進來的檔案為 `null` |
| `Location` 標頭        | 這則提問的狀態資源相對網址，規則同[非串流 202](#reply-accepted-response)；`userMessageId` 為 `null` 時不帶                                                                  |
| `Retry-After` 標頭     | 建議的輪詢間隔秒數，目前為 `5`；`userMessageId` 為 `null` 時不帶                                                                                                     |

### 取得回覆 <a href="#accepted-202-poll" id="accepted-202-poll"></a>

對 `Location` 發 `GET`，判讀方式與[輪詢狀態資源](#poll-reply-status)相同（`done` 的欄位與非串流 `200` 完全相同）。等附件的提問另有幾點：

* **附件處理沒有時間上限**：附件還在處理時一律回 `processing`，檔案大就要等比較久。
* **附件全部失敗**：這則提問帶的附件全部處理失敗時回 `failed`，`code` 為 `reply_attachment_failed`。只有部分失敗時，Agent 用處理成功的附件回答。
* **回覆時限的起算點**：從附件處理完成後才開始算（「Agent 執行逾時＋ 60 秒」，另加最多約 20 秒的接續延遲），超過仍沒有存下答案時回 `failed`、`code` 為 `reply_timed_out`。

### 附件處理中再送 <a href="#accepted-202-resend" id="accepted-202-resend"></a>

同一個對話的附件還在處理時，再送任何訊息（內容、附件相同或不同）都**不會**建立新提問。平台回 `202`、`messageCreated: false`，`message` 說明這次的內容沒有收下。這次的內容要由你再送一次：

* **`userMessageId` 有值**：它與 `Location` 指向先前還在等附件的提問。請先依 `Location` 取得那則提問的回覆（`done` 或 `failed`），再送出這次的內容。
* **`userMessageId` 為 `null`**：沒有在等附件的提問（例如 Agent 模式已經回答、附件在背景處理），回應也不帶 `Location` 與 `Retry-After`。隔幾秒（例如 5 秒）再送一次這次的內容，附件處理完成後就會收下。

```http
HTTP/1.1 202 Accepted
Location: /api/v1/chatbots/{chatbot_id}/completions/{先前提問的 userMessageId}/
Retry-After: 5

{
  "status": "pending_attachments",
  "messageCreated": false,
  "conversationId": "string",
  "userMessageId": "string",
  "message": "先前訊息的附件仍在處理中，因此本次請求未建立新訊息。請從 Location 標頭取得該訊息的回覆後，再送出本次內容。",
  "pendingAttachments": ["string"],
  "attachmentIds": ["string"]
}
```

## 範例：非串流帶附件 <a href="#attachment-examples" id="attachment-examples"></a>

以下 ID 與金鑰都是虛構的。附件先用 `POST /api/v1/attachments-upload/` 上傳（見[知識庫 API：建立訊息附件](https://docs.maiagent.ai/tech/api-integration/api_knowledge.md#message-attachments)），再把回應的 `id`、`type`、`filename`、`file` 放進 `message.attachments`。

### 請求 <a href="#attachment-request" id="attachment-request"></a>

```bash
curl -X POST \
  'https://api.maiagent.ai/api/v1/chatbots/3f2b8c1e-7a4d-4e5f-9b6a-0c1d2e3f4a5b/completions/' \
  -H 'Authorization: Api-Key YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "conversation": null,
    "message": {
      "content": "請摘要這份文件",
      "attachments": [
        {
          "id": "5d1f2a7c-3b8e-4c19-9a62-1e4b7f0c8d35",
          "type": "other",
          "filename": "document.pdf",
          "file": "https://example.com/media/document.pdf"
        }
      ]
    },
    "isStreaming": false
  }'
```

### 等待上限內完成：200 <a href="#attachment-200" id="attachment-200"></a>

回覆在等待上限內完成時，直接回 `200` 與完整回覆。一般模式帶文件或音訊附件時，平台預設（`waitForAttachments` 未帶或為 `true`）會在請求內等附件處理完再回答，回應時間包含附件處理時間（適用版本見[附件還在處理](#accepted-202)；尚未套用的版本會回下面的 `202`）：

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "content": "這份文件的重點如下：……",
  "done": true,
  "reset": false,
  "citations": null,
  "citationNodes": null,
  "contentPayload": {
    "content": "這份文件的重點如下：……",
    "items": [{ "type": "text", "text": "這份文件的重點如下：……" }],
    "metadata": null
  },
  "messageId": "9f1e6d2c-4b8a-4f3e-a5c7-1d0e9b8a7c6f"
}
```

`citations`、`citationNodes` 只在 API 對話平台開啟引用顯示時帶值。

### 一般模式附件還在處理：202 <a href="#attachment-202-pending" id="attachment-202-pending"></a>

一般模式的 Agent 帶文件或音訊附件，請求帶 `waitForAttachments: false`，或等到等待上限時附件還在處理，平台回 `202`：

```http
HTTP/1.1 202 Accepted
Location: /api/v1/chatbots/3f2b8c1e-7a4d-4e5f-9b6a-0c1d2e3f4a5b/completions/7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f/
Retry-After: 5
Content-Type: application/json

{
  "status": "pending_attachments",
  "messageCreated": true,
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "userMessageId": "7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f",
  "message": "訊息已收下，附件仍在處理中。回覆會自動產生，請勿重送訊息，並從 Location 標頭取得回覆。",
  "pendingAttachments": ["e2d9a4b6-8f1c-4a3e-b7d5-6c9e0f1a2b3c"],
  "attachmentIds": ["5d1f2a7c-3b8e-4c19-9a62-1e4b7f0c8d35"]
}
```

### 超過等待上限：202 <a href="#attachment-202-processing" id="attachment-202-processing"></a>

回覆已經開始產生、但超過等待上限還沒完成時；或在請求內等附件時回覆已確定失敗（例如附件全部處理失敗，這時不等到上限，依 `Location` 會查到 `failed`）：

```http
HTTP/1.1 202 Accepted
Location: /api/v1/chatbots/3f2b8c1e-7a4d-4e5f-9b6a-0c1d2e3f4a5b/completions/7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f/
Retry-After: 5
Content-Type: application/json

{
  "status": "processing",
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "userMessageId": "7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f"
}
```

### 依 Location 輪詢到拿到回覆 <a href="#attachment-poll" id="attachment-poll"></a>

兩種 `202` 都一樣：每隔 `Retry-After` 秒對 `Location` 發 `GET`。

```bash
curl 'https://api.maiagent.ai/api/v1/chatbots/3f2b8c1e-7a4d-4e5f-9b6a-0c1d2e3f4a5b/completions/7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f/' \
  -H 'Authorization: Api-Key YOUR_API_KEY'
```

還沒好時：

```json
{
  "status": "processing",
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "userMessageId": "7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f"
}
```

完成時（`status` 之外的欄位與 `200` 相同）：

```json
{
  "status": "done",
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "content": "這份文件的重點如下：……",
  "done": true,
  "reset": false,
  "citations": null,
  "citationNodes": null,
  "contentPayload": {
    "content": "這份文件的重點如下：……",
    "items": [{ "type": "text", "text": "這份文件的重點如下：……" }],
    "metadata": null
  },
  "messageId": "9f1e6d2c-4b8a-4f3e-a5c7-1d0e9b8a7c6f"
}
```

附件全部處理失敗時：

```json
{
  "status": "failed",
  "conversationId": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
  "userMessageId": "7b31f0a2-6c4d-4e8b-a1f9-2d3c4b5a6e7f",
  "code": "reply_attachment_failed",
  "reason": "附件全部處理失敗，因此沒有產生回覆。請重新上傳檔案，或不帶附件再送出訊息。"
}
```

### 可執行範例：上傳附件到取得回覆 <a href="#attachment-python" id="attachment-python"></a>

以下 Python 範例上傳附件、送出非串流請求，收到 `200` 直接取回覆；收到 `202` 時依 `status` 與 `messageCreated` 處理：已收下就依 `Location` 輪詢到 `done` 或 `failed`；沒收下就先等前一則提問有結果（或沒有可查的提問時隔幾秒）再送。需要 Python 3.10 以上與 `requests`（`pip install requests`）。

```python
import time
from urllib.parse import urljoin

import requests

BASE_URL = "https://api.maiagent.ai"
API_KEY = "YOUR_API_KEY"
CHATBOT_ID = "YOUR_CHATBOT_ID"
HEADERS = {"Authorization": f"Api-Key {API_KEY}"}


def upload_attachment(path: str) -> dict:
    """上傳附件，回傳要放進 message.attachments 的物件。"""
    with open(path, "rb") as f:
        resp = requests.post(
            f"{BASE_URL}/api/v1/attachments-upload/", headers=HEADERS, files={"file": f}, timeout=120
        )
    resp.raise_for_status()
    attachment = resp.json()
    return {key: attachment[key] for key in ("id", "type", "filename", "file")}


def poll_reply(location: str, retry_after: int, max_poll_seconds: int = 1800) -> dict:
    """依 202 的 Location 查詢，直到 done 或 failed。"""
    status_url = urljoin(BASE_URL, location)
    deadline = time.monotonic() + max_poll_seconds
    while time.monotonic() < deadline:
        time.sleep(retry_after)
        resp = requests.get(status_url, headers=HEADERS, timeout=30)
        resp.raise_for_status()
        body = resp.json()
        if body["status"] == "done":
            return body  # 欄位與非串流 200 相同
        if body["status"] == "failed":
            raise RuntimeError(f"{body['code']}: {body['reason']}")
    raise TimeoutError(f"still processing: {status_url}")


def ask(content: str, attachments: list | None = None, conversation_id: str | None = None,
        max_attempts: int = 20) -> dict:
    """送出非串流提問，回傳與 200 相同欄位的回覆。"""
    payload = {
        "conversation": conversation_id,
        "message": {"content": content, "attachments": attachments or []},
        "isStreaming": False,
    }
    for _ in range(max_attempts):
        resp = requests.post(
            f"{BASE_URL}/api/v1/chatbots/{CHATBOT_ID}/completions/",
            headers=HEADERS,
            json=payload,
            timeout=600,  # 留得比平台等待上限長，讓平台有機會先回 202
        )
        resp.raise_for_status()
        if resp.status_code == 200:
            return resp.json()

        body = resp.json()  # 202
        location = resp.headers.get("Location")
        retry_after = int(resp.headers.get("Retry-After", 5))
        if body["status"] == "processing" or body.get("messageCreated"):
            return poll_reply(location, retry_after)  # 訊息已收下：不要重送，查詢回覆

        # pending_attachments 且 messageCreated 為 false：這次的內容沒有被收下
        payload["conversation"] = body["conversationId"]
        if location:
            try:
                poll_reply(location, retry_after)  # 先等前一則提問有結果（它的回覆由原本送出它的流程處理）
            except RuntimeError:
                pass  # 前一則提問 failed 也一樣可以再送
        else:
            time.sleep(retry_after)  # 沒有可查的提問：隔幾秒再送
    raise RuntimeError("對話的附件一直在處理中，請稍後再送")


reply = ask("請摘要這份文件", attachments=[upload_attachment("document.pdf")])
print(reply["conversationId"], reply["messageId"])
print(reply["content"])
```

## 用 Webhook 接收回覆 <a href="#webhook-reply" id="webhook-reply"></a>

除了輪詢，也可以設定 Outgoing Webhook，讓平台在回覆存進對話後主動推送到你的系統，適合回覆時間長、不想輪詢的串接。送出 completions 的請求逾時仍要留得比平台等待上限長，才收得到 `200` 或 `202` 帶回的 `conversationId`，用來對應推送來的回覆。設定欄位、簽章驗證、自動重送與冪等的通用規則見 [Webhook](https://docs.maiagent.ai/tech/serve/webhook.md)，本節只寫 completions 特有的部分。

{% hint style="info" %}
地端部署的推送欄位與 `202` 回應內容依版本而異，請洽服務窗口確認你的版本。非串流帶附件的適用版本見[附件還在處理](#accepted-202)。
{% endhint %}

```mermaid
sequenceDiagram
    participant C as 你的系統
    participant P as MaiAgent
    participant W as 你的 Webhook 接收端
    C->>P: completions 提問（可帶附件）
    alt 等待上限內完成
        P-->>C: 200＋回覆（conversationId、messageId）
    else 附件處理中或超過等待上限
        P-->>C: 202（conversationId、userMessageId、Location）
        opt 並用輪詢
            C->>P: GET Location
            P-->>C: processing／done（含 messageId）／failed
        end
    end
    Note over P: 回覆存進對話
    P-)W: Outgoing 推送（id＝回覆 ID、conversation.id）
    opt 接收端逾時、連線失敗、5xx、429
        P-)W: 同一內容重送，最多 3 次
    end
    Note over C,W: 以回覆 ID 去重，以對話 ID 對回自己的那一題
```

回 `200` 時回覆在回應前就已存進對話，推送可能比 `200` 回應早到；送出端與接收端要能不論先後都對得上。

### 設定 Outgoing Webhook <a href="#webhook-reply-setup" id="webhook-reply-setup"></a>

completions 新建的對話（`conversation` 帶 `null`）都在這個 Agent 的 **API 對話平台**。這個平台在建立 Agent 時自動產生，名稱與 Agent 相同，在對話平台列表的「頻道」欄顯示 `API`。呼叫時帶的 `?inbox=` 查詢參數不會改變對話建在哪個平台。

1. 後台 → <mark style="color:blue;">客服對話</mark> → <mark style="color:blue;">對話平台</mark> → 選頻道為 `API`、名稱與 Agent 相同的平台 → 左側「串接與登入」群組的 <mark style="color:blue;">Webhook 設定</mark> → <mark style="color:blue;">新增 Webhook</mark>。
2. 填寫 <mark style="color:blue;">名稱</mark>，<mark style="color:blue;">類型</mark>選 <mark style="color:blue;">Outgoing</mark>，填入 <mark style="color:blue;">Webhook URL</mark>（必須可從網際網路連線），<mark style="color:blue;">Payload 格式</mark>選 <mark style="color:blue;">MaiAgent Standard</mark>，填入 <mark style="color:blue;">Secret Token</mark>，儲存。
3. 對這個 Agent 發一次 completions，到 Agent 頁面的 <mark style="color:blue;">Webhook</mark> 分頁確認有一筆推送紀錄、狀態碼是 2xx。

也可以用 API 設定：先查出 API 對話平台的 ID，再新增 Webhook（欄位見 [Webhook：以 API 管理 Webhook](https://docs.maiagent.ai/tech/serve/webhook.md#manage-by-api)）。

```bash
# 列出這個 Agent 的 API 對話平台，取回應裡的 id
curl 'https://api.maiagent.ai/api/v1/inboxes/?chatbot={chatbot_id}&access_type=api' \
  -H 'Authorization: Api-Key YOUR_API_KEY'

curl -X POST 'https://api.maiagent.ai/api/v1/inboxes/{inbox_id}/webhooks/' \
  -H 'Authorization: Api-Key YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "completions 回覆",
    "direction": "outgoing",
    "url": "https://your-system.example.com/maiagent/reply",
    "templatePreset": "maiagent_standard",
    "secretToken": "YOUR_RANDOM_SECRET"
  }'
```

延續既有對話（`conversation` 帶對話 ID）時，對話留在它原本的平台。例如延續 LINE 平台上的對話，推送依 LINE 平台的 Webhook 設定，回覆也照常送到 LINE。

### 什麼時候推送 <a href="#webhook-reply-when" id="webhook-reply-when"></a>

* **回覆存進對話後推送一次**：回 `200` 的回覆、回 `202` 之後在背景產生的回覆、附件處理完才產生的回覆都會推送。串流呼叫在回覆完成後推送一次完整內容，不會每個片段各推一次。
* **逾時或錯誤也會推送**：回覆因 Agent 執行逾時或錯誤以說明文字收尾時，推送的就是那段說明文字，`sender.type` 一樣是 `chatbot`。
* **提問本身**：設了 Incoming Webhook 時，completions 送出的提問也會推到 Incoming。
* **送達**：不保證順序，至少送達一次，失敗會自動重送，見 [Webhook：傳送行為](https://docs.maiagent.ai/tech/serve/webhook.md#delivery)。
* **輪詢判定失敗後**：輪詢回 `failed`、`code` 為 `reply_timed_out` 之後，答案仍可能晚到並存進對話，這則回覆一樣會推送。判定失敗後要重問時，建議開新對話（`conversation` 帶 `null`），避免晚到的回覆被當成下一題的回覆。

### 推送內容 <a href="#webhook-reply-payload" id="webhook-reply-payload"></a>

Payload 格式選 MaiAgent Standard 時，推送內容如下（ID 為虛構）：

```json
{
  "id": "9f1e6d2c-4b8a-4f3e-a5c7-1d0e9b8a7c6f",
  "type": "outgoing",
  "content": "這份文件的重點如下：……",
  "created_at": "2026-11-10T02:15:42.318204+00:00",
  "conversation": {
    "id": "c2a7e5d0-1b3f-4c8e-9a6d-5f4e3d2c1b0a",
    "title": "請摘要這份文件",
    "type": "individual",
    "status": "open",
    "progress_status": "ai_processing",
    "auto_reply_enabled": true,
    "assignee": null
  },
  "inbox": {
    "id": "6a0d4e2f-9c1b-4d7a-8e3f-2b5c7d9e1f04",
    "name": "文件小幫手",
    "channel_type": "web"
  },
  "contact": {
    "id": "d4c3b2a1-0f9e-4d8c-b7a6-5e4f3a2b1c0d",
    "name": "王小明",
    "email": null,
    "phone_number": null
  },
  "sender": {
    "id": "3f2b8c1e-7a4d-4e5f-9b6a-0c1d2e3f4a5b",
    "name": "文件小幫手",
    "type": "chatbot"
  },
  "attachments": [],
  "metadata": {}
}
```

| 欄位                             | 說明                                               |
| ------------------------------ | ------------------------------------------------ |
| `id`                           | **回覆**的訊息 ID，等於 `200` 或輪詢 `done` 回應的 `messageId` |
| `conversation.id`              | 對話 ID，等於 completions 回應的 `conversationId`        |
| `conversation.progress_status` | 推送送出當下的對話狀態，不是回覆建立當下的；重送時可能已經改變                  |
| `inbox.channel_type`           | API 對話平台為 `web`                                  |
| `sender.type`                  | Agent 的回覆為 `chatbot`；真人客服在同一個對話的回覆為 `user`，也會推送  |
| `metadata`                     | **回覆**自己的附加資料，不是提問的                              |

其餘欄位見 [Webhook：MaiAgent 標準格式](https://docs.maiagent.ai/tech/serve/webhook.md#standard-payload)。

### 對應到是哪一題 <a href="#webhook-reply-matching" id="webhook-reply-matching"></a>

推送只帶回覆 ID 與對話 ID，**沒有**提問的訊息 ID；提問時帶的 `message.metadata`、`queryMetadata` 也不會跟著推送。要把回覆對回你系統裡的那一題，用對話 ID 對應，二選一：

* **同一個對話一次只問一題**：送出後記下「這個 `conversationId` 在等哪一題」，等這題的回覆推到（或輪詢到 `done`／`failed`）再送下一題。
* **每題開新對話**：`conversation` 帶 `null`，每題各自一個 `conversationId`。代價是新對話不帶前面的對話歷史。

第一題就拿到 `202` 時，`202` 回應已經帶 `conversationId`，從第一題起就能對應。收到 `200` 時回覆已經在回應裡，同一則回覆之後仍會推送一次，以回覆 ID 去重即可。

### 與輪詢並用 <a href="#webhook-reply-dedupe" id="webhook-reply-dedupe"></a>

同一則回覆可能從三個地方拿到：`200` 回應、輪詢 `done`、Webhook 推送；Webhook 本身也可能重送。三者是同一則回覆、只扣一次點數，以回覆 ID 去重：推送的 `id` 與 `200`、輪詢 `done` 的 `messageId` 相同。去重與先落地再回 `2xx` 的做法見 [Webhook：冪等處理建議](https://docs.maiagent.ai/tech/serve/webhook.md#idempotency)。

### 收不到 AI 回覆推送的情況 <a href="#webhook-reply-missing" id="webhook-reply-missing"></a>

| 情況                   | 怎麼知道                                                                           | 怎麼處理                                                                                                                                                                                 |
| -------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 附件全部處理失敗             | 不產生回覆、不推送；輪詢回 `failed`、`code` 為 `reply_attachment_failed`                      | 重新上傳檔案，或不帶附件再送                                                                                                                                                                       |
| 回覆在產生任何內容前被中斷        | 不推送；輪詢回 `failed`、`code` 為 `reply_interrupted`                                  | 重新送出                                                                                                                                                                                 |
| 對話已轉真人               | completions 回 `200`，`messageId` 為 `null`，帶 `progressStatus`，`content` 為排隊或轉接提示 | AI 不回答這題。轉接提示不推送；排隊中的等候提醒會以 `sender.type: "chatbot"` 推送；之後真人客服的回覆以 `sender.type: "user"` 推送。見[第三方客服系統串接](https://docs.maiagent.ai/tech/serve/customer-service-system-integration.md) |
| 推送重送 3 次都失敗          | Agent 頁面 <mark style="color:blue;">Webhook</mark> 分頁的紀錄狀態碼不是 2xx               | 依 `202` 的 `Location` 查詢，或用 `GET /api/v1/messages/?conversation={conversationId}` 補                                                                                                   |
| Webhook 設在別的對話平台或已停用 | 推送紀錄沒有這則回覆                                                                     | 確認對話所屬的平台（見[設定 Outgoing Webhook](#webhook-reply-setup)）與啟用狀態                                                                                                                         |

建議接收端為每一題設一個等待上限，超過就改用 `Location` 或訊息 API 補查，不要無限期等推送。

### 範例：帶附件提問，以 Webhook 取得回覆 <a href="#webhook-reply-example" id="webhook-reply-example"></a>

以下三個檔案組成可以直接跑的完整流程（Python 3.10 以上，`pip install requests flask`）：

* `ask.py`：上傳附件、送出 completions。`200` 直接取回覆；`202` 等 Webhook 推來，等太久改查 `Location`。
* `receiver.py`：接收端。驗證簽章、以回覆 ID 去重、先落地再回 `2xx`。
* `store.py`：兩者共用，以對話 ID 把回覆對回自己的那一題（同一個對話一次只問一題）。範例用 SQLite，正式環境請換成你的資料庫。

{% code title="store.py" %}

```python
"""送出端（ask.py）與接收端（receiver.py）共用：哪一題在等哪個對話、收到了哪些回覆。範例用 SQLite，正式環境請換成你的資料庫。"""
import sqlite3

DB_PATH = "maiagent_replies.db"


def connect() -> sqlite3.Connection:
    conn = sqlite3.connect(DB_PATH, timeout=30, isolation_level=None)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute(
        "CREATE TABLE IF NOT EXISTS questions (question_id TEXT PRIMARY KEY, conversation_id TEXT,"
        " sent_at TEXT, status TEXT, reply_id TEXT)"
    )
    conn.execute(
        "CREATE TABLE IF NOT EXISTS replies (reply_id TEXT PRIMARY KEY, conversation_id TEXT,"
        " sender_type TEXT, content TEXT, created_at TEXT)"
    )
    return conn


def add_question(conn, question_id: str, conversation_id: str, sent_at: str, reply_id: str | None = None) -> None:
    """記下「這個對話在等哪一題」；已經拿到回覆（200）時直接帶 reply_id。"""
    status = "answered" if reply_id else "waiting"
    conn.execute(
        "INSERT OR REPLACE INTO questions VALUES (?, ?, ?, ?, ?)",
        (question_id, conversation_id, sent_at, status, reply_id),
    )
    match(conn, conversation_id)  # 推送可能比這裡還早到


def save_reply(conn, reply_id: str, conversation_id: str, sender_type: str, content: str, created_at: str) -> bool:
    """同一則回覆不論從 200、輪詢或 Webhook 來，都只存一次；第一次存下時回傳 True。"""
    cur = conn.execute(
        "INSERT OR IGNORE INTO replies VALUES (?, ?, ?, ?, ?)",
        (reply_id, conversation_id, sender_type, content, created_at),
    )
    match(conn, conversation_id)
    return cur.rowcount == 1


def set_result(conn, question_id: str, status: str, reply_id: str | None = None) -> None:
    conn.execute("UPDATE questions SET status = ?, reply_id = ? WHERE question_id = ?", (status, reply_id, question_id))


def get_question(conn, question_id: str) -> tuple[str, str | None]:
    """回傳（狀態, 回覆內容）。"""
    return conn.execute(
        "SELECT q.status, r.content FROM questions q LEFT JOIN replies r ON r.reply_id = q.reply_id"
        " WHERE q.question_id = ?",
        (question_id,),
    ).fetchone()


def match(conn, conversation_id: str) -> None:
    """把對話裡還沒對上的 Agent 回覆，對給同一個對話正在等的那一題（一個對話一次只問一題）。"""
    conn.execute("BEGIN IMMEDIATE")
    try:
        question = conn.execute(
            "SELECT question_id, sent_at FROM questions WHERE conversation_id = ? AND status = 'waiting'",
            (conversation_id,),
        ).fetchone()
        if question:
            reply = conn.execute(
                "SELECT reply_id FROM replies WHERE conversation_id = ? AND sender_type = 'chatbot'"
                " AND created_at >= ? AND reply_id NOT IN"
                " (SELECT reply_id FROM questions WHERE reply_id IS NOT NULL)"
                " ORDER BY created_at LIMIT 1",
                (conversation_id, question[1]),
            ).fetchone()
            if reply:
                conn.execute(
                    "UPDATE questions SET status = 'answered', reply_id = ? WHERE question_id = ?",
                    (reply[0], question[0]),
                )
        conn.execute("COMMIT")
    except Exception:
        conn.execute("ROLLBACK")
        raise
```

{% endcode %}

{% code title="receiver.py" %}

```python
"""Outgoing Webhook 接收端：驗簽、先落地再回 2xx、以回覆 ID 去重、以對話 ID 對回自己的那一題。"""
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

import store

app = Flask(__name__)
SECRET = os.environ["MAIAGENT_WEBHOOK_SECRET"]  # Webhook 設定的 Secret Token
TOLERANCE_SECONDS = 300


def is_valid_signature(timestamp: str, signature: str, body: bytes) -> bool:
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = "sha256=" + hmac.new(SECRET.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


@app.post("/maiagent/reply")
def maiagent_reply():
    if not is_valid_signature(
        request.headers.get("X-MaiAgent-Timestamp", ""),
        request.headers.get("X-MaiAgent-Signature-256", ""),
        request.get_data(),  # 原始位元組，不要先解析再序列化
    ):
        abort(401)

    payload = request.get_json(force=True)
    if payload["type"] == "outgoing":
        # sender.type：chatbot 是 Agent 的回覆，user 是真人客服；只有 chatbot 會對到等待中的題目
        store.save_reply(
            store.connect(),
            payload["id"],
            payload["conversation"]["id"],
            payload["sender"]["type"],
            payload["content"],
            payload["created_at"],
        )
    return "", 204  # 30 秒內回 2xx；重送來的同一則回覆也回 2xx
```

{% endcode %}

{% code title="ask.py" %}

```python
"""上傳附件、送出 completions，取得這一題的回覆：200 直接拿到；202 等 Webhook 推來，等太久改查 Location。"""
import sys
import time
import uuid
from datetime import datetime, timezone
from urllib.parse import urljoin

import requests

import store

BASE_URL = "https://api.maiagent.ai"
API_KEY = "YOUR_API_KEY"
CHATBOT_ID = "YOUR_CHATBOT_ID"
HEADERS = {"Authorization": f"Api-Key {API_KEY}"}
WAIT_FOR_WEBHOOK_SECONDS = 900  # 等推送的上限，超過就改查 Location


def now_iso() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="microseconds")


def upload_attachment(path: str) -> dict:
    """上傳附件，回傳要放進 message.attachments 的物件。"""
    with open(path, "rb") as f:
        resp = requests.post(f"{BASE_URL}/api/v1/attachments-upload/", headers=HEADERS, files={"file": f}, timeout=120)
    resp.raise_for_status()
    attachment = resp.json()
    return {key: attachment[key] for key in ("id", "type", "filename", "file")}


def poll_location(conn, question_id: str, location: str, retry_after: int, max_poll_seconds: int = 1800) -> str:
    """依 202 的 Location 查詢，直到 done 或 failed。"""
    deadline = time.monotonic() + max_poll_seconds
    while time.monotonic() < deadline:
        resp = requests.get(urljoin(BASE_URL, location), headers=HEADERS, timeout=30)
        resp.raise_for_status()
        body = resp.json()
        if body["status"] == "done":
            store.save_reply(conn, body["messageId"], body["conversationId"], "chatbot", body["content"], now_iso())
            store.set_result(conn, question_id, "answered", body["messageId"])
            return body["content"]
        if body["status"] == "failed":
            store.set_result(conn, question_id, "failed")
            raise RuntimeError(f"{body['code']}: {body['reason']}")
        time.sleep(retry_after)
    raise TimeoutError(f"still processing: {location}")


def wait_for_answer(conn, question_id: str, location: str, retry_after: int) -> str:
    """等 Webhook 把回覆推來；等不到（例如推送重送 3 次都失敗）就改查 Location。"""
    deadline = time.monotonic() + WAIT_FOR_WEBHOOK_SECONDS
    while time.monotonic() < deadline:
        status, content = store.get_question(conn, question_id)
        if status == "answered":
            return content
        time.sleep(retry_after)
    return poll_location(conn, question_id, location, retry_after)


def ask(question_id: str, content: str, attachments: list | None = None, conversation_id: str | None = None,
        max_attempts: int = 20) -> str:
    """question_id 是你系統裡這一題的 ID；同一個對話請等前一題有結果再問下一題。"""
    conn = store.connect()
    payload = {
        "conversation": conversation_id,
        "message": {"content": content, "attachments": attachments or []},
        "isStreaming": False,
    }
    for _ in range(max_attempts):
        sent_at = now_iso()  # 送出前記下時間，用來排除這一題之前的回覆
        resp = requests.post(
            f"{BASE_URL}/api/v1/chatbots/{CHATBOT_ID}/completions/",
            headers=HEADERS,
            json=payload,
            timeout=600,  # 留得比平台等待上限長，讓平台有機會先回 202
        )
        resp.raise_for_status()
        body = resp.json()
        payload["conversation"] = body["conversationId"]

        if resp.status_code == 200:
            if body["messageId"] is None:
                # 對話已轉真人：AI 不回答這一題，真人的回覆之後由 Webhook 推來（sender.type 為 user）
                return f"[轉真人：{body['progressStatus']}] {body['content']}"
            store.add_question(conn, question_id, body["conversationId"], sent_at, reply_id=body["messageId"])
            store.save_reply(conn, body["messageId"], body["conversationId"], "chatbot", body["content"], sent_at)
            return body["content"]  # 同一則回覆稍後也會推送，接收端會以回覆 ID 去重

        location = resp.headers.get("Location")
        retry_after = int(resp.headers.get("Retry-After", 5))
        if body["status"] == "processing" or body.get("messageCreated"):
            # 202 已收下：不要重送，等回覆
            store.add_question(conn, question_id, body["conversationId"], sent_at)
            return wait_for_answer(conn, question_id, location, retry_after)

        # 202 沒收下：這個對話先前的附件還在處理（前一題的回覆由送出它的流程處理），隔幾秒再送
        time.sleep(retry_after)
    raise RuntimeError("對話的附件一直在處理中，請稍後再送")


if __name__ == "__main__":
    files = [upload_attachment(path) for path in sys.argv[1:]]
    print(ask(str(uuid.uuid4()), "請摘要這份文件" if files else "你好，請介紹你自己", files))
```

{% endcode %}

執行方式：

```bash
# 1. 啟動接收端，並讓 https://your-system.example.com/maiagent/reply 轉到這裡（填進 Webhook URL）
MAIAGENT_WEBHOOK_SECRET=YOUR_RANDOM_SECRET flask --app receiver run --port 8080

# 2. 另開一個終端機，把 ask.py 的 API_KEY、CHATBOT_ID 換成你的
python ask.py                # 不帶附件：通常拿到 200，回覆直接印出，稍後的推送會被去重
python ask.py document.pdf   # 一般模式帶文件附件：在等待上限內處理完並回答就拿到 200、直接印出；否則拿到 202，回覆由 Webhook 推來後印出
```

`ask.py` 用「送出前的時間」排除這一題之前就存在的回覆，請確認執行它的主機時間已校正。排隊中的等候提醒也以 `sender.type: "chatbot"` 推送，範例沒有排除；等待中途可能轉真人的串接，請再依推送的 `conversation.progress_status` 判斷。

## 串流回應格式 <a href="#streaming-format" id="streaming-format"></a>

`isStreaming: true` 時，回應的 `Content-Type` 為 `text/event-stream`。每個事件是一行 `data: <JSON>`，事件之間以一個空行分隔：

```
data: {"conversationId": "c6a4…", "content": "你好", "done": false, "reset": false, "citations": null, "citationNodes": null, "contentPayload": {"content": "你好", "items": [{"type": "text", "text": "你好", …}], "metadata": null}, "messageId": null}

data: {"conversationId": "c6a4…", "content": "，我是", "done": false, "reset": false, …, "messageId": null}

data: {"conversationId": "c6a4…", "content": "", "done": true, "reset": false, "citations": […], "citationNodes": […], "contentPayload": {}, "messageId": "9f1e…"}
```

### 事件欄位 <a href="#frame-fields" id="frame-fields"></a>

所有欄位名稱都是 camelCase。

| 欄位               | 型別              | 說明                                                                                                                          |
| ---------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `conversationId` | string          | 對話 ID。建立新對話時從這裡取得，後續請求帶入 `conversation` 即可延續對話                                                                              |
| `content`        | string          | 這個事件**新增**的文字片段（增量，不是累計全文）。思考過程、工具呼叫、引用與心跳事件的 `content` 為空字串                                                                |
| `done`           | boolean         | `true` 表示這是最後一個事件，之後伺服器會關閉連線                                                                                                |
| `reset`          | boolean         | `true` 時，要用這個事件的 `content` **整段取代**目前已顯示的文字，見 [reset 何時出現](#reset)。少數事件不帶此欄位，視為 `false`                                     |
| `citations`      | array 或 `null`  | 回覆引用的知識庫檔案。只在 `done: true` 的事件帶值，且該 Agent 的 API 對話平台須開啟引用顯示，否則為 `null`                                                      |
| `citationNodes`  | array 或 `null`  | 回覆引用的段落。在 `done: true` 的事件帶值；開啟行內引用時，檢索完成後也可能先送一個 `content` 為空、只帶 `citationNodes` 的事件                                       |
| `contentPayload` | object          | 結構化內容，`items` 陣列的每一項以 `type` 區分，例如 `text`、`thinking`（需開啟思考過程顯示）、`tool_use`、`tool_result`、`client_tool_call`。只需要文字的整合可以略過此欄位 |
| `messageId`      | string 或 `null` | AI 回覆訊息的 ID。回覆存檔後才有值，所以串流途中都是 `null`，通常只在 `done: true` 的事件出現                                                                |

### 前端處理規則 <a href="#client-handling" id="client-handling"></a>

依序處理每個事件：

1. `reset` 為 `true`：以這個事件的 `content` 取代目前累積的文字（`content` 可能是空字串，代表清空）。
2. 其他事件：把 `content` 接在累積文字後面。`content` 為空的事件照接即可，不需特別判斷。
3. `done` 為 `true`：處理完這個事件後結束，從中取得 `messageId`、`citations`、`citationNodes`。

`done: true` 的事件通常 `content` 為空字串，因為文字已經在前面的事件送完。以下情況它會帶內容：整段回覆沒有串出任何片段（例如輸入被攔下），這時 `content` 是完整回覆；Hook 改寫回覆時則帶 `reset: true` 與完整內容。依上面的規則處理，兩種情況都會得到正確結果。

### reset 何時出現 <a href="#reset" id="reset"></a>

* **輸出 Hook 改寫或攔截了回覆**：最後一個事件會是 `done: true`、`reset: true`，`content` 是改寫後的完整內容或攔截提示。如果前端只把 `content` 往後接，先前已串出的原始內容（包括被攔下的內容）會留在畫面上。
* **模型重新產生回覆**：串流途中送出 `reset: true`、`content` 為空的事件，表示清空已顯示的文字，之後的事件是重新產生的內容（例如模型輸出異常，改送錯誤說明）。

{% hint style="warning" %}
`reset` 一定要處理。只做「把 `content` 往後接」的整合，在 Hook 攔截回覆時會把不該顯示的內容留在使用者畫面上。
{% endhint %}

### 心跳 <a href="#heartbeat" id="heartbeat"></a>

串流期間，伺服器每 15 秒送一個 `content` 為空、`done: false` 的事件，避免連線被中間的 Proxy 或負載平衡器判定閒置而切斷。依處理規則接上空字串即可。

### 結束條件與錯誤 <a href="#end-and-errors" id="end-and-errors"></a>

* **正常結束**：收到 `done: true` 的事件，伺服器隨即關閉連線。
* **產生回覆時出錯或逾時**：多數情況下，錯誤或逾時說明會當成回覆文字送出，最後仍以 `done: true` 結束；依處理規則就能正確顯示。
* **非預期錯誤**：伺服器送出一個 `event: error` 事件後關閉連線，**不會**再送 `done: true`：

  ```
  event: error
  data: {"error": "Internal server error", "conversationId": "c6a4…"}
  ```
* **連線提早中斷**：在收到 `done: true` 或 `event: error` 之前連線就斷了，請視為未完成。伺服器端仍會把回覆產生完並存檔，稍後可用 `GET /api/v1/messages/?conversation={conversationId}` 查詢該對話的訊息取得結果。

### 不會進入串流的情況 <a href="#non-streaming-cases" id="non-streaming-cases"></a>

即使 `isStreaming` 為 `true`，以下情況的回應也不是逐段的 SSE：

| 情況                            | 回應                                                                                                                                                                              |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 請求驗證失敗、Credits 不足等，在開始回覆前就被擋下 | 一般 JSON 錯誤回應與對應的 4xx 狀態碼，不是 SSE                                                                                                                                                 |
| 這個對話還有附件在處理                   | HTTP `202`，JSON 內容 `status: "pending_attachments"`，不是 SSE。`messageCreated` 為 `true` 時訊息已收下、回覆會自動產生，不要重送；為 `false` 時這次的內容沒有被收下，見[附件還在處理](#accepted-202)                          |
| 對話已轉由真人客服處理                   | SSE 只有一個 `done: true` 的事件，`content` 為排隊或轉接提示，`messageId` 為 `null`，另帶 `progressStatus`。詳見[第三方客服系統串接](https://docs.maiagent.ai/tech/serve/customer-service-system-integration.md) |
| Agent 設定為 JSON 結構化輸出          | 回覆會先完整產生，SSE 只有一個 `done: true` 的事件，`content` 為完整內容                                                                                                                              |

### 範例程式 <a href="#examples" id="examples"></a>

以下範例會累積回覆文字、處理 `reset` 與 `event: error`，並在 `done: true` 時回傳結果。請在自己的後端執行，不要把 API Key 放在瀏覽器前端。

{% tabs %}
{% tab title="Python" %}
需要 `requests`（`pip install requests`）。

```python
import json

import requests

API_KEY = "YOUR_API_KEY"
CHATBOT_ID = "YOUR_CHATBOT_ID"


def stream_reply(content, conversation_id=None):
    response = requests.post(
        f"https://api.maiagent.ai/api/v1/chatbots/{CHATBOT_ID}/completions/",
        headers={"Authorization": f"Api-Key {API_KEY}"},
        json={
            "conversation": conversation_id,
            "message": {"content": content},
            "isStreaming": True,
        },
        stream=True,
        timeout=(10, 300),
    )
    response.raise_for_status()
    if response.status_code == 202:
        # 附件還在處理（pending_attachments）：messageCreated 為 True 時訊息已收下、不要重送，改依 Location 查詢回覆；
        # 為 False 時這次的內容沒有被收下，取得前一則提問的回覆後再送（見「附件還在處理」與「輪詢範例」）
        return {"accepted": response.json(), "location": response.headers.get("Location")}

    text = ""
    event = "message"
    # 回應沒有宣告 charset，逐行以 bytes 讀取後自行用 UTF-8 解碼
    for raw_line in response.iter_lines(chunk_size=None):
        line = raw_line.decode("utf-8")
        if not line:
            event = "message"
            continue
        if line.startswith("event:"):
            event = line[len("event:"):].strip()
            continue
        if not line.startswith("data:"):
            continue

        frame = json.loads(line[len("data:"):])
        if event == "error":
            raise RuntimeError(f"串流錯誤：{frame['error']}（對話 {frame['conversationId']}）")

        if frame.get("reset"):
            text = frame["content"]
        else:
            text += frame["content"]

        if frame["done"]:
            return {
                "conversation_id": frame["conversationId"],
                "message_id": frame.get("messageId"),
                "text": text,
                "citations": frame.get("citations"),
            }

    raise RuntimeError("連線在收到 done 之前中斷")


result = stream_reply("你好，請介紹你自己")
print(result["text"])
```

{% endtab %}

{% tab title="JavaScript（Node.js 18+）" %}
使用內建的 `fetch`，不需安裝套件。

```javascript
const API_KEY = "YOUR_API_KEY";
const CHATBOT_ID = "YOUR_CHATBOT_ID";

async function streamReply(content, conversationId = null, onUpdate = () => {}) {
  const response = await fetch(
    `https://api.maiagent.ai/api/v1/chatbots/${CHATBOT_ID}/completions/`,
    {
      method: "POST",
      headers: {
        Authorization: `Api-Key ${API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        conversation: conversationId,
        message: { content },
        isStreaming: true,
      }),
    },
  );
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  }
  if (response.status === 202) {
    // 附件還在處理：accepted.messageCreated 為 true 時依 Location 查詢回覆、不要重送；
    // 為 false 時這次的內容沒有被收下，取得前一則提問的回覆後再送（見「附件還在處理」）
    return { accepted: await response.json(), location: response.headers.get("Location") };
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let buffer = "";
  let text = "";

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    let boundary;
    while ((boundary = buffer.indexOf("\n\n")) !== -1) {
      const rawEvent = buffer.slice(0, boundary);
      buffer = buffer.slice(boundary + 2);

      let eventName = "message";
      let data = "";
      for (const line of rawEvent.split("\n")) {
        if (line.startsWith("event:")) eventName = line.slice(6).trim();
        else if (line.startsWith("data:")) data += line.slice(5).trim();
      }
      if (!data) continue;

      const frame = JSON.parse(data);
      if (eventName === "error") {
        throw new Error(`串流錯誤：${frame.error}（對話 ${frame.conversationId}）`);
      }

      // reset 為 true 時整段取代，否則接在後面
      text = frame.reset ? frame.content : text + frame.content;
      onUpdate(text);

      if (frame.done) {
        return {
          conversationId: frame.conversationId,
          messageId: frame.messageId,
          text,
          citations: frame.citations,
        };
      }
    }
  }
  throw new Error("連線在收到 done 之前中斷");
}

streamReply("你好，請介紹你自己").then((result) => console.log(result.text));
```

`onUpdate` 每次收到事件時會拿到目前的完整文字，可用來更新畫面。
{% endtab %}
{% endtabs %}

注意事項：

* 回應中的 `conversationId` 可用於後續請求的 `conversation`，延續同一段對話
* 串流途中連線中斷不會取消伺服器端的回覆，請勿為了「重試」立刻重送同一則訊息，否則會在對話中產生重複的訊息

## 工具呼叫期間的事件 <a href="#tool-call-frames" id="tool-call-frames"></a>

Agent 模式下，模型可能先呼叫工具再回答。這時串流與同步回應的表現如下：

* **串流**：工具呼叫本身以 `contentPayload.items` 的 `tool_use`、`tool_result` 項目送出，這些事件的 `content` 是空字串；模型在呼叫工具之前與之後產生的文字，都會以 `content` 增量送出。依[前端處理規則](#client-handling)把 `content` 往後接，得到的就是整段回覆。
* **同步**（`isStreaming: false`）：`content` 是整段回覆的文字，包含工具呼叫前後的文字；工具呼叫的過程在 `contentPayload.items` 依發生順序列出。
* 沒有「只回傳最後一段」的參數。只想顯示最後的回答時，取 `contentPayload.items` 中最後一個 `type: "text"` 項目。
* `done: true` 一律代表整個回合結束（含所有工具呼叫），不會在工具呼叫中途出現。

工具呼叫的輪數上限與逾時由 Agent 的進階設定決定，見 [Function Calling：執行上限](https://docs.maiagent.ai/tech/advanced-genai-tech/function-calling.md#limits)。

## 以 API 使用 Code Interpreter <a href="#code-interpreter" id="code-interpreter"></a>

Code Interpreter 不是工具 ID，不要放進 `message.toolIds`。它是 Agent 的設定：在後台開啟（見使用者手冊 [Code Interpreter](https://docs.maiagent.ai/build/agent/code-interpreter#what-do-i-need-to-do)），或用 `PATCH /api/v1/chatbots/{chatbotId}/` 把 `enableCodeInterpreter` 設為 `true`；Agent 的 `replyMode` 必須是 `agent`。設定後，對這個 Agent 的 `completions` 請求不需要任何額外欄位，模型會自行決定何時執行程式；Canvas 與 Agent Teams 都不是前提。

產出的檔案不會以附件物件出現在回覆裡，取得方式見[對話產出清單 API](https://docs.maiagent.ai/tech/api-integration/endpoint-behaviors/conversation-outputs-api.md)。`/api/v1/chatbots/{chatbotId}/completions/` 是 Agent 的對話端點；名稱相近的 `/api/v1/chat/completions/` 是 [AI Gateway](https://docs.maiagent.ai/tech/ai-gateway/ai-gateway-openai-compatible.md) 的 OpenAI 相容端點，直接呼叫模型、不經過 Agent 設定，也沒有 Code Interpreter。

## 省略 `message.sender` 時的身分 <a href="#anonymous-sender" id="anonymous-sender"></a>

`message.sender` 填聯絡人 ID，用來指定「是誰在問」。省略時不是匿名，而是：

* **建立新對話**（`conversation` 為 `null`）時，對話的聯絡人是 **API 金鑰綁定的成員**在這個對話平台上的聯絡人（第一次呼叫時自動建立，`sourceId` 為該成員的使用者 ID）。用同一把金鑰、都不帶 `sender` 建立的對話，全部歸在這位聯絡人底下：對話歷史、持久記憶、聯絡人的 `queryMetadata` 與工具憑證都以它為準，用量與 Credits 也歸屬到這位成員。
* **延續既有對話**（帶 `conversation`）時，聯絡人沿用該對話原本的聯絡人，`sender` 不會改變它。

要讓每位終端使用者各自擁有對話歷史與權限，請先建立聯絡人並在每次請求帶 `sender`，見[聯絡人 (Contact) 介紹及串接](https://docs.maiagent.ai/tech/serve/contacts.md)。

## 內容長度與上下文 <a href="#content-limits" id="content-limits"></a>

* `message.content` 是字串，平台沒有另外設定字元數上限；有附件時可以是空字串，沒有附件時不能為空（回 `400`）。
* 實際的上限是模型的 context window：這則訊息、對話歷史、檢索到的知識庫段落、附件解析後的文字與角色指令都算在內。超出時模型端會回錯誤，平台把錯誤說明當成回覆文字送出並以 `done: true` 結束（見[結束條件與錯誤](#end-and-errors)），不會回 `413`。
* 長文請改用附件上傳，或拆成多則訊息；回覆長度由 Agent 的「回覆長度與 Agent 執行上限」設定控制，見使用者手冊 [回覆長度與 Agent 執行上限](https://docs.maiagent.ai/build/agent/custom-max-tokens)。

## 對話 ID 的有效期與錯誤 <a href="#conversation-lifecycle" id="conversation-lifecycle"></a>

* 對話沒有到期時間，也沒有輪數上限；只要對話沒有被刪除，`conversationId` 就可以一直延續。對話附件另有保留天數，到期後附件檔案會被刪除，見[對話附件管理 API](https://docs.maiagent.ai/tech/api-integration/endpoint-behaviors/conversation-attachments.md)。
* `conversation` 填了不存在或已刪除的 ID 時回 `400`，內容是欄位錯誤：`{"conversation": ["Invalid pk \"…\" - object does not exist."]}`；不屬於這把金鑰所在組織的對話同樣會被拒絕。收到這類錯誤時請改以 `null` 建立新對話，不要重試同一個 ID。
* 延續的對話已轉由真人客服處理時，回應不是一般的 AI 回覆，見[不會進入串流的情況](#non-streaming-cases)。

## 真人回覆寫回對話 <a href="#outgoing-message" id="outgoing-message"></a>

自家客服系統要將真人回覆寫回 MaiAgent 對話時，使用 `POST /api/v1/messages/outgoing/`，而非向 AI 發問的 Completions 端點。所需權限、欄位、呼叫範例與轉真人生命週期，統一見[第三方客服系統串接：串接流程](https://docs.maiagent.ai/tech/serve/customer-service-system-integration.md#scenario-b-flow)。

## 串接成果

{% embed url="<https://drive.google.com/file/d/1sCIoxxASZ-SnHPAmkjDT270B3dz0LyHo/view?usp=sharing>" %}


---

# 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/dui-hua-yu-xun-xi-hui-fu-chuan-liu-tong-bu.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.
