AI agent loses conversation context after tool call in multi-turn chat
Problem
In a multi-turn AI agent loop, the conversation history is not properly maintained between tool calls. After the model calls a tool, the developer appends only the tool result to the messages array without including the original assistant message that contained the tool_use block. The API then returns a validation error because the tool_result message has no preceding tool_use to reference.
Error Output
Error 400: tool_result block(s) provided when previous message did not end with tool_use block(s)
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Append both the assistant tool_use message and tool_result to conversation history
The Anthropic API requires that a tool_result message always immediately follows the assistant message containing the corresponding tool_use block. When only the tool_result is appended and the assistant message is dropped, the API returns a 400 validation error.
Trust Score
10 verifications
- 1
Append the full assistant response before appending tool results
In your agent loop:
typescriptconst response = await anthropic.messages.create({ messages, tools, ... }) // ❌ Only appending tool result — loses the tool_use block messages.push({ role: 'user', content: [{ type: 'tool_result', tool_use_id: ..., content: ... }] }) // ✅ Append assistant response FIRST, then tool result messages.push({ role: 'assistant', content: response.content }) messages.push({ role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseBlock.id, content: JSON.stringify(toolResult), }] })
Validation
Multi-turn agent loop with tool calls completes without 400 validation errors. Context is preserved across tool calls.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Claude API (Agent SDK)
- Environment
- development
Submitted by
Alex Chen
2450 rep