在 function calling(工具调用)的场景中,传递给大语言模型(LLM)的历史消息需要包含完整的对话上下文,包括用户输入、模型生成的工具调用请求(tool_calls
),以及工具执行后的返回结果。以下是详细的格式说明和示例:
消息历史需要按顺序包含这些步骤,格式如下:
{
"role": "user",
"content": "What's the weather in Beijing tomorrow?"
}
tool_calls
)tool_calls
字段的消息,描述需要调用的工具和参数。tool_calls
: 工具调用列表,每个调用包含唯一 id
、工具名称 name
和参数 arguments
。{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\", \"date\": \"2023-10-05\"}"
}
}
]
}
tool
角色的消息返回,需关联对应的 tool_call_id
。tool_call_id
: 与 tool_calls
中的 id
对应。content
: 工具返回的结果(通常是 JSON 字符串或纯文本)。{
"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."
}
// 用户提问
{
"role": "user",
"content": "What's the weather in Beijing tomorrow?"
},
// 模型请求调用工具
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\", \"date\": \"2023-10-05\"}"
}
}
]
},
// 工具返回结果
{
"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."
}
]
tool_call_id
:工具的返回结果必须与对应的工具调用请求通过 tool_call_id
匹配。tool_calls
列表有多个条目),需为每个工具调用单独返回对应的 tool
消息。通过这种方式,模型能够根据完整的对话历史和工具结果生成准确的回答。
{
"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"
}
}
]
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有