函式呼叫(function calling,也稱為工具使用 tool use)讓模型可以請你的程式碼執行某個函式,而不是直接回答:例如查詢天氣 API、查詢資料庫或進行計算,再用得到的結果完成回答。模型本身從不執行任何東西;它只會回傳一個「以特定參數呼叫某函式」的請求,而是否真的執行,由你的程式碼決定。
請求的結構
你要用 JSON Schema 描述每個可用的函式:名稱、說明,以及參數的結構。
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Tokyo"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]
模型會依據函式說明和參數說明來決定何時以及如何呼叫函式,所以請像向另一個人解釋這個函式那樣撰寫說明,而不只是寫出型別簽章。
完整的多輪範例
工具呼叫並不是對話的終點。模型會暫停,由你執行函式,再把結果放在一則新訊息中送回,讓模型繼續作答。
import json
from openai import OpenAI
client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 18, "unit": unit, "condition": "cloudy"}
messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]
resp = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
msg = resp.choices[0].message
messages.append(msg)
if msg.tool_calls:
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
print(final.choices[0].message.content)
這個範例依賴的重點:先附加助理的工具呼叫訊息,再附加工具結果;讓每個 tool_call_id 對應到它所回覆的呼叫;並以字串形式送出 content(物件請用 json.dumps 編碼)。
單輪中的多個工具呼叫
模型可以一次要求多個工具呼叫,例如查詢三個城市的天氣。請逐一處理 msg.tool_calls,為每個呼叫附加一則 "role": "tool" 訊息,各自帶上對應的 tool_call_id,然後再呼叫模型。
Anthropic Messages 格式
結構有所不同:每個工具的 schema 放在 input_schema 而非 function.parameters;工具呼叫會以 tool_use 內容區塊送達;結果則要以 tool_result 內容區塊放在使用者訊息中送回。
import anthropic
client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
tools = [{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]
resp = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
messages.append({"role": "assistant", "content": resp.content})
tool_use = next(b for b in resp.content if b.type == "tool_use")
result = get_weather(**tool_use.input)
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": json.dumps(result)}],
})
final = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
print(final.content[0].text)
強制或停用工具使用
預設情況下,由模型決定是否呼叫工具。若要強制使用某個特定工具,請傳入 tool_choice={"type": "function", "function": {"name": "get_weather"}}(OpenAI 格式)或 tool_choice={"type": "tool", "name": "get_weather"}(Anthropic 格式)。若要在保留工具定義的同時,讓模型在某次請求中不呼叫工具,請設定 tool_choice="none"(OpenAI 格式)或 tool_choice={"type": "none"}(Anthropic 格式)。
常見錯誤
- 用錯誤的角色回傳工具結果。OpenAI 格式要求使用
"role": "tool";它不接受以一般的使用者或助理訊息回傳結果。 - 忘了把助理的工具呼叫訊息送回去。模型需要在對話紀錄中看到自己的工具呼叫,才能把它和結果連結起來。
- 在
content中送出原始 Python 物件,而不是 JSON 字串。請一律用json.dumps序列化。 - 執行函式前沒有驗證參數。請把工具呼叫的參數視為來自模型的不可信輸入;在採取行動前先驗證型別和範圍,尤其是在將它們用於資料庫查詢或 shell 指令之前。
挑選模型
AIDiscount 上大多數現行模型都支援工具呼叫;市集中的模型頁面會在功能清單中列出。以下是幾個支援工具的模型及其目前價格:
| 模型 | 輸入 / 百萬 tokens | 輸出 / 百萬 tokens | 與官方價格比較 |
|---|---|---|---|
GPT-6 Lunagpt-6-luna | $0.05 | $0.30 | 優惠 40% |
Claude Opus 4.8claude-opus-4-8 | $0.375 | $1.875 | 優惠 92.5% |
DeepSeek V4 Prodeepseek-v4-pro | $0.3857 | $1.1571 | 優惠 41.6% |
Kimi K3kimi-k3 | $1.714 | $8.571 | 優惠 42.9% |
GLM-5.3glm-5.3 | $0.6857 | $2.40 | 優惠 45.5% |