函式呼叫(Function Calling)
函式呼叫允許模型根據使用者需求,自動選擇並呼叫你預定義的工具函式,實作資料查詢、API 呼叫、任務執行等能力。
基本概念
函式呼叫的完整流程:
- 定義工具 — 在請求中描述可用函式和參數
- 模型決策 — 模型判斷是否需要呼叫工具
- 回傳呼叫 — 模型回傳函式名和參數
- 執行函式 — 你執行函式並取得結果
- 繼續對話 — 將結果發回模型,生成最終回覆
OpenAI 協議
Python
function_calling.py
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="<你的 OFOXAI_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)Anthropic 協議
Anthropic 使用 tools 參數,格式略有不同:
anthropic_tools.py
import anthropic
client = anthropic.Anthropic(
base_url="https://api.ofox.ai/anthropic",
api_key="<你的 OFOXAI_API_KEY>"
)
response = client.messages.create(
model="anthropic/claude-sonnet-4.5",
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-3.1-pro-preview、gemini-3-flash-preview、gemini-3-pro-preview - 國產:
deepseek-chat、qwen-max、glm-4
Last updated on