cuddly-cartoon-47334
07/29/2025, 11:02 PMtall-airline-16756
07/29/2025, 11:02 PMtall-airline-16756
07/29/2025, 11:03 PMAPIStatusError 400, with the message "Invalid parameter: messages with role 'tool' must be a response to a preceding message with 'tool_calls'" occurs when the conversation flow between tool calls and tool responses is not properly structured in the LiveKit agents framework.
Steps to Resolve:
1. Ensure Proper Message Sequencing: Verify that your conversation flow follows this pattern:
◦ An assistant message with tool_calls
◦ Followed by tool response messages with role 'tool' and matching tool_call_id
1. Verify Tool Call ID Matching: Ensure the tool_call_id in your tool response exactly matches the call_id from the corresponding function call.
2. Use Built-in Validation: Utilize the framework's group_tool_calls function to automatically group related messages, function calls, and outputs together. This function also removes invalid tool calls and outputs.
3. Check Your ChatContext Structure: Ensure your ChatContext contains properly structured items where:
◦ FunctionCall items have valid call_id values
◦ FunctionCallOutput items reference the correct call_id from their corresponding function calls
1. Review Message Building Logic: If you're manually constructing messages, ensure that:
◦ Tool response messages have the role 'tool'
◦ They include the correct tool_call_id matching a previous tool call
◦ Tool responses are only sent after assistant messages containing tool_calls
The framework's built-in validation and grouping mechanisms should handle most cases automatically, but this error typically indicates that the conversation flow has been disrupted or tool call IDs are mismatched.
Sources: livekit-agents/livekit/agents/llm/_provider_format/aws.pycuddly-cartoon-47334
07/29/2025, 11:17 PMcuddly-cartoon-47334
07/29/2025, 11:17 PMtall-airline-16756
07/29/2025, 11:17 PM