Function Calling 執(zhí)行流程和歷史消息結(jié)構(gòu)
在 function calling(工具調(diào)用)的場景中,傳遞給大語言模型(LLM)的歷史消息需要包含完整的對話上下文,包括用戶輸入、模型生成的工具調(diào)用請求(tool_calls),以及工具執(zhí)行后的返回結(jié)果。以下是詳細的格式說明和示例:

核心流程與消息結(jié)構(gòu)
- 用戶提問 → 2. 模型生成工具調(diào)用請求 → 3. 工具執(zhí)行并返回結(jié)果 → 4. 模型根據(jù)結(jié)果生成最終回答
消息歷史需要按順序包含這些步驟,格式如下:
1. 用戶提問(User Message)
- 用戶的問題或請求。
- 格式:
{
"role": "user",
"content": "What's the weather in Beijing tomorrow?"
}
2. 模型生成工具調(diào)用請求(Assistant Message with tool_calls)
- 模型決定調(diào)用工具時,返回一個包含
tool_calls字段的消息,描述需要調(diào)用的工具和參數(shù)。 - 關(guān)鍵字段:
tool_calls: 工具調(diào)用列表,每個調(diào)用包含唯一id、工具名稱name和參數(shù)arguments。
- 格式:
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\", \"date\": \"2023-10-05\"}"
}
}
]
}
3. 工具執(zhí)行結(jié)果(Tool Message)
- 將工具執(zhí)行的結(jié)果以
tool角色的消息返回,需關(guān)聯(lián)對應的tool_call_id。 - 關(guān)鍵字段:
tool_call_id: 與tool_calls中的id對應。content: 工具返回的結(jié)果(通常是 JSON 字符串或純文本)。
- 格式:
{
"role": "tool",
"content": "{\"temperature\": 22, \"condition\": \"sunny\"}",
"tool_call_id": "call_abc123"
}
4. 模型生成最終回答(Assistant Message)
- 模型根據(jù)工具返回的結(jié)果生成最終回答。
- 格式:
"role": "assistant",
"content": "The weather in Beijing tomorrow will be sunny with 22°C."
}
完整示例對話歷史
// 用戶提問
{
"role": "user",
"content": "What's the weather in Beijing tomorrow?"
},
// 模型請求調(diào)用工具
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\", \"date\": \"2023-10-05\"}"
}
}
]
},
// 工具返回結(jié)果
{
"role": "tool",
"content": "{\"temperature\": 22, \"condition\": \"sunny\"}",
"tool_call_id": "call_abc123"
},
// 模型生成最終回答
{
"role": "assistant",
"content": "The weather in Beijing tomorrow will be sunny with 22°C."
}
]
關(guān)鍵注意事項
- 順序必須嚴格:消息需按時間順序排列,確保模型能正確理解上下文。
- 關(guān)聯(lián)
tool_call_id:工具的返回結(jié)果必須與對應的工具調(diào)用請求通過tool_call_id匹配。 - 工具結(jié)果格式:工具返回的結(jié)果可以是 JSON 字符串或純文本,但需與模型預期的輸入格式一致。
- 支持多工具調(diào)用:如果模型同時調(diào)用多個工具(如
tool_calls列表有多個條目),需為每個工具調(diào)用單獨返回對應的tool消息。
通過這種方式,模型能夠根據(jù)完整的對話歷史和工具結(jié)果生成準確的回答。
歷史消息樣例(deepseek-v3)
{
"model": "deepseek-chat",
"messages": [
{
"role": "user",
"content": "今天是星期幾?"
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"index": 0,
"id": "call_0_a762209f-0498-4166-a95c-5b8c5302dcaa",
"type": "function",
"function": {
"name": "get_current_datetime",
"arguments": "{}"
}
}
]
},
{
"tool_call_id": "call_0_a762209f-0498-4166-a95c-5b8c5302dcaa",
"role": "tool",
"content": "2025-03-26 10:16:20 星期三"
}
],
"stream": false,
"tools": [
{
"type": "function",
"function": {
"name": "get_current_datetime",
"description": "Get current datetime and day of week"
}
}
]
}
?? 持續(xù)分享AI工具,AI應用場景,AI學習資源 ??


?? 創(chuàng)作不易,如果這篇文章對你有幫助,歡迎??關(guān)注、??點贊支持,并?轉(zhuǎn)發(fā)給那些需要的朋友!關(guān)注 [拓荒者IT] 公眾號獲取更多精彩內(nèi)容!

浙公網(wǎng)安備 33010602011771號