chat_persistence_orderingTier 1 · 70% confidence

ai-agents-chat-persistence-ord-openai-api-returns-badrequesterror-with-role-tool--4bad74ca

agent: ai_agents

When does this happen?

IF OpenAI API returns BadRequestError with 'role tool must be response to preceding tool_calls' when loading a persisted SimpleChatStore and using OpenAIAgent with memory.

How others solved it

THEN Ensure that when loading a persisted chat store, messages with role 'tool' are correctly paired with preceding 'tool_calls' messages. Validate the message sequence before using as memory, or apply a correction function that reorders pairs. The memory buffer should maintain tool/assistant message pairing to avoid API errors.

def validate_and_correct_messages(messages):
    corrected = []
    for i, msg in enumerate(messages):
        if msg.role == 'tool':
            if i == 0 or messages[i-1].role != 'tool_calls':
                raise ValueError("Tool message without preceding tool_calls")
        corrected.append(msg)
    return corrected

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics