> 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/web-chat-sdk/web-chat-context-data.md).

# 注入頁面 Context

透過 embed SDK 的 auth.contextData，把頁面 context（如商品 ID、工單編號、使用者識別碼）注入 AI 助理的 LLM System Prompt

當 Web Chat 嵌入在您的網站時，AI 助理預設並不知道「使用者目前在哪個頁面、正在看什麼」。`contextData` 讓嵌入方在 embed 設定中傳入任意 key-value 資料，這些資料會**隨每則訊息自動送出，並注入 LLM System Prompt**，讓 AI 助理在對話與工具呼叫（Tool / Function Calling）中直接使用。

常見應用：

* **電商商品頁**：注入 `productId`，助理不必反問「您想問哪個商品？」，直接以該商品 ID 呼叫「查商品」API 工具回答
* **客服系統**：注入 `ticketId`、`customerId`，助理直接引用工單脈絡處理客服流程
* **醫療 / 表單服務**：從 QR code 讀取識別碼（如開立序號）注入，助理在呼叫送出 API 時自動帶入
* **會員 / 金融服務**：注入會員等級等屬性，助理依身分提供個人化回覆

{% hint style="info" %}
`contextData` 掛在 embed 設定的 `auth` 底下，因此必須同時提供 `auth.sourceId`（使用者識別碼）。詳細的 auth 機制請參考 [Web Chat 嵌入與 SDK](/tech/api-integration/web-chat-sdk.md#identify-users)。
{% endhint %}

## 一、快速開始 <a href="#quickstart" id="quickstart"></a>

在嵌入腳本前的 `maiagentChatbotConfig` 中加入 `auth.contextData`：

```html
<script>
  window.maiagentChatbotConfig = {
    webChatId: 'your-web-chat-id',
    baseUrl: 'https://yourdomain.com/web-chats',
    auth: {
      sourceId: 'user-12345',        // 必填：使用者唯一識別碼
      name: '王小明',                 // 選填：顯示名稱
      contextData: {                 // 任意 key-value，注入 LLM system prompt
        productId: '3021',
        productName: '無線降噪耳機',
      },
    },
  }
</script>
<script src="https://yourdomain.com/js/embed.min.js"></script>
```

SDK 載入完成後會自動執行 `auth.setup()`，之後使用者送出的**每一則訊息**都會在 `metadata` 中夾帶這些 key-value，後端會將它們以下列格式附加到 System Prompt：

```
Contact custom attributes:
- productId: 3021
- productName: 無線降噪耳機
```

AI 助理即可在回答與工具呼叫中直接引用這些值。

## 二、運作機制 <a href="#how-it-works" id="how-it-works"></a>

```mermaid
flowchart LR
  A["嵌入頁面 config:<br/>auth.contextData"] --> B["embed SDK<br/>auth.setup()"]
  B --> C["每則訊息的<br/>message.metadata"]
  C --> D["後端合併 metadata<br/>注入 System Prompt"]
  D --> E["LLM 讀到 context"]
  E --> F["對話回覆 /<br/>API 工具呼叫帶入參數"]
```

幾個重要特性：

* **隨訊息送出、不落資料庫**：`contextData` 只存在前端記憶體，隨每則訊息的 payload 送出。使用者重新整理頁面後，需由嵌入頁面重新注入（適合 QR code、session 這類短生命週期資料）
* **每輪對話都生效**：因為隨每則訊息送出，AI 在整段對話中都能持續取得最新的 context
* **無額外 API 呼叫**：沿用既有訊息通道，沒有額外效能負擔

### 與 queryMetadata 的差異 <a href="#context-data-vs-query-metadata" id="context-data-vs-query-metadata"></a>

兩者用途完全不同，請勿混用：

|           | `auth.contextData`                 | `queryMetadata`     |
| --------- | ---------------------------------- | ------------------- |
| 用途        | 把頁面 context 告訴 AI（進 System Prompt） | 控制知識庫檢索範圍（RAG 權限過濾） |
| LLM 是否讀得到 | ✅ 出現在 System Prompt                | ❌ 不進 prompt、不傳給工具   |
| 適用情境      | 商品 ID、工單編號、使用者識別碼                  | 知識管理權限、文件存取範圍       |

如果您想讓 AI「知道」某個值（例如讓它填入 API 工具參數），請使用 `contextData`；如果想限制 AI「查得到哪些知識文件」，請使用 [知識管理權限（Query Metadata）](/tech/authorization-integration/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan.md)。

## 三、資料規則與限制 <a href="#data-rules" id="data-rules"></a>

SDK 會對傳入的 `contextData` 做淨化（sanitize），規則如下：

| 規則       | 行為                                                                         |
| -------- | -------------------------------------------------------------------------- |
| value 型別 | 支援 `string`；`number` / `boolean` 自動轉為字串；其餘型別（object、array、null…）該 key 直接丟棄 |
| key 數量上限 | 最多 **50 組** key-value，超過的部分丟棄                                              |
| 保留 key   | 與系統既有 metadata 衝突的 key 會被丟棄（見下方清單）                                         |
| 空物件 `{}` | 淨化後為空，視同未傳，metadata 不含自訂 key                                               |
| 淨化方式     | 靜默處理，不會報錯、不阻斷送訊                                                            |

**保留 key 清單**（傳入會被丟棄，避免覆蓋系統欄位）：

`contact_name`、`timezone`、`latitude`、`longitude`、`accuracy`、`locale`、`language`、`working_directory`

{% hint style="warning" %}
**安全性由嵌入方負責**：`contextData` 由嵌入頁面注入，MaiAgent 不對其來源做簽章或加密驗證。請勿注入不應讓終端使用者得知的機密資料（值會進入 LLM prompt，AI 可能在回覆中複述）；若資料具識別性（如身分證字號），請由嵌入方確保來源可信（例如經簽章的 QR code / session）並符合個資合規要求。
{% endhint %}

## 四、更新與清除 <a href="#update-and-clear" id="update-and-clear"></a>

`contextData` 的生命週期跟隨 `auth.setup()`：

* **更新**：再次呼叫 `MaiAgent.auth.setup()` 會**整份覆寫**目前的 `contextData`（不是合併）
* **清除**：`auth.setup()` 時不帶 `contextData`，即清空先前注入的值；`MaiAgent.auth.signOut()` 也會一併清空，避免跨身分殘留

```jsx
// SPA 切換頁面時，更新 context 為新商品
MaiAgent.auth.setup({
  sourceId: 'user-12345',
  contextData: {
    productId: '4552',
    productName: '攜帶式藍牙喇叭',
  },
})

// 離開商品頁時，清空 context（不帶 contextData 即清空）
MaiAgent.auth.setup({
  sourceId: 'user-12345',
})
```

## 五、應用範例 <a href="#examples" id="examples"></a>

### 1. 電商商品頁：AI 依當前商品回答 <a href="#example-product-page" id="example-product-page"></a>

情境：AI 助理設定了「查商品」API 工具（以商品 ID 查詢商品詳情）。Web Chat 嵌入在商品詳細頁，希望使用者問「這個適合我嗎？」時，助理不反問、直接針對當前商品回答。

```html
<!-- 商品詳細頁，例如 product_detail.php?id=3021 -->
<script>
  // 從頁面取得當前商品資訊（依您的網站實作方式取得）
  const productId = new URLSearchParams(location.search).get('id')

  window.maiagentChatbotConfig = {
    webChatId: 'your-web-chat-id',
    baseUrl: 'https://yourdomain.com/web-chats',
    auth: {
      sourceId: 'visitor-' + productId,   // 依您的會員 / 訪客識別邏輯
      contextData: {
        productId,                         // AI 呼叫「查商品」工具時填入此 ID
        productName: document.querySelector('.product-title')?.textContent ?? '',
      },
    },
  }
</script>
<script src="https://yourdomain.com/js/embed.min.js"></script>
```

使用者問「這款的續航力可以用多久？」時，System Prompt 已包含 `productId: 3021`，AI 直接以 `id=3021` 呼叫「查商品」工具取得商品詳情後回答，不需反問「您想問哪個商品？」。

{% hint style="info" %}
**建議搭配角色指令引導**：context 是否被工具實際使用，由 LLM 依 prompt 判斷。在 AI 助理的[角色指令](/tech/ai-agents/system-prompt.md)中明確引導可大幅提升穩定度，例如：「當 Contact custom attributes 中有 productId 時，代表使用者正在瀏覽該商品，請優先以此 ID 呼叫查商品工具回答，不要反問使用者。」
{% endhint %}

### 2. 客服系統：帶入工單脈絡 <a href="#example-support-ticket" id="example-support-ticket"></a>

```jsx
window.maiagentChatbotConfig = {
  webChatId: 'your-web-chat-id',
  baseUrl: 'https://yourdomain.com/web-chats',
  auth: {
    sourceId: currentUser.id,
    name: currentUser.displayName,
    contextData: {
      ticketId: 'T-2026-0142',
      customerId: currentUser.id,
      plan: 'enterprise',
    },
  },
}
```

使用者開啟對話後，AI 已知工單編號與客戶方案等級，可直接處理該工單的後續流程，不需客戶重複說明。

### 3. 識別碼注入：QR code / URL 參數 <a href="#example-identifier-injection" id="example-identifier-injection"></a>

情境：服務網頁由 QR code 或帶參數的連結開啟，需要讓 AI 在呼叫送出 API 時自動帶入識別碼。

```jsx
const params = new URLSearchParams(location.search)

window.maiagentChatbotConfig = {
  webChatId: 'your-web-chat-id',
  baseUrl: 'https://yourdomain.com/web-chats',
  auth: {
    sourceId: params.get('sessionId'),
    contextData: {
      formId: params.get('formId'),       // 表單 / 單據識別碼
      userRef: params.get('userRef'),     // 使用者參考編號
    },
  },
}
```

AI 引導使用者完成流程後，呼叫送出工具（如 `SubmitAnswers`）時自動將 `formId`、`userRef` 填入 request body。

## 六、驗證與疑難排解 <a href="#troubleshooting" id="troubleshooting"></a>

**如何確認 contextData 有生效？**

1. 開啟瀏覽器開發者工具的 Network 分頁，觀察 WebSocket 訊息：送出的訊息 payload 中 `metadata` 應包含您注入的 key
2. 直接問 AI 助理：「你知道我的 productId 是什麼嗎？」——若注入成功，AI 能直接回答
3. 在管理後台的對話監控中檢視該則訊息實際使用的 prompt，應包含 `Contact custom attributes` 區塊

**常見問題**

| 問題                   | 原因與處理                                                   |
| -------------------- | ------------------------------------------------------- |
| contextData 完全沒生效    | 確認有提供 `auth.sourceId`（必填，缺少時 `auth.setup()` 不會執行）       |
| 某些 key 消失了           | 檢查是否用到保留 key、value 是否為不支援的型別（object / array）、或超過 50 組上限 |
| 重新整理後 context 不見了    | 預期行為：不落資料庫，需由頁面在每次載入時重新注入                               |
| AI 沒有使用 context 呼叫工具 | 在角色指令中明確引導（見上方範例 1 的 hint）                              |


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.maiagent.ai/tech/api-integration/web-chat-sdk/web-chat-context-data.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
