具備函式呼叫的 LLM:運作原理與程式碼
具備函式呼叫的 LLM 不會執行你的程式碼。它會回傳一個結構化請求,指定函式名稱與參數,由你的程式決定如何處理。本指南展示針對 OpenAI 相容端點執行完整迴圈的程式碼。
更新於
重點摘要
- 模型提出呼叫請求;你的程式執行該請求,並將結果以 role: tool 訊息回傳。
- 工具定義使用 JSON Schema,因此描述與參數類型會影響呼叫結果的品質。
- 務必驗證參數並限制迴圈迭代次數。
- 串流回應中的 tool_calls 是分段傳送的,你必須將它們組裝起來。

函式呼叫的實際定義
函式呼叫(亦稱工具呼叫)是你的程式與語言模型之間的協定。你以 JSON 結構描述函式。模型會讀取使用者訊息,然後以純文字回答,或以 tool_calls 列表回覆:包含函式名稱與參數的 JSON 字串。模型端不會執行任何動作。你的程式會執行該函式,然後將輸出結果送回,讓模型撰寫最終答案。
這個小迴圈將聊天模型轉變為能查詢訂單、查詢資料庫、檢查日曆或呼叫內部 API 的工具。這也是大多數 agent 框架的基礎。如果你能手寫下方的迴圈,就能除錯任何建立在它之上的框架。
此 API 遵循 OpenAI 聊天完成格式,支援 tools、tool_choice、串流輸出 tool_calls,以及以 role: "tool" 格式回傳的結果。Base URL 為 https://api.abliteratedllm.cc/v1,模型 ID 為 uncensored。
請求:描述工具
工具包含名稱、描述與參數結構描述。描述並非裝飾。模型透過閱讀描述來選擇工具,因此請將其寫成一行規格:說明函式的作用、使用時機與回傳內容。
{
"model": "uncensored",
"messages": [
{"role": "user", "content": "Is order 48213 shipped yet?"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "integer", "description": "The order number"}
},
"required": ["order_id"]
}
}
}
],
"tool_choice": "auto"
}
tool_choice 控制行為。使用 auto 時由模型決定。你也可以強制指定特定函式,以確保某個步驟總是產生結構化輸出。如果你只需要純淨的 JSON 且不需要外部呼叫,response_format: {"type": "json_object"} 會更簡單。
Python 完整迴圈
這個迴圈有四個步驟:傳送訊息與工具、檢查 tool_calls、執行每一項、附加結果並再次呼叫。當模型回答且未包含工具呼叫時停止。
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.abliteratedllm.cc/v1",
api_key=os.environ["LLM_API_KEY"],
)
def get_order_status(order_id: int) -> dict:
# replace with a real lookup
return {"order_id": order_id, "status": "shipped", "carrier": "post"}
REGISTRY = {"get_order_status": get_order_status}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Is order 48213 shipped yet?"}]
for _ in range(5): # hard cap on iterations
resp = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = resp.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg) # keep the assistant turn that holds tool_calls
for call in msg.tool_calls:
try:
args = json.loads(call.function.arguments)
result = REGISTRY[call.function.name](**args)
except Exception as e:
result = {"error": str(e)}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
三個細節會導致大多數初次使用的錯誤。包含 tool_calls 的助手訊息必須保留在歷史記錄中。每個工具訊息都需要對應的 tool_call_id。此外,工具訊息的 content 是字串,因此請將你的字典序列化。
從命令列嘗試
你可以在使用 SDK 之前,透過 curl 查看原始結構。傳送上一節的請求並查看回覆。
curl https://api.abliteratedllm.cc/v1/chat/completions \
-H "Authorization: Bearer $LLM_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Is order 48213 shipped yet?"}],
"tools": [{"type": "function", "function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"]}}}]
}'
在回應中,你要尋找的是 choices[0].message.tool_calls[0].function.arguments。這是一個包含 JSON 的字串,例如 {"order_id": 48213},而非物件。這就是為什麼 Python 程式會呼叫 json.loads 的原因。
串流輸出的工具呼叫
使用 stream: true 時,工具呼叫會以片段形式到達。呼叫的第一個區塊包含其 id 與函式名稱,後續區塊則追加參數字串的片段。你必須依 index 將片段串接,並在串流結束時才進行解析。
calls = {}
stream = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
if not chunk.choices:
continue
for tc in chunk.choices[0].delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
if tc.id:
slot["id"] = tc.id
if tc.function and tc.function.name:
slot["name"] = tc.function.name
if tc.function and tc.function.arguments:
slot["args"] += tc.function.arguments
# after the loop: json.loads(slot["args"]) for each entry
一個運作要點:串流請求會保留其並行請求槽位,直到串流結束。完整金鑰允許同時進行 8 個,試用金鑰允許 2 個。如果你的 agent 並行發送多個使用工具的對話,請計算串流數量,否則你會看到程式碼為 concurrency 的 429 錯誤回應。
Node 中的相同呼叫
JavaScript 中的結構相同。以下是第一輪,從回應中讀取工具呼叫並解析參數字串。
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.abliteratedllm.cc/v1",
apiKey: process.env.LLM_API_KEY,
});
const tools = [{
type: "function",
function: {
name: "get_order_status",
description: "Look up the shipping status of an order by its numeric ID.",
parameters: {
type: "object",
properties: { order_id: { type: "integer" } },
required: ["order_id"],
},
},
}];
const messages = [{ role: "user", content: "Is order 48213 shipped yet?" }];
const resp = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = resp.choices[0].message;
if (msg.tool_calls) {
const args = JSON.parse(msg.tool_calls[0].function.arguments);
console.log("model wants order", args.order_id);
}
何時 JSON 模式是更好的選擇
並非所有結構化任務都需要工具。如果你希望模型從文字中提取欄位(例如從電子郵件中提取姓名、日期和金額),則沒有函式可呼叫。請要求模型回傳 JSON 物件,將 response_format 設為 json_object,在提示詞中描述鍵值,然後解析回應。當模型必須在動作之間做出選擇,或你的程式必須根據結果採取行動並回傳內容時,請使用函式呼叫。
提高呼叫的可靠性
- 保持工具列表簡短。 五個清晰明確的工具勝過二十個重疊的工具。合併僅有一個參數差異的函式。
- 使用列舉。 如果參數有一組固定值,請在結構中列出它們,而不是用文字描述。
- 執行前進行驗證。 參數是模型輸出。檢查類型與範圍,切勿直接將它們傳遞至 shell 指令或 SQL 字串。
- 將錯誤作為資料回傳。當函式失敗時,將
{"error": "..."}作為工具結果回傳。模型通常會在下一輪自行修正。 - 限制迭代次數。上述迴圈在進行五輪後停止。若無上限,迷惘的模型可能會無止境地消耗 token。
- 降低 temperature。 對於工具選擇,0 到 0.3 的設定比預設的創意範圍更穩定。
當回答出乎意料時,請將 X-Request-Id 回應標頭與你自己的追蹤記錄一起記錄下來。這會讓支援問題的解答變得容易得多。
使用工具的 agent 成本
每個迴圈輪次都會重新傳送對話,包括工具定義,因此輸入 token 會增加。以支援機器人為例,每輪有 2,500 個輸入 token(歷史記錄加上工具結構)與 150 個輸出 token,典型問題需要 2 輪。輸入:5,000 tokens x $0.15 / 1,000,000 = $0.00075。輸出:300 tokens x $0.50 / 1,000,000 = $0.00015。總計每題 $0.0009,因此 1,000 題的成本為 $0.90。
計費採隨用隨付,輸入 token 每 100 萬個 $0.15,輸出 token 每 100 萬個 $0.50,失敗的請求不會收費。請見 定價頁面 進行儲值與查看獎金,文件 查看完整參數列表,以及 金鑰頁面 領取 $0.50 試用額度。如果你正在為這類工作比較模型,無過濾模型比較 說明了它們的差異。
此服務僅支援文字,且模型為單一開放權重模型,由獨立供應商提供,針對合法成人用途調校為不會因內容而拒絕回答。上線前,請務必在自有提示詞上測試自有結構。
更多指南
問答
模型會執行我的函式嗎?
不會。它只會回傳函式名稱與參數。你的程式會執行該函式,並將結果以 role 為 tool 的訊息送回。
我可以強制模型呼叫特定函式嗎?
可以,透過 tool_choice 欄位。當某個步驟必須產生結構化參數時,請使用此功能。
為什麼 function.arguments 是字串?
這遵循 OpenAI 格式,其中參數為 JSON 編碼的字串。請使用 json.loads 或 JSON.parse 解析,並處理格式錯誤的情況。
串流輸出是否支援與工具搭配使用?
會。工具呼叫會以片段串流輸出,你在解析前需依索引將它們串接起來。
工具定義會佔用我的 token 嗎?
是的。它們屬於提示詞的一部分,因此每次請求都會作為輸入 token 計費,而長工具列表在多次輪次中會累積消耗。