> 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/advanced-genai-tech/function-calling.md).

# Function Calling

Function Calling（工具呼叫）的概念，以及 MaiAgent 的 Agent 怎麼取得工具定義、平台怎麼執行工具並把結果交回模型，還有迭代次數、逾時與結果長度等限制。

## 什麼是 Function Calling？

Function Calling（函式呼叫，也稱工具呼叫）是指大型語言模型（LLM）在處理請求時，判斷需要使用外部程式或 API（以下統稱「工具」），並以結構化格式（通常是 JSON）輸出要呼叫的工具名稱與參數。

LLM 本身不執行工具，只負責「決定」呼叫哪個工具、帶什麼參數。實際執行由呼叫端程式完成，再把執行結果交回 LLM，由 LLM 根據結果回答，或決定接著呼叫下一個工具。

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2Fgit-blob-174638479c334f8fa77665a8f7c7d488a7e620d3%2Ffc2.png?alt=media" alt="LLM 依需求選擇搜尋、天氣 API、翻譯 API 等工具"><figcaption><p>LLM 依使用者需求選擇要呼叫的工具（示意）</p></figcaption></figure>

## Function Calling 的運作原理

一般而言，Function Calling 是一個循環：

1. **提供工具定義**：呼叫端把每個工具的名稱、用途說明與參數結構（JSON Schema）連同對話一起送給 LLM。
2. **模型決定呼叫**：LLM 判斷需要工具時，輸出工具名稱與 JSON 參數，而不是直接回答。
3. **執行工具**：呼叫端依名稱與參數執行對應的程式，例如查詢資料庫或呼叫第三方 API。
4. **交回結果**：呼叫端把執行結果加進對話，再交給 LLM。
5. **回答或繼續**：LLM 依結果產生回答，或判斷還需要其他資料而再次呼叫工具。

模型是否呼叫工具、填入什麼參數，主要取決於工具的用途說明與參數說明寫得是否清楚。

### 常見用途 <a href="#common-uses" id="common-uses"></a>

| 用途           | 例子                                                                                            |
| ------------ | --------------------------------------------------------------------------------------------- |
| 取得即時或內部資料    | 查訂單狀態、庫存、匯率、公司內部系統的紀錄                                                                         |
| 執行操作         | 建立工單、預約、寄送通知                                                                                  |
| 多步驟任務        | 先查客戶資料，再依結果查詢合約，最後彙整回覆                                                                        |
| 把自然語言轉成結構化查詢 | Text to SQL，見 [Text to SQL](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql.md) |

***

## 在 MaiAgent 怎麼運作 <a href="#how-it-works-in-maiagent" id="how-it-works-in-maiagent"></a>

### 啟用條件 <a href="#prerequisites" id="prerequisites"></a>

* Agent 的 <mark style="color:blue;">回答模式</mark> 必須是 <mark style="color:blue;">Agent 模式</mark>。<mark style="color:blue;">RAG 問答</mark> 等其他回答模式不會呼叫工具。
* 後台只對支援工具呼叫的模型提供 Agent 模式；組織方案也可能限制可用的回答模式。

### 模型可以呼叫哪些工具 <a href="#tool-sources" id="tool-sources"></a>

| 來源     | 說明                                                  | 規格                                                                                                                                                   |
| ------ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| API 工具 | 一個工具對應一個 HTTP 端點與方法，由平台代為送出請求                       | [API 工具工程指南](https://docs.maiagent.ai/tech/api-integration/api-tool-engineering-guide.md)                                                            |
| MCP 工具 | 一個工具對應一個 MCP 伺服器，伺服器上「允許的工具」都會成為模型可呼叫的工具            | [自架 MCP Server 接入規格](https://docs.maiagent.ai/tech/mcp/self-hosted-mcp-server.md)、[Remote MCP 服務概述](https://docs.maiagent.ai/tech/mcp/remote-mcp.md) |
| 平台內建工具 | 例如知識庫檢索、Code Interpreter、Browser Tool，依 Agent 的設定開啟 | 見使用手冊                                                                                                                                                |
| 技能     | 綁定技能後，模型透過 `skill_expand_tool` 展開技能的指令與附加工具         | [Skill 技能模組](https://docs.maiagent.ai/tech/advanced-genai-tech/skill.md)                                                                             |

Agent 只能呼叫綁定給它的工具；後台建立工具時可選的類型為 API 工具與 MCP 工具。

### 工具定義怎麼交給模型 <a href="#tool-definition" id="tool-definition"></a>

* **名稱**：工具名稱會正規化成英數與底線、最長 64 字元，規則見 [API 工具工程指南：工具定義對照](https://docs.maiagent.ai/tech/api-integration/api-tool-engineering-guide.md#tool-definition)。
* **用途說明**：API 工具的「<mark style="color:blue;">提示詞</mark>」有值時用它，否則用「<mark style="color:blue;">描述</mark>」；MCP 工具用伺服器 `tools/list` 回傳的 `description`。
* **參數結構**：API 工具用「<mark style="color:blue;">參數結構 (JSON Schema)</mark>」，MCP 工具用伺服器回傳的 `inputSchema`。
* **工具搜尋**：Agent 開啟「<mark style="color:blue;">啟用工具搜尋功能</mark>」（預設開啟）時，大部分工具的完整定義不會一開始就交給模型。模型先從 `tool_searching_tool` 的說明看到可用工具名稱，要呼叫時再以名稱搜尋、載入定義。綁定的工具很多時，這能減少每次送給模型的工具定義。

### 執行與回傳 <a href="#execution" id="execution"></a>

```mermaid
sequenceDiagram
    participant U as 使用者
    participant A as Agent（LLM）
    participant P as MaiAgent 平台
    participant T as 工具（API／MCP 伺服器／內建功能）

    U->>A: 提問
    A->>P: 工具呼叫（名稱＋JSON 參數）
    P->>P: 依參數結構檢查參數、檢查 Credits
    P->>T: 執行工具
    T-->>P: 結果
    P->>P: 截斷過長結果、寫入工具執行紀錄
    P-->>A: 工具結果
    A-->>U: 回答（或再次呼叫工具）
```

* **參數檢查**：模型給的參數會依參數結構檢查。參數不符或工具執行時發生錯誤，錯誤內容會當作工具結果交回模型，由模型修正參數重試或向使用者說明，不會中斷整個回覆。
* **多個工具**：模型在同一步驟要求多個工具時，平台會同時執行。
* **結果長度**：工具結果超過模型 context window 的一定比例（平台預設 0.8）時，保留開頭與結尾、省略中間。Agent 另可開啟「<mark style="color:blue;">工具結果截斷</mark>」，以字元數上限（預設 8000）截斷過大的結果。
* **重複呼叫**：同一輪回覆中，以完全相同的參數再次呼叫同一個工具、且結果也相同時，平台不會再次交回相同結果，改回一段提示，告知模型重試不會得到不同資料。
* **執行紀錄**：每次呼叫都會寫入工具執行紀錄，包含輸入參數、輸出或錯誤、狀態與耗時。
* **Credits**：API 工具、MCP 工具與部分內建工具每次呼叫會扣 Credits；額度不足時，這次呼叫不會送出，模型會收到額度不足的說明。

### 執行上限 <a href="#limits" id="limits"></a>

| 設定                                         | 範圍與預設                         | 達到時                 |
| ------------------------------------------ | ----------------------------- | ------------------- |
| <mark style="color:blue;">最大迭代次數</mark>    | 1–100，預設 20。計算工具呼叫的輪數，工具搜尋不計入 | Agent 停止呼叫工具，產生總結回應 |
| <mark style="color:blue;">執行逾時時間（秒）</mark> | 30–1200，預設 600                | 工作流終止，顯示逾時訊息（可自訂）   |

兩者以先到者為準。提高迭代次數時要一併提高逾時時間，否則容易先逾時。

***

## 限制與注意事項 <a href="#limitations" id="limitations"></a>

* **模型可能不呼叫或呼叫錯工具**：平台不保證模型一定在對的時機呼叫對的工具。模型沒有呼叫工具時不會產生工具執行紀錄；這時要調整的是工具說明與參數說明，而不是工具本身。
* **工具說明決定品質**：每個參數都寫說明與格式範例，並在工具說明寫清楚用途、使用時機與回傳內容。
* **寫入型操作要能承受重送**：API 工具遇到逾時與部分錯誤時會自動重試，模型也可能重複呼叫。下單、建立工單等寫入操作請在工具端做冪等處理，細節見 [API 工具工程指南：逾時、重試與 TLS](https://docs.maiagent.ai/tech/api-integration/api-tool-engineering-guide.md#timeout-retry-tls)。
* **不要把金鑰放進參數結構**：模型看得到參數結構與參數值。金鑰放在工具的標頭或 Query 參數，或使用聯絡人憑證。
* **一般而言，不同模型的工具呼叫能力不同**：同一組工具換模型後，呼叫時機與參數品質可能改變，換模型後請重新測試。

***

## 操作請看使用手冊 <a href="#user-guide-links" id="user-guide-links"></a>

* [工具功能概覽](https://docs.maiagent.ai/build/tools/tool_description)
* [建立 API 工具](https://docs.maiagent.ai/build/tools/setup_api_tool)
* [建立 MCP 工具](https://docs.maiagent.ai/build/tools/mcp-setup)
* [為 Agent 配置工具](https://docs.maiagent.ai/build/tools/configure_tools)
* [回覆長度與 Agent 執行上限](https://docs.maiagent.ai/build/agent/custom-max-tokens)
* [工具執行紀錄](https://docs.maiagent.ai/build/agent-ops/tool-execution-records)


---

# 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/advanced-genai-tech/function-calling.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.
