HTTP 400: An assistant message with 'tool_calls' must be followed by tool messag...
错误信息
Error: HTTP 400: An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'. (insufficient tool messages following tool_calls message)
AI 解决方案
🔍 报错分析
1. 🌐 错误翻译
原文:Error: HTTP 400: An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'. (insufficient tool messages following tool_calls message)
译文:错误:HTTP 400:包含'tool_calls'的助手消息后面必须跟有响应每个'tool_call_id'的工具消息。(工具调用消息后工具消息数量不足)
2. 🎯 原因分析
此错误发生在调用大模型API时,当模型输出了工具调用请求(
tool_calls)后,你没有按照协议返回对应每个工具调用ID的执行结果(tool messages),导致API请求不完整,违反了工具调用的交互流程规范。3. 💡 解决方案
需要确保在收到模型的工具调用请求后,执行对应的工具函数,并将每个工具的执行结果按照tool_call_id返回给API,形成完整的工具调用交互闭环。以下是修复后的代码示例(以Python为例,调用对话API时的工具调用响应逻辑):
# 假设已获取模型返回的tool_calls,且工具函数已定义
# 1. 执行所有工具调用
tool_responses = []
for tool_call in model_response.tool_calls:
# 根据工具名称调用对应函数
if tool_call.function.name == "target_tool":
result = target_tool_function(**tool_call.function.arguments)
# 其他工具...
# 2. 构造符合要求的工具响应消息
tool_responses.append({
"role": "tool",
"tool_call_id": tool_call.id, # 必须匹配对应工具调用的ID
"content": str(result) # 工具执行结果
})
# 3. 将工具响应传回API,完成完整交互
# 此处以调用API的参数形式为例,具体根据实际API SDK调整
response = client.chat.completions.create(
# ...其他基础参数
messages=[
# ...历史对话消息
*model_response.choices[0].message, # 模型的工具调用消息
*tool_responses # 追加所有工具响应消息
]
)
4. 🛡️ 预防措施
tool_call_id返回对应的工具执行结果,两者需一一对应,不可遗漏或错配。tool_calls,确保每个调用都有对应的响应构造,避免少响应或无响应。