在多轮工具调用中如何正确处理第二轮结果与 tool_call_id
- 保存模型返回的完整 assistant 消息,包括 reasoning_content 和 tool_calls。[2]
- 执行每个工具,用返回的 tool_calls[].id 填写对应结果的 tool_call_id。
- 下一轮发送原有上下文、原始 assistant 消息以及所有匹配的工具结果。
并行工具可能乱序完成,应按 ID 配对,不能只按返回先后猜测。ID 缺失、重复或结果未齐时,先检查历史并处理缺失结果,再继续。
Kimi K3.1 Pro 多轮工具调用结构:从第一轮到第二轮
流程是:用户提问 → 模型返回 assistant 消息和 tool_calls → 应用执行工具 → 每条 tool 消息携带对应 ID → 将完整历史发回模型。Kimi 模型卡明确要求保留完整 assistant 消息,而不仅是 content。[2]
| 消息角色 | 字段名称 | 字段作用 | 与 tool_call_id 的关系 |
|---|---|---|---|
| assistant | tool_calls[].id | 模型返回的调用 ID | 原样保存,作为对应结果的配对依据 |
| assistant | tool_calls[].function.name / arguments | 要调用的函数与参数 | 按实际接口解析,勿将调用顺序当作身份 |
| tool | tool_call_id | 本条结果所属的调用 ID | 与该次 tool_calls[].id 完全相同 |
| tool | content | 工具执行结果 | 按接口要求序列化;保留与原调用的对应关系 |
公开编码器会按 ID 匹配最近一组工具结果并调整顺序;这是该编码器的实现细节,不应据此假设所有平台都接受乱序结果。[1]
tool_call_id 在多轮调用中的语义与作用
tool_call_id 用于把一条工具结果关联到具体调用。检查同一条 assistant 消息内的 ID 是否缺失或重复;不要自行改写模型返回的 ID。[1]
- 工具重试属于同一次调用时,保留模型的调用 ID,另用内部尝试编号记录各次执行。
- 如果调用结果未知,先核对状态再重试,避免重复执行有副作用的操作。
- 跨请求日志可另外使用会话 ID 和业务追踪 ID,不要把它们替换为 tool_call_id。
分步示例:保存工具调用与结果并在第二轮携带完整上下文
- 读取并原样保存第一轮 assistant 消息。
- 校验调用 ID、工具名和参数;执行工具并把结果按 ID 保存。
- 为每个调用构造一条 tool 消息,返回完整历史;如工具失败,应按接口要求返回明确错误或停止等待处理。
# 伪代码示例:保存工具调用与结果,并在第二轮携带完整上下文
# 注意:仅示意数据结构与流程,不包含具体 SDK / HTTP 细节。
# 1. 发送第一轮请求,得到带工具调用的 assistant 响应
user_message = {"role": "user", "content": "帮我查一下天气并创建一个提醒"}
# response_1 假设为模型返回的结构化数据,其中包括 assistant 消息
response_1 = call_kimi_api(messages=[user_message]) # 伪函数
assistant_msg_1 = response_1["choices"][0]["message"]
# 2. 解析工具调用并按 tool_call_id 保存调用单元
# 约定:assistant_msg_1["tool_calls"] 是一个列表,每个元素表示一次工具调用
call_registry = {} # 以 tool_call_id 为键保存整个调用生命周期
for tool_call in assistant_msg_1.get("tool_calls", []):
call_id = tool_call.get("id") # 即 tool_call_id
function = tool_call.get("function") or {}
tool_name = function.get("name") # 函数名位于 function 对象中
tool_args = function.get("arguments") # 通常是 JSON 字符串
if not call_id or call_id in call_registry:
raise ValueError("工具调用 ID 缺失或重复,停止第二轮请求")
if not tool_name or tool_args is None:
raise ValueError("工具名称或参数缺失,停止第二轮请求")
call_registry[call_id] = {
"tool_name": tool_name,
"arguments": tool_args,
"status": "pending",
"result": None,
}
# 3. 按 ID 实际执行工具,并生成带相同 tool_call_id 的结果对象
tool_result_messages = [] # 准备发送给模型的“工具结果消息”列表
for call_id, record in call_registry.items():
if record["status"] != "pending":
continue
# 根据工具名路由到具体实现(HTTP、数据库、本地函数等)
result_payload = execute_tool(
name=record["tool_name"],
arguments=record["arguments"],
)
# 在调用记录中保存结果
record["status"] = "completed"
record["result"] = result_payload
# 构造一条工具结果消息,关键是携带同一个 tool_call_id
tool_result_messages.append({
"role": "tool",
"tool_call_id": call_id, # 必须与原始调用的 ID 完全一致
"name": record["tool_name"],
"content": serialize_result(result_payload), # 将结果序列化为字符串/JSON
})
# 提示:如果这里漏传某个 call_id,或某个结果消息的 tool_call_id
# 与第一轮的调用 ID 不一致,模型在第二轮就可能无法正确关联
# 该结果属于哪一次调用,从而影响后续推理或工具调用计划。
# 4. 构造第二轮请求,将完整上下文(用户消息 + 第一轮调用 + 工具结果)一起发送
messages_for_round_2 = [
user_message,
assistant_msg_1,
] + tool_result_messages
response_2 = call_kimi_api(messages=messages_for_round_2) # 再次调用模型
assistant_msg_2 = response_2["choices"][0]["message"]
# 5. 后续轮次复用同一模式
# 如果 assistant_msg_2 中仍然包含新的工具调用(例如 assistant_msg_2["tool_calls"]),
# 则可以:
# - 重复步骤 2:解析新的 tool_calls,按 ID 写入 call_registry 或新建一个 registry;
# - 重复步骤 3:按 tool_call_id 执行工具,并生成对应的工具结果消息;
# - 重复步骤 4:将最新的工具调用和结果连同历史消息一起发给模型。
# 当某一轮 assistant 不再返回新的工具调用,而是直接给出最终自然语言答复时,
# 就可以视为当前调用链结束;此时仍建议保留 call_registry 中的全部记录,
# 以便后续日志分析、调试或重建这次调用的完整轨迹。复杂工作流中围绕 tool_call_id 的设计取舍
| 场景 | 处理方式 | 收益 | 注意事项 |
|---|---|---|---|
| 串行调用 | 保留 assistant 消息和对应结果 | 便于排查和回放 | 结果 ID 必须匹配原调用 |
| 并行调用 | 按模型返回的 ID 收集结果 | 避免按完成顺序错配 | 所有结果齐全后再继续 |
| 失败或超时 | 保留原 ID,另记尝试编号 | 可追踪一次调用的多次执行 | 结果未知先查状态,避免重复副作用 |
| 多服务日志 | 记录会话、调用和尝试编号 | 跨组件追踪 | 日志按需脱敏 |
应用内部可以自定义业务追踪号,但发送给模型的工具结果仍应引用模型返回的原调用 ID。
验证 Kimi K3.1 Pro 多轮工具调用与 tool_call_id 行为
模型卡要求续传完整 assistant 消息;不同服务对异常消息的具体报错可能不同。[2] 以下测试应在受控环境执行,避免触发真实业务操作。
- 正常:两个工具乱序完成,按 ID 配对后按调用顺序组装结果。
- 异常:缺失、重复或错误 ID 时在客户端停止,确认不会错误续传。
- 升级后:更换 SDK 或服务时,用相同用例核对消息、错误和日志;记录时去除敏感内容。
可运行的两轮请求示例
下面的 Python 3 示例使用标准库:设置 SMTOKEN_API_KEY 后执行,会向 SmarToken 发起两次真实请求,可能产生费用;get_temperature 是本地模拟工具,18°C 不是实时天气。如模型未发工具调用,程序会停止;结果以实际接口为准。
import json
import os
from urllib.request import Request, urlopen
from urllib.error import HTTPError
base = os.environ.get('SMTOKEN_BASE_URL', 'https://thesmartoken.com/v1').rstrip('/')
key = os.environ['SMTOKEN_API_KEY']
model = 'kimi-k3.1-pro'
tools = [{"type": "function", "function": {
"name": "get_temperature", "description": "Return a demo temperature for a city.",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}},
"required": ["city"]}}}]
messages = [{"role": "user", "content": "Use get_temperature to look up Paris, then answer."}]
def chat():
body = json.dumps({"model": model, "messages": messages, "tools": tools,
"stream": False}).encode()
request = Request(base + '/chat/completions', data=body,
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
try:
with urlopen(request, timeout=60) as response:
print('HTTP status:', response.status)
return json.load(response)['choices'][0]['message']
except HTTPError as error:
print('HTTP status:', error.code)
raise
assistant = chat()
calls = assistant.get('tool_calls') or []
if not calls:
raise RuntimeError('No tool call returned; inspect the first response before continuing.')
messages.append(assistant) # Preserve the complete response, including reasoning fields.
seen = set()
for call in calls:
call_id = call.get('id')
fn = call.get('function') or {}
if not call_id or call_id in seen or fn.get('name') != 'get_temperature':
raise ValueError('Missing/duplicate ID or unexpected tool; stop.')
seen.add(call_id)
args = json.loads(fn['arguments'])
if not isinstance(args, dict) or not isinstance(args.get('city'), str):
raise ValueError('Invalid city argument.')
result = {'city': args['city'], 'temperature_c': 18, 'source': 'illustrative'}
messages.append({'role': 'tool', 'tool_call_id': call_id,
'content': json.dumps(result, ensure_ascii=False)})
answer = chat()
print(answer.get('content') or '[No final text; inspect the response]')2026 年 12 月 1 日,我们用 kimi-k3.1-pro 实际完成一次两轮请求,max_tokens 为 400。下表为脱敏摘录;同一个 <call_id> 表示两处原始编号相同,实际续传时必须保留完整 assistant 消息和原始编号。工具的 18°C 是本地示例值,不是真实天气。
| 环节 | 实际内容(摘录) |
|---|---|
| 首轮用户请求 | Use get_temperature to look up Paris, then answer. |
| 首轮模型响应 | 调用 get_temperature,参数 {"city": "Paris"},id = <call_id> |
| 工具结果 | tool_call_id = <call_id>;{"city":"Paris","temperature_c":18,"source":"illustrative"} |
| 第二轮模型响应 | Paris is 18°C (illustrative temperature). |
这份代码另用 Python 3.9.6 和本地模拟 HTTP 服务复测,无需安装第三方包;模拟时打印两次 HTTP status: 200 和 Paris: 18°C (illustrative)。实际调用的状态、回复和用量以接口返回为准。
真实两轮请求与响应
以下是 2026 年 12 月 1 日对 POST https://thesmartoken.com/v1/chat/completions 的一次实测记录。为便于公开,响应编号被替换,reasoning_content 已脱敏;两处 <call_id> 代表同一个原始工具调用编号。凭据未包含在请求体中。它是核对流程的记录,不可直接复制脱敏内容作为第二轮请求;运行上面的示例时使用接口返回的原始 assistant 消息和编号。18°C 为本地模拟值。
第一轮请求
{
"model": "kimi-k3.1-pro",
"messages": [
{
"role": "user",
"content": "Use get_temperature to look up Paris, then answer."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_temperature",
"description": "Return a demo temperature for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
],
"stream": false,
"max_tokens": 400
}第一轮响应
{
"id": "<response_1>",
"object": "chat.completion",
"created": 1796107750,
"model": "kimi-k3.1-pro",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "",
"reasoning_content": "[redacted]",
"tool_calls": [
{
"function": {
"arguments": "{\"city\": \"Paris\"}",
"name": "get_temperature"
},
"id": "<call_id>",
"index": 0,
"type": "function"
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 175,
"completion_tokens": 77,
"total_tokens": 252
}
}第二轮请求
{
"model": "kimi-k3.1-pro",
"messages": [
{
"role": "user",
"content": "Use get_temperature to look up Paris, then answer."
},
{
"role": "assistant",
"content": "",
"reasoning_content": "[redacted]",
"tool_calls": [
{
"function": {
"arguments": "{\"city\": \"Paris\"}",
"name": "get_temperature"
},
"id": "<call_id>",
"index": 0,
"type": "function"
}
]
},
{
"role": "tool",
"tool_call_id": "<call_id>",
"content": "{\"city\": \"Paris\", \"temperature_c\": 18, \"source\": \"illustrative\"}"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_temperature",
"description": "Return a demo temperature for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
}
],
"stream": false,
"max_tokens": 400
}第二轮响应
{
"id": "<response_2>",
"object": "chat.completion",
"created": 1796107755,
"model": "kimi-k3.1-pro",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Paris is **18°C** (illustrative temperature).",
"reasoning_content": "[redacted]"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 304,
"completion_tokens": 57,
"total_tokens": 361
}
}两次调用分别返回 175 / 77 和 304 / 57 个输入 / 输出 Token;数字来自本次回执,不代表其他任务用量。原始日志未单独保存 HTTP 状态码,不在此推断具体状态值。
两项工具调用的倒序回填实测
2026 年 12 月 1 日,我们通过 SmarToken 在线调试接口用 kimi-k3.1-pro 发起两轮请求,要求分别查询巴黎和柏林。首轮一次返回两个 get_temperature 调用;应用本地提供虚构温度,并故意按相反顺序回填。两次 HTTP 均为 200;下表将真实调用 ID 脱敏为 A、B,映射在各行保持一致。
| 阶段 | 脱敏记录 |
|---|---|
| 首轮调用 A | get_temperature({"city":"Paris"}) |
| 首轮调用 B | get_temperature({"city":"Berlin"}) |
| 先回填 B | tool_call_id=B,Berlin,22°C(示意) |
| 再回填 A | tool_call_id=A,Paris,18°C(示意) |
| 第二轮回答 | Paris 18°C;Berlin 22°C,均为示意值 |
第二轮回答把巴黎与 18°C、柏林与 22°C 正确对应,并标明是示意温度。首轮输入/输出为 184/230 Token,第二轮为 497/70 Token;两轮 max_tokens 均为 400。本例只验证这一次倒序回填,不证明实际工具并发执行,也不能保证其他服务支持相同顺序。