Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode:...

2026年07月15日 15:16 31.83 秒 success

错误信息

status_code=400, InvokeModelWithResponseStream: operation error Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode: 400, RequestID: ac073d74-93dd-416a-ab36-df893ad7edc3, ValidationException: messages: text content blocks must be non-empty (request id: 20260715065205783018555rMQtQc3stgn6G0H1)

AI 解决方案

🔍 错误分析

1. 🌐 错误翻译


原文:status_code=400, InvokeModelWithResponseStream: operation error Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode: 400, RequestID: ac073d74-93dd-416a-ab36-df893ad7edc3, ValidationException: messages: text content blocks must be non-empty (request id: 20260715065205783018555rMQtQc3stgn6G0H1)
译文:状态码=400,InvokeModelWithResponseStream:操作错误 Bedrock Runtime:InvokeModelWithResponseStream,https 响应错误 状态码:400,请求ID:ac073d74-93dd-416a-ab36-df893ad7edc3,验证异常:消息:文本内容块必须非空(请求id:20260715065205783018555rMQtQc3stgn6G0H1)

2. 🎯 原因分析


  • 根本原因:向 Bedrock Runtime 的 InvokeModelWithResponseStream 接口发送的请求中,消息的文本内容块为空(空字符串或完全缺失)

  • 错误位置:发生在构造消息体时,文本内容块未正确填充有效内容,违反了接口的必填字段验证规则
  • 3. 💡 解决方案


    检查并确保请求中所有消息的文本内容块非空,补充有效内容后再发送请求。以下是修复后的示例代码(以 Python 为例,使用 boto3 调用 Bedrock):
    import boto3
    
    # 初始化 Bedrock 客户端
    bedrock = boto3.client(
        service_name='bedrock-runtime',
        region_name='us-east-1'  # 根据实际情况调整区域
    )
    
    # 构造请求参数,确保text字段为非空字符串
    request_body = {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "请帮我分析这段数据"  # 避免为空,必须填充有效内容
                    }
                ]
            }
        ],
        # 其他必要的模型参数(如模型ID、推理配置等)
        "modelId": "arn:aws:bedrock:us-east-1:xxxxxxxxxxxx:foundation-model/amazon.titan-text-express-v1",
        # 根据模型要求补充其他字段
    }
    
    try:
        # 发送请求,确保内容块非空
        response = bedrock.invoke_model_with_response_stream(
            modelId=request_body["modelId"],
            body=json.dumps(request_body)
        )
        # 处理响应逻辑
    except Exception as e:
        print(f"请求失败:{e}")
    

    4. 🛡️ 预防措施


  • 数据校验前置:发送请求前,对所有文本内容块进行非空校验,禁止空字符串、空数组或未定义内容进入请求体。

  • 单元测试覆盖:编写针对请求参数的测试用例,重点验证必填字段的有效性,确保极端场景(如内容为空)被拦截,避免直接触发接口调用。