> 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/api/preparation/conventions.md).

# API 共通規範

呼叫 MaiAgent 平台 API 的共通規則：網址與版本前綴、API Key 認證、速率限制、錯誤回應與狀態碼、分頁、欄位格式與上傳大小上限

本頁整理所有平台 API 共用的規則：網址、認證、限流、錯誤回應、分頁、欄位格式與上傳上限。各端點的欄位與範例見左側「API 端點說明文件」，本頁的規則適用於全部端點，端點頁不再重複。建議在開始寫程式前讀過一次。

{% hint style="info" %}

* 建立與管理 API Key 的畫面操作見使用者手冊 [API Key 管理](https://docs.maiagent.ai/org/developer/api-keys)；查呼叫紀錄見 [API 呼叫紀錄](https://docs.maiagent.ai/org/developer/api-logs)。
* 從零開始串接的步驟見技術人員手冊 [快速上手](https://docs.maiagent.ai/tech/api-integration/quickstart)。
  {% endhint %}

## 網址與版本前綴 <a href="#base-url" id="base-url"></a>

SaaS 的 API 網址是 `https://api.maiagent.ai/api/v1/`；地端與私有雲部署請換成貴公司的平台網域。

* `/api/` 與 `/api/v1/` 掛的是同一套端點，路徑、欄位與權限都相同。
* AI Gateway（OpenAI 相容端點）與 SCIM **只在 `/api/v1/` 底下**。
* 新的整合請一律使用 `/api/v1/`。
* 端點路徑以 `/` 結尾。少了結尾的 `/` 會收到 `301` 轉址到加上 `/` 的網址；部分 HTTP 用戶端跟隨轉址時會把 `POST` 改成 `GET`，請直接呼叫帶 `/` 的網址。

## 認證 <a href="#authentication" id="authentication"></a>

伺服器對伺服器的呼叫使用 API Key，放在 `Authorization` 標頭：

```
Authorization: Api-Key <您的 API Key>
```

金鑰由前綴與密鑰兩段英數字組成，中間以 `.` 相連，請完整帶入。

| 規則         | 說明                                                                                                              |
| ---------- | --------------------------------------------------------------------------------------------------------------- |
| 金鑰綁定一位成員   | 呼叫時的組織就是這位成員所屬的組織，請求不需要另外帶組織 ID                                                                                 |
| 權限等於該成員的角色 | 沒有依端點細分的 scope；成員能做的事，金鑰都能做。缺少權限回 `403`，見 [API 金鑰的權限範圍](/api/preparation/authentication.md#api-key-permissions) |
| 成員停用即失效    | 成員被停用或移出組織後，這把金鑰立即無法使用                                                                                          |
| 到期、停用、撤銷   | 和不存在的金鑰一樣回 `401`，回應不會說明原因                                                                                       |
| 完整金鑰只顯示一次  | 建立後只會顯示部分字元，遺失請重新建立                                                                                             |

金鑰的建立與管理入口見 [API 認證方式](/api/preparation/authentication.md)。

### 認證失敗的回應 <a href="#auth-errors" id="auth-errors"></a>

沒帶金鑰、標頭格式不對，或金鑰無效（不存在、已到期、已停用、已撤銷，或綁定的成員已停用、已移出組織）都回 `401`，內容相同：

```json
{"detail": "Authentication credentials were not provided."}
```

* 金鑰無效時，訊息同樣是「沒有提供認證資訊」：平台把認不得的金鑰當成沒有帶憑證，不會說明是哪一種原因。
* 回應帶 `WWW-Authenticate` 標頭。多數端點的值是 `Bearer realm="api"`（這些端點也接受 OAuth 存取權杖）；只接受 API Key 的端點（例如下方的 `api-key-context`）是 `Api-Key`。請以 `401` 狀態碼判斷，不要依這個標頭的值決定要帶哪一種憑證。
* 把 API Key 放在 `Bearer` 後面，平台會把它當成登入權杖驗證，回 `401` 與不同的內容：

```json
{"detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ … ]}
```

收到這個回應時，請把標頭改成 `Api-Key <金鑰>`。

{% hint style="warning" %}
**整合用金鑰的建議**：建一位專用的整合成員，只給它需要的角色權限，再用它的身分簽發金鑰並設定到期時間。綁在個人帳號上的金鑰，會在這位員工離職、帳號被停用時一起失效，整合也跟著中斷。API Key 請只放在伺服器端：平台 API 只對允許的網域開放跨來源（CORS）呼叫，也不應該讓金鑰出現在瀏覽器裡。
{% endhint %}

### 確認金鑰所屬的組織 <a href="#api-key-context" id="api-key-context"></a>

要在自家閘道先確認金鑰屬於哪個組織，可以呼叫 `GET /api/v1/users/api-key-context/`，回應 `{"organizationId": "…"}`。這支端點只接受 API Key，不計入金鑰的 RPM。

### 其他憑證 <a href="#other-credentials" id="other-credentials"></a>

讓 MCP 客戶端以成員身分連線，見技術人員手冊 [MaiAgent 作為 OAuth 授權伺服器](https://docs.maiagent.ai/tech/identity-and-access/maiagent-oauth-server)；在自家系統嵌入 MaiGPT 的成員權杖，見 [串接 MaiGPT：成員身分嵌入](https://docs.maiagent.ai/tech/work/maigpt-system-integration-guide/maigpt-integration#member-embed)。

## 速率限制 <a href="#rate-limits" id="rate-limits"></a>

平台 API **沒有全域的預設上限**。會限流的只有下表這些：

| 範圍                                                | 上限               | 計算方式                   | 誰可以調整                                                                                               |
| ------------------------------------------------- | ---------------- | ---------------------- | --------------------------------------------------------------------------------------------------- |
| 每把 API Key 的請求數（RPM）                              | 管理者設定，未設定時不限     | 每把金鑰、每 60 秒            | 組織的 <mark style="color:blue;">API Key 管理</mark>                                                     |
| AI Gateway 的 Token 數（TPM）                         | 管理者設定，未設定時不限     | 每把金鑰、每分鐘，只算 Gateway 推論 | 同上，見 [AI Gateway 的限制](https://docs.maiagent.ai/tech/ai-gateway/ai-gateway-openai-compatible#limits) |
| SCIM 端點                                           | 100 次／分鐘         | 每個組織                   | 固定                                                                                                  |
| `web-chats/{id}/setup-contact-credentials/`       | 30 次／分鐘          | 每個來源 IP                | 固定                                                                                                  |
| 免登入的計價查詢（`credit/items/`、`credit/pricing-rules/`） | 60 次／分鐘          | 每個來源 IP                | 固定                                                                                                  |
| `auth/login/`                                     | 預設 10 次／分鐘       | 每個來源 IP                | 平台設定                                                                                                |
| 不帶憑證的 Web Chat 請求（接續對話、上傳附件等）                     | 10～30 次／分鐘，依端點而定 | 每個來源 IP                | 固定                                                                                                  |

* 金鑰的 RPM 作用在這把金鑰能呼叫的平台 API，不只 AI Gateway。表中有固定上限的端點使用自己的上限，不計入金鑰的 RPM。
* OAuth 存取權杖與後台登入的請求不受金鑰 RPM 限制。
* 超過上限回 `429`，並帶 `Retry-After` 標頭（秒數）。請依這個秒數退避後再重試，不要立刻重送。

```json
{"detail": "Request was throttled. Expected available in 42 seconds."}
```

## 錯誤回應 <a href="#errors" id="errors"></a>

平台 API 沒有統一的錯誤碼表。處理錯誤時請依 **HTTP 狀態碼**判斷，回應帶 `code` 時再依 `code` 細分；**不要比對 `detail` 文字**：文字會隨 `Accept-Language` 翻譯，也可能調整措辭。

### 回應內容的形狀 <a href="#error-shapes" id="error-shapes"></a>

| 形狀          | 範例                                                                 | 常見於                                                      |
| ----------- | ------------------------------------------------------------------ | -------------------------------------------------------- |
| `detail` 物件 | `{"detail": "You do not have permission to perform this action."}` | 認證、權限、找不到、限流、方案與 Credits；少數會多帶 `code` 或其他欄位              |
| 欄位物件        | `{"name": ["This field is required."]}`                            | 欄位驗證失敗；key 是 camelCase 欄位名，不屬於單一欄位的錯誤放在 `nonFieldErrors` |
| 字串陣列        | `["…"]`                                                            | 少數沒有對應欄位的驗證錯誤                                            |

例外情況：

* **AI Gateway** 的 OpenAI 相容端點使用 OpenAI 格式的 `error` 物件，見 [AI Gateway 錯誤格式](https://docs.maiagent.ai/tech/ai-gateway/ai-gateway-openai-compatible#errors)。
* **SCIM** 端點的請求內容錯誤、找不到與衝突，依 SCIM 2.0 規格回應（`schemas`、`status`、`detail`）。
* **網址不存在**（路徑打錯、少了資源 ID）時回 `404`，內容是 HTML，不是 JSON；`5xx` 回應也不保證是 JSON。解析回應前請先確認 `Content-Type`。

### 狀態碼 <a href="#status-codes" id="status-codes"></a>

| 狀態碼               | 意義                                                                   | 建議處理                                                                                                                             |
| ----------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `200`／`201`／`204` | 成功；`204` 沒有回應內容，常見於刪除                                                | —                                                                                                                                |
| `202`             | 已受理但尚未完成，例如同步回覆時附件還在建立索引，回應 `status: "pending_attachments"`          | 稍後重試，見 [不會進入串流的情況](https://docs.maiagent.ai/tech/api-integration/dui-hua-yu-xun-xi-hui-fu-chuan-liu-tong-bu#non-streaming-cases) |
| `301`             | 路徑少了結尾的 `/`                                                          | 改用帶 `/` 的網址                                                                                                                      |
| `400`             | 欄位驗證失敗；資源 ID 不是有效的 UUID 時，多數端點回 `{"detail": "Invalid UUID format."}` | 修正請求，不要重試                                                                                                                        |
| `401`             | 沒帶憑證或憑證無效，見 [認證失敗的回應](#auth-errors)                                  | 檢查金鑰與標頭格式，不要重試                                                                                                                   |
| `402`             | 方案、Credits 或額度不足，見 [下方說明](#payment-required)                         | 通知組織管理者                                                                                                                          |
| `403`             | 角色權限不足、組織未開通該功能、組織已停用，或字數計費方案的用量已達上限                                 | 調整角色權限或洽窗口                                                                                                                       |
| `404`             | 資源不存在、不屬於金鑰所屬的組織，或網址打錯                                               | 確認 ID、金鑰所屬組織與路徑                                                                                                                  |
| `409`             | 與資源目前的狀態衝突，例如同一件工作已在執行中、要刪除的資源仍被引用                                   | 讀回最新狀態再決定，不要原樣重送                                                                                                                 |
| `429`             | 超過速率限制                                                               | 依 `Retry-After` 退避                                                                                                               |
| `5xx`             | 平台或上游服務錯誤                                                            | 指數退避後重試                                                                                                                          |

`409` 的回應是 `detail` 物件，部分端點會附上處理所需的欄位，例如知識庫已有 FAQ 匯入在執行時：

```json
{"detail": "An FAQ import is already running for this knowledge base.", "jobId": "…"}
```

### 402：方案、Credits 或額度不足 <a href="#payment-required" id="payment-required"></a>

| 情況                       | 回應內容                                                                                   | 有沒有 `code`         |
| ------------------------ | -------------------------------------------------------------------------------------- | ------------------ |
| 組織沒有有效的付費方案              | `{"detail": "Your organization has no active paid plan. …", "code": "no_active_plan"}` | 有，`no_active_plan` |
| 組織 Credits 不足            | `{"detail": "Insufficient credits …"}`，文字依端點而異                                         | 沒有                 |
| 成員的個人額度用完或未分配，或所屬角色的額度用完 | `{"detail": "Personal credit quota exhausted. …"}`，文字依情況而異                             | 沒有                 |

* 只有「沒有有效的付費方案」會帶 `code`。Credits 不足與額度用完的回應只有 `detail`，目前無法只從回應內容分辨是組織 Credits 不足，還是個人或角色額度用完，請組織管理者到後台確認。
* Credits 與額度在會產生用量的寫入請求檢查，例如送出訊息、知識庫檔案上傳與搜尋、網頁爬取；查詢類的 `GET` 請求不會因此回 `402`。
* AI Gateway 的 OpenAI 相容端點回 OpenAI 格式：`{"error": {"type": "billing_error", "code": "insufficient_credits", …}}`，沒有有效方案時也是這個 `code`。
* 平台未啟用 Credits 計費時（部分地端部署），不會出現這類 `402`。

## 分頁 <a href="#pagination" id="pagination"></a>

多數列表端點用頁碼分頁：

| 參數                          | 說明                                                  |
| --------------------------- | --------------------------------------------------- |
| `page`                      | 頁碼，從 1 開始；超出範圍回 `404` `{"detail": "Invalid page."}` |
| `page_size`（也可寫 `pageSize`） | 每頁筆數，預設 20、上限 100；超過 100 會自動截成 100，不會報錯             |

回應格式為 `{"count": …, "next": "…", "previous": "…", "results": [ … ]}`，取下一頁時直接使用 `next` 的網址，沒有下一頁時為 `null`。

另外兩種情況：

* **游標分頁**：對話列表（`GET /api/v1/conversations/`）與訊息列表（`GET /api/v1/messages/`）用 `cursor` 參數，由新到舊翻頁，以 `next` 取更早的資料。訊息列表的回應帶 `count`，對話列表沒有；訊息列表每一頁內的訊息依時間由舊到新排列。
* **不分頁**：部分清單直接回傳陣列，例如 `GET /api/v1/credit/items/`。

各端點屬於哪一種，以該端點頁的回應範例為準。

## 欄位格式 <a href="#field-format" id="field-format"></a>

* **命名**：回應的 key 一律是 camelCase。請求的 JSON 與查詢參數可以用 camelCase，snake\_case 也接受。少數自由格式的欄位內容會原樣保留、不轉換大小寫，例如 JSON Schema、自訂 HTTP 標頭與 metadata。
* **時間**：多數時間欄位輸出為 Unix 時間戳記的毫秒字串，例如 `"1759536000000"`，精度到秒（最後三位固定是 `000`）。少數欄位使用 ISO 8601 字串，以該端點頁為準。
* **小數**：金額、單價等小數欄位以字串輸出，例如 `"316.8000000000"`，請用十進位型別處理，避免浮點誤差。
* **ID**：資源 ID 多為 UUID。
* **語系**：錯誤訊息會依 `Accept-Language` 標頭翻譯（例如 `ja`），沒有翻譯的訊息維持英文，請勿依賴訊息文字。

## 上傳大小上限 <a href="#upload-limits" id="upload-limits"></a>

上傳上限由平台設定，可能調整，地端部署也可能不同。請以 `GET /api/v1/allowed-file-specs/` 的回應為準：這支端點不需認證，依用途列出允許的副檔名與 `maxSize`（位元組）。2026 年 10 月正式區的值如下：

| 用途                | 上限     |
| ----------------- | ------ |
| 知識庫檔案             | 100 MB |
| 對話附件：文件、試算表、簡報與音檔 | 10 MB  |
| 對話附件：圖片           | 5 MB   |
| 會議記錄音檔            | 100 MB |

* 以 Presigned 方式上傳時，取得上傳網址的 `POST /api/v1/upload-presigned-url/` 就會依 `fileSize` 與副檔名檢查，超過上限或類型不允許回 `400`。流程見技術人員手冊 [Presigned 檔案上傳模式](https://docs.maiagent.ai/tech/api-integration/api_knowledge)。
* 知識庫的中繼資料、標籤與 FAQ 的 Excel 匯入，共用知識庫檔案的上限。

## 常見問題 <a href="#faq" id="faq"></a>

<details>

<summary>金鑰明明是對的，卻一直回 401？</summary>

`401` 不會說明原因。請到 <mark style="color:blue;">API Key 管理</mark> 確認金鑰的狀態不是已停用、已過期或已撤銷，並確認綁定的成員仍是啟用狀態。標頭格式必須是 `Api-Key <金鑰>`；用 `Bearer` 會收到 `token_not_valid`，見 [認證失敗的回應](#auth-errors)。

</details>

<details>

<summary>可以限制某把金鑰只能呼叫特定 API 嗎？</summary>

不行。金鑰的權限就是綁定成員的角色權限，請用一位只有必要角色的整合成員來簽發金鑰。AI Gateway 另外可以限定一把金鑰能呼叫的模型，見 [AI Gateway：OpenAI 相容 API 串接](https://docs.maiagent.ai/tech/ai-gateway/ai-gateway-openai-compatible)。

</details>

<details>

<summary>為什麼 `/api/` 開頭的範例和 `/api/v1/` 都能用？</summary>

兩個前綴掛的是同一套端點。只有 AI Gateway 與 SCIM 必須用 `/api/v1/`，新整合請統一使用 `/api/v1/`。

</details>


---

# 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/api/preparation/conventions.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.
