函式呼叫(Function Calling)

函式呼叫允許模型根據使用者需求,自動選擇並呼叫你預定義的工具函式,實作資料查詢、API 呼叫、任務執行等能力。

基本概念#

函式呼叫的完整流程:

  • 定義工具 — 在請求中描述可用函式和引數
  • 模型決策 — 模型判斷是否需要呼叫工具
  • 回傳呼叫 — 模型回傳函式名和引數
  • 執行函式 — 你執行函式並取得結果
  • 繼續對話 — 將結果發回模型,生成最終回覆

OpenAI 協議#

Python

程式碼
from openai import OpenAI
import json
 
client = OpenAI(
    base_url="https://as.apinoma.com/v1",
    api_key="<你的 APINOMA_API_KEY>"
)
 
# 1. 定義工具
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "獲取指定城市的即時天氣資訊",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名稱,如:北京、上海"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "溫度單位"
                }
            },
            "required": ["city"]
        }
    }
}]
 
# 2. 傳送請求
messages = [{"role": "user", "content": "北京今天天氣怎麼樣?"}]
 
response = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)
 
message = response.choices[0].message
 
# 3. 處理工具呼叫
if message.tool_calls:
    for tool_call in message.tool_calls:
        args = json.loads(tool_call.function.arguments)
 
        # 4. 執行你的函式
        result = get_weather(args["city"])  # 你自己的實現
 
        # 5. 將結果發回模型
        messages.append(message)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result)
        })
 
    # 獲取最終回覆
    final = client.chat.completions.create(
        model="openai/gpt-4o",
        messages=messages,
        tools=tools
    )
    print(final.choices[0].message.content)

TypeScript

Anthropic 協議#

Anthropic 使用 `tools` 引數,格式略有不同:

程式碼
import anthropic
 
client = anthropic.Anthropic(
    base_url="https://as.apinoma.com/anthropic",
    api_key="<你的 APINOMA_API_KEY>"
)
 
response = client.messages.create(
    model="anthropic/claude-sonnet-4.6",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "獲取指定城市的即時天氣資訊",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名稱"}
            },
            "required": ["city"]
        }
    }],
    messages=[{"role": "user", "content": "北京今天天氣怎麼樣?"}]
)
 
# 處理 tool_use content block
for block in response.content:
    if block.type == "tool_use":
        print(f"呼叫工具: {block.name}, 引數: {block.input}")

並行函式呼叫#

模型可以在一次回應中回傳多個工具呼叫,你應該並行執行它們:

程式碼
# 模型可能同時請求多個工具呼叫
if message.tool_calls:
    # 並行執行所有工具呼叫
    import asyncio
 
    async def execute_tools(tool_calls):
        tasks = []
        for tc in tool_calls:
            args = json.loads(tc.function.arguments)
            tasks.append(execute_function(tc.function.name, args))
        return await asyncio.gather(*tasks)

tool_choice 引數#

說明

`"auto"`

模型自動決定是否呼叫工具(預設)

`"none"`

禁止呼叫工具

`"required"`

強制呼叫工具

`{"type": "function", "function": {"name": "xxx"}}`

強制呼叫指定工具

支援的模型#

以下模型支援 Function Calling:

  • OpenAI: `gpt-4o`、`gpt-4o-mini`、`o1`、`o3-mini`
  • Anthropic: `claude-opus-4`、`claude-sonnet-4`、`claude-3-5-haiku`
  • Google: `gemini-pro-compatible-pro-preview`、`gemini-pro-compatible-flash-lite-preview`、`gemini-3-pro-preview`
  • 國產: `deepseek-chat`、`qwen-max`、`glm-4`

最後更新於 2026 年 6 月 23 日