":{"message":"Invalid param: Message format error, the role 'tool' of index [*] ...

2026年02月25日 20:19 状态: processing

🚨 错误信息

HttpException: HTTP 400: {"error":{"message":"Invalid param: Message format error, the role 'tool' of index [*] must be a response to a preceeding assistant message with 'tool_calls'.","type":"rix_api_error","param":"8b7649d5-4187-40f3-9794-4d196200b092","code":"param_error"}}

🤖 AI解决方案

代码糕手 - 专业报错分析助理

错分析报告

错误翻译



原文:Invalid param: Message format error, the role 'tool' of index [*] must be a response to a preceeding assistant message with 'tool_calls'
译文:参数无效:消息格式错误,索引[*]处的角色'tool'必须是对前一个包含'tool_calls'的助手消息的响应

2


这是一个API调用格式错误,发生在使用工具调用功能时。根本原因是:
  • 消息顺序错误:在对话历史中,role: 'tool'的消息没有正确跟随在role: 'assistant'且包含tool_calls的消息之后

  • 格式不匹配:工具响应消息没有正确关联到对应的工具调用请求
  • 3


    修复消息格式,确保正确的消息顺序:

    javascript
    // 正确的消息格式示例
    const messages = [
    {
    role: 'user',
    content: '查询北京的天气'
    },
    {
    role: 'assistant',
    content: null,
    tool_calls: [
    {
    id: 'call_abc123',
    type: 'function',
    function: {
    name: 'get_weather',
    arguments: JSON.stringify({ city: '北京' })
    }
    }
    ]
    },
    {
    role: 'tool',
    tool_call_id: 'call_abc123', // 必须匹配前一个assistant消息中的tool_call_id
    name: 'get_weather',
    content: JSON.stringify({ temperature: 25, condition: '晴朗' })
    }
    ];

    // 错误示例 - 不要这样做
    const wrongMessages = [
    {
    role: 'user',
    content: '查询天气'
    },
    {
    role: 'tool', // ❌ 错误:tool消息没有对应的assistant tool_calls
    content: '{"temperature": 25}'
    }
    ];

    ️ 预防措施


  • 消息顺序验证:在发送API请求前,验证消息数组的顺序是否符合规范

  • 使用SDK工具:推荐使用官方SDK(如OpenAI Node.js库),它们会自动处理消息格式和工具调用流程

  • 调试工具:使用API调试工具(如Postman)先测试消息格式,确保正确后再集成到代码中
  • ---
    请检查您的对话历史数组,确保每个tool角色消息都有对应的前一个assistant消息包含tool_calls,并且tool_call_id匹配正确。