> 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/work/maigpt-system-integration-guide.md).

# 把 MaiGPT 加進您的系統

把 MaiGPT 加進您自己的系統、給組織成員使用的端到端指南：從開通成員、換發 token、前端嵌入到登出與驗收，一頁讀完照著做

這一頁給「我們的系統要加上 MaiGPT」的工程師從頭讀到尾。不管您是企業自己的入口網站、內部工作台，還是替客戶代管的 SaaS，只要使用者是 **MaiAgent 組織的成員**（員工、承辦人），流程都一樣。每一步把要做的事直接寫在這裡，想深入才點連結。

{% hint style="info" %}
如果您的使用者是**您的客戶、會員或匿名訪客**、不是組織成員，MaiGPT 產品本身不能給他們用，請改走[自建 AI Agent＋MaiGPT 視窗模式](/tech/work/maigpt-system-integration-guide/maigpt-integration.md#build-agent)，聯絡人身分對接見[軟體廠商整合指南](/tech/serve/vendor-integration-guide.md)。
{% endhint %}

## 全貌 <a href="#overview" id="overview"></a>

```mermaid
flowchart LR
    A["1 開通成員<br/>SCIM／邀請／SSO"] --> B["2 後端換發成員 token<br/>組織 API Key"]
    B --> C["3 前端嵌入<br/>auth.getToken"]
    C --> D["4 登出與離職<br/>signOut／停用"]
    D --> E["5 驗收"]
```

做完之後：員工在您的系統登入，頁面裡直接出現 MaiGPT，能生圖、Deep Research、用連接器，權限、額度、對話歷史都跟著他在 MaiAgent 的成員身分；他不需要另外登入 MaiAgent，也不需要知道 MaiAgent 的存在。

## 開始前準備 <a href="#prerequisites" id="prerequisites"></a>

| 項目                               | 到哪拿                                                                                                                                             |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 一個 MaiAgent 組織，方案含 MaiGPT 與身分同步  | 不確定請洽業務                                                                                                                                         |
| 組織 API Key，持有者是組織擁有者或具「組織總覽」管理權限 | 取得方式見[快速上手](/tech/api-integration/quickstart.md)                                                                                                |
| MaiGPT 的 Web Chat ID             | `GET /api/v1/web-chats/` 回傳中名稱為 `MaiGPT`、`accessType` 為 `web` 的那一筆                                                                              |
| 角色先建好、權限先設好                      | 後台「組織設定 → 組織總覽 → 編輯角色權限」建例如「員工」角色，勾選 MaiGPT 使用權（[設定方式](https://docs.maiagent.ai/org/roles/maigpt-role-permissions)）。**成員的能力全部來自角色**，這步沒做，後面全部白做 |
| 決定成員從哪來                          | 下一節三選一                                                                                                                                          |

## 第一步：開通成員 <a href="#step-1" id="step-1"></a>

您的使用者要先是 MaiAgent 組織的成員。三種做法，選最省事的那個：

{% hint style="info" %}
組織裡已經有人在用 MaiAgent？接 SCIM 不會讓他們原本的帳號失效，也不會建立重複帳號；被接管的既有成員之後會跟著您的系統同步。細節見[既有帳號與成員會怎樣](/tech/identity-and-access/member-provisioning.md#scim-existing-accounts)。
{% endhint %}

{% tabs %}
{% tab title="您的系統有使用者管理（推薦）" %}
在您系統新增、修改、停用使用者的事件裡，順手呼叫 MaiAgent 的 SCIM 端點，成員即時一致。

1. 後台「組織設定 → 身份同步」選 SCIM，「連線資訊」分頁複製 Endpoint URL 與 Token（Token 只顯示一次，放伺服器環境變數）
2. 把[即時同步頁](/tech/identity-and-access/member-provisioning/member-event-sync.md)的 `MaiAgentMembers` client 放進您的專案，在事件裡呼叫：

```python
members = MaiAgentMembers()   # 讀環境變數 MAIAGENT_SCIM_URL / MAIAGENT_SCIM_TOKEN

# 新增使用者
user.maiagent_member_id = members.on_user_created(
    external_id=user.id, email=user.email, name=user.display_name, groups=["員工"],
)
# 改名、換部門
members.on_user_updated(user.maiagent_member_id, user.id, user.email, user.display_name, ["員工"])
# 停權、離職
members.on_user_deactivated(user.maiagent_member_id)
```

3. 第一次上線先把既有使用者跑一輪 `on_user_created`（冪等，[批次補建](/tech/identity-and-access/member-provisioning/member-event-sync.md#backfill)），之後靠事件維持。
   {% endtab %}

{% tab title="只有名單（HR 匯出、Excel、資料庫）" %}
用[名單同步工具](/tech/identity-and-access/member-provisioning/member-roster-sync.md)：準備一份四欄的 CSV 或 JSON（人員編號、Email、姓名、角色），設好 SCIM 連線環境變數，先 `--dry-run` 看計畫再真跑，之後排程每天跑一次。名單上有的建立或更新、名單上消失的停用。
{% endtab %}

{% tab title="有 Okta／Entra ID／JumpCloud" %}
把 SCIM 的 Endpoint URL 與 Token 填進 IdP 的 provisioning 設定，IdP 會自動推送使用者與群組。細節見[從 IdP 推送](/tech/identity-and-access/member-provisioning.md#scim-idp)。
{% endtab %}
{% endtabs %}

三件事要記得，都是實際整合時最常卡的：

* **角色名稱對上後台建好的角色**：SCIM 建成員時 `groups` 填的名稱，就是後台那個已設好權限的角色；名稱對不上會自動建一個**沒有權限**的新角色。
* **Email 是帳號的鍵**：`userName` 就是之後換發 token 用的 Email；建立後不能經 SCIM 改 Email。
* **SCIM 建的帳號沒有密碼**：這條路的員工不會登入 MaiAgent，這正是我們要的；若同時要開放 MaiGPT 網頁版或 App，另設 [SSO](/tech/identity-and-access/member-provisioning.md#sso)。

## 第二步：後端換發成員 token <a href="#step-2" id="step-2"></a>

在您的後端開一支只給**已登入使用者**呼叫的端點（例如 `GET /maigpt-token`），內部以組織 API Key 向 MaiAgent 換發該成員的短效 token：

```bash
curl -X POST https://api.maiagent.ai/api/v1/members/embed-tokens/ \
  -H "Authorization: Api-Key <您的組織 API Key>" \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@acme.com"}'
```

成功回 `201`：

```json
{
  "accessToken": "<成員短效 JWT>",
  "organizationId": "8d2f...-...",
  "expiresAt": 1789906401000,
  "member": { "id": "c1a4...", "userId": "5e77...", "email": "alice@acme.com", "name": "Alice" }
}
```

把整份回應原樣回給前端就好。規則與狀態碼：

| 事實                        | 說明                                                   |
| ------------------------- | ---------------------------------------------------- |
| 效期 15 分鐘、不發 refresh token | 續期由前端 SDK 自動處理（第三步），您的後端只要「被叫到就換一顆」——**每次都換新的，不要快取** |
| token 只能用在 MaiGPT 對話端點    | 拿去打 `/api/v1/` 任何 API 一律 `401`，外洩也不能碰組織資料            |
| `401`／`403`               | 沒用 Api-Key／Key 的持有者不是擁有者或組織管理員                       |
| `404`                     | 這個 Email 不是本組織的啟用成員——第一步沒做、或已被停用                     |
| 每次換發都留稽核紀錄                | 組織的 API 請求紀錄可查，回應中的 token 不會被記錄                      |

參數與更多細節見[成員 token 換發](/tech/work/maigpt-system-integration-guide/maigpt-integration.md#member-embed-issue)。

## 第三步：前端嵌入 <a href="#step-3" id="step-3"></a>

在要放 MaiGPT 的頁面加入嵌入碼，`auth.getToken` 指向第二步的端點；其餘都交給 SDK（初始化時取一次 token、到期前自動再取、同一則對話續用）：

```html
<div id="maigpt-container" style="height: 720px;"></div>
<script>
  window.maiagentChatbotConfig = {
    webChatId: '<MaiGPT 的 Web Chat ID>',
    baseUrl: 'https://chat.maiagent.ai/web-chats',
    enabledWindowModes: ['maigpt'],
    targetElement: '#maigpt-container',
    maigptTitle: 'Acme GPT',            // 選填：左上角品牌名
    locale: 'zh-TW',                    // 選填：介面語系
    auth: {
      getToken: async () => {
        const res = await fetch('/maigpt-token', { credentials: 'include' })
        const { accessToken, organizationId, member } = await res.json()
        return { accessToken, organizationId, sourceId: member.userId }
      },
    },
  }
</script>
<script src="https://chat.maiagent.ai/js/embed.min.js" defer></script>
```

{% hint style="danger" %}
`sourceId` 一定要填回應裡的 `member.userId`，不是 `member.id`、也不是您系統的使用者編號。MaiGPT 靠它把對話對應到成員，填錯會變成匿名對話、看不到該成員的歷史。
{% endhint %}

容器要自己給高度；SPA 要等容器 mount 後再載入 SDK；`baseUrl` 與 SDK 網址是 SaaS 位址，私有部署請換成您的網域。版面與其他參數見 [MaiGPT 模式嵌入](/tech/serve/web-chat-sdk/web-chat-maigpt-mode.md)。

## 第四步：登出與離職 <a href="#step-4" id="step-4"></a>

| 事件        | 您要做的事                                     | 結果                                      |
| --------- | ----------------------------------------- | --------------------------------------- |
| 使用者登出您的系統 | 前端呼叫 `MaiAgent.auth.signOut()`            | iframe 清掉身分並停止續期；已發出的 token 最多再存活 15 分鐘 |
| 使用者離職／停權  | 第一步的停用（`on_user_deactivated`、名單移除、IdP 停用） | 之後換發回 `404`，嵌入頁自然失效；對話與額度紀錄保留           |
| 復職        | 第一步的重新啟用                                  | 角色與歷史恢復                                 |

## 第五步：驗收 <a href="#step-5" id="step-5"></a>

依序確認，每一項都有明確的判斷點：

1. **成員存在且有角色**：後台「成員管理」看得到這個人，角色是您設好權限的那個。
2. **換發成功**：第二步 curl 回 `201`；換一個不存在的 Email 回 `404`。
3. **能對話**：嵌入頁開啟 MaiGPT、送一句話得到回覆；用該成員登入 MaiGPT 網頁版（若有 SSO）或後台對話紀錄能看到這則對話。
4. **能力對**：請它生一張圖；若角色有開連接器與 Deep Research，入口會出現。
5. **續期無感**：頁面停留超過 15 分鐘再送訊息，不用重新整理、同一則對話繼續。
6. **登出生效**：`signOut()` 後再送訊息被拒；停用該成員後第二步回 `404`。

## 上線後 <a href="#after-launch" id="after-launch"></a>

* **SCIM Token 與 API Key 輪換**：SCIM Token 建立超過 180 天後台會提醒；重新產生後舊的立即失效，記得同步更新伺服器環境變數。
* **方案容量**：成員數影響內建 Agent 席次與每成員 Credits 額度，見[成員 Credits 額度管理](https://docs.maiagent.ai/others/credits/member-credit-quota)。
* **稽核**：每次換發 token 都在組織的 API 請求紀錄；SCIM 的每次同步在後台「身份同步 → 同步紀錄」。

## 出錯時 <a href="#troubleshooting" id="troubleshooting"></a>

| 現象                              | 原因                                                 | 處理                                                               |
| ------------------------------- | -------------------------------------------------- | ---------------------------------------------------------------- |
| 換發回 `404`                       | Email 不是本組織啟用成員                                    | 回第一步確認成員存在、未停用、Email 相同（大小寫不分）                                   |
| 換發回 `403`                       | API Key 持有者不是擁有者也沒有組織管理權限                          | 換用管理員發的 Key                                                      |
| 聊天視窗「建立對話失敗（400）您沒有權限使用 MaiGPT」 | 成員的角色沒有 MaiGPT 使用權，或 `auth` 沒帶到                    | 後台角色權限開 MaiGPT；確認 `getToken` 有回 `accessToken` 與 `organizationId` |
| 對話是匿名的、看不到歷史                    | `sourceId` 填錯                                      | 用 `member.userId`                                                |
| 15 分鐘後送訊息失敗                     | `getToken` 沒被呼叫或失敗（看瀏覽器 console 的 `[MaiAgent]` 錯誤） | 確認端點對已登入使用者可用、回應格式正確                                             |
| 成員建好但什麼都不能用                     | 沒進任何角色，或角色權限是空的                                    | 後台角色權限設定；SCIM 用相同名稱指派                                            |
| 改了 Email 沒生效                    | SCIM 不允許變更 Email                                   | 後台修改，或停用舊帳號以新 Email 建立                                           |

更多 SCIM 錯誤碼見[名單同步工具的錯誤對照](/tech/identity-and-access/member-provisioning/member-roster-sync.md#errors)。

## 深入閱讀 <a href="#further-reading" id="further-reading"></a>

* [成員開通：SCIM／邀請／SSO](/tech/identity-and-access/member-provisioning.md) — SCIM API 完整參考、三條路對照
* [即時同步：在使用者事件中呼叫](/tech/identity-and-access/member-provisioning/member-event-sync.md)／[名單同步工具](/tech/identity-and-access/member-provisioning/member-roster-sync.md)
* [串接 MaiGPT：選對 Agent、補齊能力](/tech/work/maigpt-system-integration-guide/maigpt-integration.md) — MaiGPT 產品 vs 自建 Agent、成員身分嵌入的完整參數
* [Web Chat 嵌入與 SDK](/tech/serve/web-chat-sdk.md)／[MaiGPT 模式嵌入](/tech/serve/web-chat-sdk/web-chat-maigpt-mode.md)


---

# 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/work/maigpt-system-integration-guide.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.
