> 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/build/tools/setup_api_tool.md).

# 建立 API 工具

本指南將引導您在平台中建立新的 API 工具。

{% hint style="info" %}
您可以使用 MaiAgent 製作的 [工具製作 Agent](https://chat.maiagent.ai/web-chats/27934296-105a-4f3f-80f0-7e9dcdb638d3) 協助您建立 API 工具
{% endhint %}

API 工具用於整合外部服務、自動化操作流程。

本頁內容：[什麼是 API？](#what-is-api)｜[快速建立 API 工具](#quick-create-api-tool)｜[在 Query 參數中引用 Agent 的參數](#query-param-templates)｜[金鑰與憑證放哪裡](#credentials)｜[⚠️ 重要提醒](#important-notes)

## **什麼是 API？** <a href="#what-is-api" id="what-is-api"></a>

**API（Application Programming Interface，應用程式介面）** 是不同軟體系統之間溝通的橋樑。簡單來說，它就像是**軟體世界的「服務員」**，幫助不同的程式互相傳遞資訊和執行功能。

想像你在餐廳用餐：

* **你**：需要食物的客戶（應用程式）
* **廚房**：製作食物的地方（提供服務的系統）
* **服務員**：在你和廚房之間傳遞訊息（**API**）

你不需要直接進廚房，只要告訴服務員你要什麼，服務員會把你的需求傳達給廚房，然後把做好的餐點送到你面前。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-affedbd5ccc8692a11a20ce5fc69a39886d0e2d3%2Fplayma%20(10)%20(1).png?alt=media" alt=""><figcaption><p>API 流程示意圖</p></figcaption></figure>

API 工具可以協助您自動操作標準化流程及設置特定的回傳格式，也可以協助您獲取您系統中的資訊如：

**電商客服自動化**

```
客戶詢問訂單 ➡️ API 查詢訂單狀態 ➡️ 自動回覆配送進度
```

**行銷活動管理**

```
新產品上架 ➡️ 自動更新官網 ➡️ 發送 EDM ➡️ 社群平台宣傳
```

**線上課程平台：**

```
學生詢問課程進度 ➡️ API 查詢學習紀錄 ➡️ 自動回覆完成百分比和下次上課時間
```

透過 API 工具，Agent 從單純的對話機器人，進化成能夠實際執行業務流程的智慧助理，大幅提升工作效率和自動化程度。

## 快速建立 API 工具 <a href="#quick-create-api-tool" id="quick-create-api-tool"></a>

### 1. 進入工具管理介面 <a href="#step-1-enter-tool-management" id="step-1-enter-tool-management"></a>

首先，請從左側選單進入 <mark style="color:blue;">AI 功能</mark> → <mark style="color:blue;">工具</mark>。進入工具列表頁面後，點選右上角的 <mark style="color:blue;">新增工具</mark> 按鈕。

### 2. 選擇工具類型 <a href="#step-2-select-tool-type" id="step-2-select-tool-type"></a>

工具類型，選擇 API。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-36d929d6f379aadbfe05520796e63d6f8fefaf4f%2FAPI%E5%B7%A5%E5%85%B7.png?alt=media" alt=""><figcaption></figcaption></figure>

### 3. 設定顯示名稱 <a href="#step-3-set-display-name" id="step-3-set-display-name"></a>

為工具設定清晰的顯示名稱，這邊設為 <mark style="color:blue;">google calendar</mark>。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-1b6a8ebbc7b3900a46b0a20494b1c11c118fbe47%2FAPI%E5%B7%A5%E5%85%B7%20(2).png?alt=media" alt=""><figcaption></figcaption></figure>

* **用途**：此名稱將會顯示在平台介面中，供所有用戶查看。
* **建議**：選擇一個能清晰表達工具主要功能的名稱，方便用戶理解。此名稱沒有嚴格的格式限制。

### 4. 設定工具名稱 <a href="#step-4-set-tool-name" id="step-4-set-tool-name"></a>

接下來是「<mark style="color:blue;">工具名稱</mark>」欄位。

* **用途**：此名稱是 Agent 在內部呼叫和識別此工具時使用的唯一標識符。
* **命名規則 (重要)**：
  * 必須使用英文。
  * 只能包含：
    * 小寫英文字母 (a-z)
    * 大寫英文字母 (A-Z)
    * 數字 (0-9)
    * 底線 (`_`)
    * 連字符 (`-`)
  * **範例**：`get_weather_forecast`, `database-query-tool`

下圖設為 <mark style="color:blue;">google\_calendar\_retriever</mark>

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-e60b90c068677f55f73f007d3f191a41bc3a9e5f%2FAPI%E5%B7%A5%E5%85%B7%20(4).png?alt=media" alt=""><figcaption><p>API 工具名稱定義</p></figcaption></figure>

### 5. 撰寫工具描述 <a href="#step-5-write-tool-description" id="step-5-write-tool-description"></a>

在「<mark style="color:blue;">工具描述</mark>」欄位中，用戶可以提供清晰且詳細的工具說明。

* **重要性**：良好的描述能幫助 Agent 更準確地理解：
  * 工具的功能和目的。
  * 何時應該使用這個工具。
  * 如何解釋工具的輸出結果。
* **建議內容**：說明工具做什麼、輸入什麼、輸出什麼，以及任何使用上的注意事項。
* **兩個說明欄位**：表單裡的 「<mark style="color:blue;">描述</mark>」 顯示在工具列表給成員看；「<mark style="color:blue;">提示詞</mark>」 才是給 Agent 參考的使用方法、參數格式與注意事項。寫好描述後按旁邊的 「<mark style="color:blue;">同步到提示詞</mark>」，會把描述複製到提示詞欄位作為起點（描述空白時提示「請先填寫描述內容」），再補上 Agent 需要的細節。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-61fe2994e26226077604c4865223522621a0c39c%2FAPI%E5%B7%A5%E5%85%B7%20(5).png?alt=media" alt=""><figcaption><p>工具描述</p></figcaption></figure>

### 6. API 配置詳細設定 <a href="#step-6-api-configure-details" id="step-6-api-configure-details"></a>

#### a. 🔗 API URL <a href="#api-url" id="api-url"></a>

* 填寫目標 API 端點的完整網址 (包含 `http://` 或 `https://`)。
* **範例**：`https://api.opencalendar.org/data/2.5`
* **貼 cURL 自動解析**：欄位提示「可貼上從瀏覽器 DevTools 複製的 cURL」。在 DevTools 的 Network 面板對請求選「Copy as cURL」後直接貼進這個欄位，系統會解析出 URL、標頭與 HTTP 方法並自動填入對應欄位（提示「已從 cURL 解析出 URL、標頭與 HTTP 方法」）；開啟新增工具視窗時，若剪貼簿裡已是 cURL 指令也會自動帶入（需瀏覽器允許讀取剪貼簿）。cURL 用到不支援的 HTTP 方法時，URL 與標頭仍會填入，請手動選擇方法；格式無法解析時提示「無法解析 cURL，請檢查格式是否正確」。貼入後請刪掉標頭裡的個人 Cookie 或一次性 token，再依[金鑰與憑證放哪裡](#credentials)改用變數。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-7c8ec1446f411f007db93eecab4a2de07ee8036e%2FAPI%E5%B7%A5%E5%85%B7%20(6).png?alt=media" alt=""><figcaption></figcaption></figure>

#### b. 📮 HTTP 方法 <a href="#http-method" id="http-method"></a>

* 從下拉選單中選擇 API 服務要求的 HTTP 動詞：
  * `GET`：通常用於獲取資源。
  * `POST`：通常用於創建新資源或提交數據。
  * `PUT`：通常用於完整替換或更新資源。
  * `DELETE`：通常用於刪除資源。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-a96418d1f33a03fb89d7c99d75cbff4200fa5851%2FAPI%E5%B7%A5%E5%85%B7%20(8).png?alt=media" alt=""><figcaption></figcaption></figure>

#### c. 📰 標頭 (Headers) <a href="#headers" id="headers"></a>

標頭就像是信件的「<mark style="color:blue;">信封</mark>」，在看到實際的資料內容前，先告訴接收方一些重要的資訊，**沒有正確的標頭，API 請求可能無法通過驗證，或者接收方無法正確解析資料。**。

**常見用途**：

* 身分驗證 (`Authorization`, `X-API-Key`)
* 指定內容類型 (`Content-Type`)
* 指定接受的回應格式 (`Accept`)

若要設定標頭，您需要：

* 在「<mark style="color:blue;">標頭 (JSON)</mark>」欄位填入每次請求都要帶上的 HTTP 標頭。
* **格式**：必須是有效的 JSON 物件，其中鍵 (Key) 是標頭名稱，值 (Value) 是標頭內容 (字串)。不需要額外標頭時維持 `{}`。
* **金鑰請直接填實際的值**：API Key、Token 等憑證請把服務商提供的值原樣填進標頭。平台不會代換自訂名稱的 `{{…}}`，只有特定變數會在呼叫時代入，詳見 [金鑰與憑證放哪裡](#credentials)。
* **範例**：

  ```json
  {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Bearer 這裡貼上服務商提供的 Token",
    "Accept": "application/vnd.github.v3+json"
  }
  ```

{% hint style="info" %}
若要讓 API 以「目前對話的使用者」身分授權，而不是共用一組金鑰：訪客以 Keycloak 登入 Web Chat 時，可在對話平台開啟 [沿用 Keycloak 登入身分呼叫工具](/build/choose-channel/web-chat.md#keycloak-token-passthrough)，並把此 API 的主機加入允許名單，平台會以 `Authorization` 標頭帶上訪客本人的 Keycloak 憑證。此時標頭 (JSON) 不要再設定 `Authorization`，否則會以您設定的內容為準。
{% endhint %}

**敏感 Header 名稱**：工具的執行紀錄會留下每次請求的標頭。平台內建的敏感標頭（`Authorization`、`Proxy-Authorization`、`X-API-Key`、`X-Auth-Token`、`Cookie`、`Set-Cookie`，清單列在唯讀的 <mark style="color:blue;">平台內建敏感 Headers</mark>）與憑證帶入的標頭一律以遮罩顯示；若您的 API 用其他自訂名稱帶金鑰（例如 `X-Client-Secret`），請在 <mark style="color:blue;">敏感 Header 名稱</mark> 輸入名稱後按 Enter 加入，查看執行紀錄時這些標頭的值就會顯示為遮罩。名稱不分大小寫、需完全相符、只能用英文字母、數字與 `- _ . ~`，最多 50 個；設定會同時套用到既有紀錄，移除名稱後恢復顯示原值。

#### d. 🔎 Query 參數 (Query Params) <a href="#query-params" id="query-params"></a>

Query 參數是附加在網址問號後面的查詢字串（例如 `?format=json&limit=10`），每次呼叫都會隨請求送出。適合放固定的查詢條件，或是只能透過 query string 傳遞的 API 金鑰。

* 點擊「<mark style="color:blue;">可用的情境變數</mark>」可展開目前支援的變數清單（聯絡人 ID、對話 ID、收件匣 ID 等）。
* **格式**：有效的 JSON 物件，鍵 (Key) 是參數名稱，值 (Value) 是參數內容（字串）。
* 值可以寫成固定文字，也可以用 `{{參數名}}` 引用「參數結構」中宣告、由 Agent 在呼叫時填入的參數，讓「前半固定、後半由使用者提供」的查詢條件用設定就能完成，詳見下方 [在 Query 參數中引用 Agent 的參數](#query-param-templates)。
* 服務商要求以 query string 傳遞 API 金鑰時，請把金鑰的實際值放在這裡，不要直接寫在 API URL 的 `?` 後面。這裡設定的值不會出現在工具執行紀錄的「<mark style="color:blue;">請求 URL</mark>」，詳見 [誰看得到這些值](#credential-visibility)。
* **範例**：

  ```json
  {
    "$format": "json",
    "$filter": "ProductName eq '{{product_name}}'"
  }
  ```

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-a0552130721b327022bc32313554617846bf0bf7%2Fapi-tool-query-params.png?alt=media" alt="工具設定視窗中的 Query 參數欄位，值裡使用 {{product_name}} 引用參數"><figcaption><p>Query 參數欄位與「可用的情境變數」清單</p></figcaption></figure>

#### e. 🧩 參數結構 (Parameters Schema) <a href="#parameters-schema" id="parameters-schema"></a>

**參數結構就像是「點餐單」**，告訴 Agent 可以向 API 要求什麼資料，以及要怎麼要求。

* **核心設定**：定義 Agent 在呼叫此工具時，可以或必須提供哪些參數(要傳遞給系統處理的內容)，以及這些參數的格式。
* **格式**：使用標準的 **JSON Schema** 格式。
* **關鍵元素**：
  * `type: "object"`：表示參數是一個物件。
  * `properties`: 定義每個參數的物件。
    * **參數名稱** (例如 `"search"`)：對應的物件包含該參數的細節。
      * `type`: 參數的資料類型 (`string`, `integer`, `number`, `boolean`, `array`, `object`)。
      * `description`: 對 Agent 的說明，解釋此參數的意義。
      * `default` (可選): 參數的默認值。
      * `enum` (可選): 如果參數值只能是特定幾個選項之一，在此列出。
  * `required`: 一個包含所有**必填**參數名稱的陣列。
* **不要放金鑰**：參數結構（包含 `default` 預設值）會作為工具定義提供給 AI 模型。API 金鑰請放在「標頭 (JSON)」或「Query 參數 (JSON)」。
* **不要貼範例資料**：參數要寫在 `properties` 裡。直接貼上 `{"keyword": "string", "limit": 10}` 這類範例資料時，按 「<mark style="color:blue;">確認</mark>」 會跳出 「<mark style="color:blue;">錯誤提示</mark>」，說明此 JSON Schema 未定義任何欄位，並列出需移入 `properties` 的鍵；依提示改寫後再儲存。工具不需要任何參數時，維持預設的 `{}` 即可儲存。
* **範例** (影音搜尋工具)：

  ```json
  {
      "type": "object",
      "properties": {
          "limit": {
              "type": "integer",
              "minimum": 1,
              "description": "回傳結果數量上限"
          },
          "fields": {
              "type": "string",
              "description": "以逗號分隔的欄位清單"
          },
          "search": {
              "type": "string",
              "description": "搜尋關鍵字"
          }
      },
      "required": ["search"]
  }
  ```

#### f. 路徑參數與參數位置 <a href="#path-parameters" id="path-parameters"></a>

API URL 可以用 `{參數名}` 標出網址路徑中會變動的段落，例如 `/users/{userId}/orders/{orderId}`。要讓系統把 Agent 提供的值代入網址，必須在「參數結構」定義同名參數，並把該參數的位置設為「<mark style="color:blue;">路徑</mark>」。送出請求前，系統會先將值做網址編碼再代入，例如 `A/B 01` 會變成 `A%2FB%2001`，不會因為值裡的斜線或空白而改變網址結構。

**使用情境**：客服主管小麥希望 Agent 依照客戶編號與訂單編號，向公司的訂單 API 查詢單筆訂單。她建立 API 工具、把兩個編號設為路徑參數，再將工具配置給 Agent。同事在對話中輸入「查詢客戶 customer-01 的訂單 order-25」，Agent 就把兩個編號放進網址的正確位置送出查詢；若少了訂單編號，工具會直接回報缺值，不會送出不完整的請求。

{% stepper %}
{% step %}

### 設定含路徑參數的 API URL <a href="#path-param-step-url" id="path-param-step-url"></a>

依照上方「快速建立 API 工具」新增工具。練習時可使用公開的 httpbin 回應服務，將 <mark style="color:blue;">API URL</mark> 設為：

```
https://httpbin.org/anything/users/{userId}/orders/{orderId}
```

同一個網址可以放入多個路徑參數。輸入後，欄位下方會出現「<mark style="color:blue;">偵測到的路徑參數</mark>」並列出 `userId, orderId`；參數結構還沒定義這些名稱時，會再以紅字提示「<mark style="color:blue;">請在參數結構中定義</mark>」。
{% endstep %}

{% step %}

### 在參數結構宣告同名參數 <a href="#path-param-step-schema" id="path-param-step-schema"></a>

在 <mark style="color:blue;">參數結構 (JSON Schema)</mark> 填入：

```json
{
  "type": "object",
  "properties": {
    "userId": { "type": "string", "description": "客戶編號" },
    "orderId": { "type": "string", "description": "訂單編號" }
  },
  "required": ["userId", "orderId"]
}
```

參數名稱必須與網址大括號內的名稱完全相同（大小寫也要一致）；`required` 讓 Agent 知道每次呼叫都要同時提供這兩個值。

填入後，參數結構下方會列出每個參數與一個位置選單，預設為「<mark style="color:blue;">預設</mark>」。此時 API URL 下方會出現紅字「<mark style="color:blue;">以下參數位置不是「路徑」，網址中的佔位符將不會被代入</mark>」，代表還需要完成下一步。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-fd22abf6d8d512da1b562b409257a40d152e10df%2Fapi-tool-path-params-url-hint.png?alt=media" alt="新增工具視窗中，API URL 填入含 userId 與 orderId 的網址，下方顯示偵測到的路徑參數，以及參數位置不是路徑的紅字提示"><figcaption><p>參數位置仍是「預設」時，API URL 下方會出現紅字提示</p></figcaption></figure>
{% endstep %}

{% step %}

### 將參數位置設為「路徑」 <a href="#path-param-step-location" id="path-param-step-location"></a>

在參數結構下方，把 `userId` 與 `orderId` 的位置選單都改為「<mark style="color:blue;">路徑</mark>」。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-ab2269bc4657f0d2d3ef15768c7817fe6f923eb8%2Fapi-tool-path-params-location-menu.png?alt=media" alt="參數結構下方的位置選單展開，選項為預設、路徑、查詢、本文、標頭"><figcaption><p>每個參數都可以從選單選擇位置</p></figcaption></figure>

選好後，系統會自動在參數結構中加入 `"location": "path"`，API URL 下方的紅字提示也會消失。確認無誤後點擊「<mark style="color:blue;">確認</mark>」儲存工具。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-a86225dedbfcf98430095438e3dee00c09eddcc4%2Fapi-tool-path-params-location-set.png?alt=media" alt="參數結構中 userId 與 orderId 都加入 location 為 path，下方兩個位置選單都顯示路徑"><figcaption><p>選擇「路徑」後，參數結構會同步寫入 location 設定</p></figcaption></figure>

{% hint style="warning" %}
位置維持「<mark style="color:blue;">預設</mark>」的參數不會代入網址。即使 Agent 有提供值，網址中的 `{userId}` 仍然缺值，工具會回報錯誤且不送出請求。請務必把網址中用到的每個參數都設為「<mark style="color:blue;">路徑</mark>」。
{% endhint %}
{% endstep %}

{% step %}

### 配置給 Agent 並驗收 <a href="#path-param-step-test" id="path-param-step-test"></a>

依照 [為 Agent 配置工具](/build/tools/configure_tools.md) 把工具加入回答模式為 Agent 模式的 Agent。接著從左側導航列進入「<mark style="color:blue;">Agent 市集</mark>」，切換到「<mark style="color:blue;">組織自建</mark>」，點選該 Agent 並輸入「查詢客戶 customer-01 的訂單 order-25」。Agent 呼叫工具後，httpbin 會回傳實際收到的請求網址 `https://httpbin.org/anything/users/customer-01/orders/order-25`。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-8fbf496275f08bf616b56673143a7aede4f364d3%2Fapi-tool-path-params-chat.png?alt=media" alt="Agent 回覆客戶編號、訂單編號，以及代入兩個編號後的請求網址"><figcaption><p>Agent 把兩個編號代入網址後送出查詢</p></figcaption></figure>

若要查看每次呼叫實際送出的網址，從左側導航列進入「<mark style="color:blue;">AgentOps</mark>」→「<mark style="color:blue;">工具執行紀錄</mark>」，點選該筆紀錄操作欄的眼睛圖示開啟「<mark style="color:blue;">詳細</mark>」，在「<mark style="color:blue;">請求資訊</mark>」查看「<mark style="color:blue;">請求 URL</mark>」。下圖是客戶編號含斜線與空白（`A/B 01`）的呼叫，可以看到值已經過網址編碼。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-42bb5fd57f4e3d8aa020f8499b1f77ef9dc246bd%2Fapi-tool-path-params-record.png?alt=media" alt="工具執行紀錄詳細視窗，輸入參數為 A/B 01 與 order#25，請求 URL 中對應段落為 A%2FB%2001 與 order%2325"><figcaption><p>工具執行紀錄中的請求 URL 顯示編碼後的路徑參數</p></figcaption></figure>

練習完成後，把公開示範網址換成公司的訂單 API 網址即可。
{% endstep %}
{% endstepper %}

**參數位置選項**

參數結構中的每個參數都可以設定位置，決定呼叫時把值放在請求的哪裡：

| 位置                                  | 說明                                                               |
| ----------------------------------- | ---------------------------------------------------------------- |
| <mark style="color:blue;">預設</mark> | 維持原本行為：GET 放在查詢字串，POST、PUT、PATCH 放在本文。DELETE 不會自動帶入，需要傳值時請明確選擇位置 |
| <mark style="color:blue;">路徑</mark> | 代入 API URL 中同名的 `{參數名}`                                          |
| <mark style="color:blue;">查詢</mark> | 附加在網址問號後的查詢字串                                                    |
| <mark style="color:blue;">本文</mark> | 放在 JSON 本文中                                                      |
| <mark style="color:blue;">標頭</mark> | 以參數名稱作為 HTTP 標頭送出；若「標頭 (JSON)」已設定同名標頭（不分大小寫），以已設定的內容為準           |

未設定位置的既有工具行為不變。

**缺少路徑參數值時不會送出請求**

某次呼叫中，只要網址裡有任何一個路徑參數沒有值（Agent 沒有提供、值為空，或該參數位置不是「路徑」），工具會直接停止並回報「路徑參數 {orderId} 在本次呼叫中沒有值」，不會把含有 `{orderId}` 的網址送出。Agent 會在對話中說明查詢失敗的原因；在「<mark style="color:blue;">工具執行紀錄</mark>」中，該筆紀錄的狀態為失敗，「<mark style="color:blue;">請求資訊</mark>」沒有請求內容，「<mark style="color:blue;">錯誤訊息</mark>」會指出缺值的參數。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-750f62d0eddb446a5a310c0f0df7ad282742b8c3%2Fapi-tool-path-params-missing.png?alt=media" alt="工具執行紀錄詳細視窗，輸入參數的 orderId 為 null，請求資訊沒有內容，錯誤訊息指出路徑參數 orderId 在本次呼叫中沒有值"><figcaption><p>缺少路徑參數值時，工具不會送出請求並記錄錯誤原因</p></figcaption></figure>

**網址寫法限制**

* 路徑參數名稱只能使用英文字母、數字與底線，且不能以數字開頭，例如 `{order_id}`；`{order-id}` 這類名稱無法儲存。
* `{參數名}` 請放在網址的路徑段落。需要放在查詢字串的值，請把參數位置設為「<mark style="color:blue;">查詢</mark>」，或在 [Query 參數](#query-param-templates) 中用 `{{參數名}}` 引用。
* API URL 不能使用 `{{變數}}` 雙大括號語法，儲存時會出現「<mark style="color:blue;">錯誤提示</mark>」：「路徑參數必須使用 {identifier} 語法。」在 API 工具中，`{{參數名}}` 請用在「標頭 (JSON)」與「Query 參數 (JSON)」。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-2504b5ecf2e51c2e9bb2ac09e44dcde725120152%2Fapi-tool-path-params-invalid-syntax.png?alt=media" alt="畫面上方顯示 Request failed with status code 400，中央的錯誤提示對話框內容為路徑參數必須使用 {identifier} 語法"><figcaption><p>API URL 含雙大括號時無法儲存</p></figcaption></figure>

Google Style REST 的自訂動作可以直接保留冒號後綴，例如 Google Weather 查詢：

```
https://weather.googleapis.com/v1/currentConditions:lookup
```

### 7. 💾 儲存工具 <a href="#step-7-save-tool" id="step-7-save-tool"></a>

確認所有設定無誤後，捲動到頁面底部，點擊「<mark style="color:blue;">確認</mark>」按鈕。您的新工具就建立完成了！

新增工具時，如果還沒打開過 <mark style="color:blue;">權限設定</mark> 分頁就按 <mark style="color:blue;">確認</mark>，這次不會建立工具：畫面會自動切到 <mark style="color:blue;">權限設定</mark>，並提示「請先查看權限設定，確認分配的角色後再提交」。在 <mark style="color:blue;">快速選擇權限範圍</mark> 確認哪些角色的成員可以使用這個工具（預設為 <mark style="color:blue;">排除預設角色</mark>），再按一次 <mark style="color:blue;">確認</mark> 即可建立。編輯既有工具時不會出現這道確認。

## 在 Query 參數中引用 Agent 的參數 <a href="#query-param-templates" id="query-param-templates"></a>

許多第三方 API 的查詢條件是「固定語法＋使用者提供的值」組成的一整個字串，例如 OData 風格的 `$filter=ProductName eq 'Chai'`，或搜尋類 API 的 `q=` 參數。這類 API 要的不是一個獨立的參數，而是把值嵌進固定的字串裡。

在「Query 參數」的值裡寫 `{{參數名}}`，MaiAgent 會在 Agent 呼叫工具時，把「參數結構」中同名參數的值代入後再送出請求。設定者負責寫好固定的骨架，Agent 只負責填值，語法正確性不再交給模型判斷。

### 使用情境 <a href="#query-param-templates-use-case" id="query-param-templates-use-case"></a>

採購部門想讓公司內部的 Agent 直接回答「某個產品目前的單價和庫存是多少」，資料來源是公司商品目錄系統提供的 OData 查詢服務。過去這類查詢必須為每一支 API 另外寫程式；現在採購專員只要建立一個 API 工具，把查詢條件寫成 `ProductName eq '{{product_name}}'`，再把工具配置給 Agent。同事在對話中問「Chai 這個產品的單價和庫存是多少？」，Agent 會自動把 `Chai` 填進查詢條件、呼叫 API，並回覆產品名稱、單價與庫存。

### 設定步驟 <a href="#query-param-templates-steps" id="query-param-templates-steps"></a>

以下用公開的 Northwind 示範資料服務（OData）示範，可直接照做：

{% stepper %}
{% step %}

### 建立工具並填入基本資料 <a href="#query-param-step-basic" id="query-param-step-basic"></a>

依照上方「快速建立 API 工具」的步驟新增一個 API 工具，填入顯示名稱（例如 <mark style="color:blue;">產品價格查詢</mark>）、工具名稱 `product_price_lookup`、描述與提示詞，並將 <mark style="color:blue;">API URL</mark> 設為：

```
https://services.odata.org/V4/Northwind/Northwind.svc/Products
```

<mark style="color:blue;">HTTP 方法</mark> 維持 `GET`。
{% endstep %}

{% step %}

### 在參數結構宣告要由 Agent 填入的參數 <a href="#query-param-step-schema" id="query-param-step-schema"></a>

在 <mark style="color:blue;">參數結構 (JSON Schema)</mark> 宣告 `product_name`，並用 `description` 告訴 Agent 該填什麼：

```json
{
  "type": "object",
  "properties": {
    "product_name": {
      "type": "string",
      "description": "完整的英文產品名稱，例如 Chai"
    }
  },
  "required": ["product_name"]
}
```

{% endstep %}

{% step %}

### 在 Query 參數的值裡引用該參數 <a href="#query-param-step-template" id="query-param-step-template"></a>

在 <mark style="color:blue;">Query 參數 (JSON)</mark> 填入固定的查詢骨架，並在值裡用 `{{product_name}}` 引用剛才宣告的參數：

```json
{
  "$format": "json",
  "$select": "ProductID,ProductName,UnitPrice,UnitsInStock",
  "$filter": "ProductName eq '{{product_name}}'"
}
```

點擊「<mark style="color:blue;">確認</mark>」儲存工具。
{% endstep %}

{% step %}

### 配置給 Agent 並測試 <a href="#query-param-step-test" id="query-param-step-test"></a>

依照 [為 Agent 配置工具](/build/tools/configure_tools.md) 把這個工具加入一個回答模式為 Agent 模式的 Agent 並儲存。接著從左側導航列進入「<mark style="color:blue;">Agent 市集</mark>」，切換到「<mark style="color:blue;">組織自建</mark>」，點選該 Agent 開始對話，輸入「請問 Chai 這個產品的單價和庫存是多少？」。Agent 會顯示「已使用工具」，並回覆 Chai 的單價與庫存。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-d301cae503ac598952cb9c0c4ef494c0b8bae727%2Fapi-tool-query-params-chat.png?alt=media" alt="Agent 在對話中使用工具，回覆產品名稱、單價與庫存"><figcaption><p>Agent 把使用者提供的產品名稱代入查詢條件後呼叫 API</p></figcaption></figure>
{% endstep %}
{% endstepper %}

### 代入規則 <a href="#query-param-templates-rules" id="query-param-templates-rules"></a>

| 規則                | 說明                                                                             |
| ----------------- | ------------------------------------------------------------------------------ |
| **變數名稱必須與參數結構一致** | `{{product_name}}` 對應「參數結構」中 `properties` 的參數名稱，大小寫需完全相符                       |
| **只有值會代入**        | 模板只作用在 Query 參數的值；鍵 (Key) 維持原樣，不做代入                                            |
| **值以原文代入**        | 參數值一律以字面文字代入，不做數值轉換；例如統一編號 `04595257` 的前導零會保留                                  |
| **缺值即中止**         | Agent 這次呼叫沒有提供該參數（或值為空）時，工具會以錯誤中止並指出是哪個參數缺值，不會把 `{{product_name}}` 原樣送出去       |
| **情境變數優先**        | 若參數名稱與情境變數（如 `contact_id`、`conversation_id`）相同，一律代入情境變數的值，Agent 提供的值不會覆蓋       |
| **被引用的參數仍會一併送出**  | 被模板引用的參數仍會照原本的行為當成獨立的 query 參數一起送出（例如同時送出 `product_name=Chai`），多數 API 會忽略多餘的參數 |
| **參數名稱原樣保存**      | Query 參數的鍵含底線或大寫（例如 `Business_Accounting_NO`）會原樣保存，不會被系統改寫                     |

{% hint style="info" %}
「<mark style="color:blue;">標頭 (JSON)</mark>」的值同樣支援 `{{參數名}}` 引用參數結構中的參數，規則與 Query 參數相同。
{% endhint %}

{% hint style="warning" %}
不含 `{{ }}` 的既有工具設定完全不受影響。若舊工具的 Query 參數名稱曾被系統改寫（例如 `Business_Accounting_NO` 變成 `business__accounting_no`），重新開啟該工具、把名稱改回正確寫法並儲存即可。重新開啟編輯視窗時，Query 參數的值會以 `****` 遮罩顯示，直接儲存不會遺失原值。
{% endhint %}

## 金鑰與憑證放哪裡 <a href="#credentials" id="credentials"></a>

API 工具沒有獨立的密鑰保管欄位，也沒有可自訂名稱的密鑰變數。呼叫外部 API 需要的金鑰，請依「Agent 要用誰的身分呼叫」放在下列位置：

| 情境                             | 放在哪裡                                                                                                                                |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| 全組織共用一組固定的 API Key 或 Token     | 直接把實際的值填在工具的「<mark style="color:blue;">標頭 (JSON)</mark>」；服務商只接受 query string 時，填在「<mark style="color:blue;">Query 參數 (JSON)</mark>」 |
| 每位聯絡人使用自己的 API Key 或 Token     | 聯絡人的「<mark style="color:blue;">API 憑證</mark>」分頁，見 [每位聯絡人使用各自的金鑰](#per-contact-api-credentials)                                      |
| 以 Keycloak 登入 Web Chat 的訪客本人身分 | 對話平台的 [沿用 Keycloak 登入身分呼叫工具](/build/choose-channel/web-chat.md#keycloak-token-passthrough)                                          |
| 服務只接受 OAuth 登入授權               | API 工具沒有 OAuth 授權流程。若服務提供 MCP 伺服器，請改用 [MCP 工具的 OAuth 連接器](/build/tools/mcp-setup.md#oauth-connector)                                |

{% hint style="warning" %}
在「<mark style="color:blue;">API URL</mark>」貼上從瀏覽器複製的 cURL 指令時，指令中的標頭會一併帶入「標頭 (JSON)」，其中常含有您本人的 `Cookie` 或 `Authorization`。這些值會成為所有對話共用的固定憑證，儲存前請刪除，或換成服務商發給這個工具使用的金鑰。
{% endhint %}

### 會被代換的 `{{…}}` 變數 <a href="#template-variables" id="template-variables"></a>

「標頭 (JSON)」與「Query 參數 (JSON)」的值可以使用 `{{變數名稱}}`，系統會在每次呼叫時代換。只有下列名稱會被代換：

| 變數                                   | 代入的值                                                                    |
| ------------------------------------ | ----------------------------------------------------------------------- |
| `{{contact_id}}`                     | 聯絡人 ID                                                                  |
| `{{source_id}}`                      | 來源 ID                                                                   |
| `{{contact_name}}`                   | 聯絡人名稱                                                                   |
| `{{conversation_id}}`                | 對話 ID                                                                   |
| `{{inbox_id}}`                       | 收件匣 ID                                                                  |
| `{{organization_id}}`                | 組織 ID                                                                   |
| `{{agent_slug}}`、`{{agent_version}}` | 供官方內建 Agent 使用；組織自建的 Agent 呼叫時一律代入空字串                                   |
| `{{參數名}}`                            | 「參數結構」中宣告的參數，代入 Agent 這次呼叫提供的值，規則見 [代入規則](#query-param-templates-rules) |

* 變數名稱大小寫必須完全相同，大括號內不能有空白；`{{ contact_id }}` 不會被代換，會原樣送出。
* 對話情境變數沒有對應值時代入空字串，例如對話沒有聯絡人時的 `{{contact_id}}`。
* 其他名稱（例如自己取名的金鑰變數）不會被代換。儲存工具時會出現「<mark style="color:blue;">包含未知的範本變數</mark>」錯誤；若舊工具仍留有這類寫法，請求會把 `{{…}}` 原樣送給對方，導致驗證失敗。請改填實際的金鑰後重新儲存。
* 「API URL」與「參數結構」不能使用 `{{…}}`。

### 每位聯絡人使用各自的金鑰 <a href="#per-contact-api-credentials" id="per-contact-api-credentials"></a>

當每位聯絡人要用自己的帳號呼叫 API（例如查詢自己的訂單），請在工具的「標頭 (JSON)」只放共用的標頭，再為每位聯絡人設定各自的憑證：

1. 進入「<mark style="color:blue;">聯絡人</mark>」頁面，編輯該聯絡人（聯絡人需已建立並儲存）。
2. 切換到「<mark style="color:blue;">API 憑證</mark>」分頁，點擊工具右側的編輯按鈕。
3. 在「<mark style="color:blue;">Headers（JSON 格式）</mark>」填入這位聯絡人的標頭，例如 `{"Authorization": "Bearer 這位聯絡人的 Token"}`，點擊「<mark style="color:blue;">儲存</mark>」。

操作方式與 [聯絡人 MCP 憑證設定](/build/tools/setup-contacts-mcp-credentials.md) 相同。呼叫時系統會先帶入工具的「標頭 (JSON)」，再以聯絡人設定的標頭覆蓋同名標頭（名稱大小寫需與工具設定一致）；聯絡人沒有設定時，使用工具的標頭。聯絡人憑證的值會原樣送出，不做 `{{…}}` 代換。

### 誰看得到這些值 <a href="#credential-visibility" id="credential-visibility"></a>

* **工具編輯視窗**：儲存後，「標頭 (JSON)」與「Query 參數 (JSON)」的值不會再以明文顯示，包含建立者本人。重新開啟編輯視窗時，每個值只顯示前後各 4 個字元，中間以 `****` 取代（8 個字元以內的值整個顯示為 `****`）。直接儲存不會改變原值；要修改某一項時，請重新輸入該項的完整值，仍含遮罩值的項目無法儲存。
* **AI 模型**：標頭與 Query 參數的值不會提供給 AI 模型。AI 模型只看得到工具名稱、提示詞（或描述）與參數結構。
* **工具執行紀錄**：在「<mark style="color:blue;">AgentOps</mark>」→「<mark style="color:blue;">工具執行紀錄</mark>」的「<mark style="color:blue;">請求資訊</mark>」可以看到每次實際送出的「<mark style="color:blue;">請求 URL</mark>」與「<mark style="color:blue;">請求 Headers</mark>」：
  * 名稱為 `Authorization`、`Proxy-Authorization`、`Cookie`、`Set-Cookie`、`X-API-Key`、`Api-Key`、`X-Auth-Token`、`X-Access-Token`（不分大小寫）的標頭，以及聯絡人「API 憑證」中設定的標頭，會顯示為 `***` 並標示「<mark style="color:blue;">已遮罩</mark>」。
  * 其他名稱的標頭會以明文顯示。服務商允許時，請把金鑰放在上列名稱的標頭。
  * 「Query 參數 (JSON)」設定的值不會出現在「請求 URL」；API 回應或錯誤訊息若回顯了這些值，也會被替換成 `***`。
  * 直接寫在「API URL」中的內容（包含 `?` 後面的查詢字串）會原樣顯示在「請求 URL」，因此金鑰不要寫在 API URL。

{% hint style="info" %}
練習用的 httpbin 會把收到的請求標頭原樣放在回應中，回應內容會進入對話與工具執行紀錄。測試時請不要帶入真實的金鑰。
{% endhint %}

## ⚠️ 重要提醒 <a href="#important-notes" id="important-notes"></a>

**連線測試**

* 建立工具後，建議先測試 API 是否正常運作
* 可使用測試工具驗證工具功能，如：
  * POSTMAN
  * 企業自己搭建的 API 測試請求平台

**權限管理**

* 定期檢查工具使用狀況及權限開放狀態


---

# 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/build/tools/setup_api_tool.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.
