OpenAI API error 400 Bad Request: {"error":{"message":"InvokeModelWithResponseSt...
错误信息
● WebSearch(?)
✘ ● Request failed
error: OpenAI API error 400 Bad Request: {"error":{"message":"InvokeModelWithResponseStream: operation error Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode: 400, RequestID: c42dfad0-4053-40e4-8ca8-88eb6c65dab6, ValidationException: ***.***.content.0: unexpected `tool_use_id` found in `tool_result` blocks: toolu_bdrk_01Ms38ntwpYzY8x3MaScX21v. Each `tool_result` block must have a corresponding `tool_use` block in the previous message. (request id: 20260409124954121895902L8xzu4QX) (request id: 20260409124952149985666Y22fseac) (request id: 202604091249521437007558268d9d6TL3KzXTV) (request id: 20260409124952131393178gjrZEukg) (request id: 20260409124951701898970LK3DFhpm)","type":"\u003cnil\u003e","param":"","code":null}}
AI 解决方案
报错分析报告
1.错误翻译
原文:unexpected `tool_use_id` found in `tool_result` blocks: toolu_bdrk_01Ms38ntwpYzY8x3MaScX21v. Each `tool_result` block must have a corresponding `tool_use` block in the previous message.
译文:在`tool_result`块中发现意外的`tool_use_id`:toolu_bdrk_01Ms38ntwpYzY8x3MaScX21v。每个`tool_result`块必须在前一条消息中有对应的`tool_use`块。
2.原因分析
tool_result块引用的tool_use_id(toolu_bdrk_01Ms38ntwpYzY8x3MaScX21v)在前一条消息中无对应tool_use块,违反Bedrock API的消息结构规则。 Bedrock Runtime: InvokeModelWithResponseStream接口时,消息的tool_result与前置tool_use的关联失效。3. 解决方案
需修正
tool_result的tool_use_id,确保与前序tool_use一致。以下是Python + Boto3的正确示例:import boto3
client = boto3.client("bedrock-runtime", region_name="us-east-1")
# 1. 先发送含tool_use的消息(生成唯一ID)
first_message = {
"messages": [
{
"role": "user",
"content": [
{"text": "查询北京天气"},
{
"tool_use": {
"tool_use_id": "toolu_valid_123", # 唯一且后续复用
"name": "web_search",
"input": {"query": "北京今日天气"}
}
}
]
}
],
"modelId": "anthropic.claude-3-sonnet-20240229-v1:0"
}
client.invoke_model_with_response_stream(**first_message)
# 2. 再发送含对应tool_result的消息(ID必须一致)
second_message = {
"messages": [
# 上一条消息(含tool_use)
...,
{
"role": "assistant",
"content": [
{
"tool_result": {
"tool_use_id": "toolu_valid_123", # 与之前tool_use_id完全一致
"content": [{"text": "北京今日晴,25℃,微风"}]
}
}
]
}
],
"modelId": "anthropic.claude-3-sonnet-20240229-v1:0"
}
client.invoke_model_with_response_stream(**second_message)
4.️ 预防措施
tool_use_id,确保tool_use与tool_result的ID严格一致(如示例中toolu_valid_123)。 tool_result.tool_use_id是否存在于前序tool_use中)。 jsonschema库(校验消息格式)、AWS Bedrock的[Message Structure文档](https://docs.aws.amazon.com/bedrock/latest/userguide/messages.html)。