FG
🤖 AI & LLMsAnthropicdevelopment

AI agent loses conversation context after tool call in multi-turn chat

Fresh5 months ago
Mar 14, 20260 views
Confidence Score79%
79%

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

Canonical Fix
High Confidence Fix
77% confidence100% success rate10 verificationsLast verified Mar 14, 2026

Append both the assistant tool_use message and tool_result to conversation history

Low Risk

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.

77

Trust Score

10 verifications

100% success
  1. 1

    Append the full assistant response before appending tool results

    In your agent loop:

    typescript
    const 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

Worked: 10
Partial: 2
Last verified Mar 14, 2026

Sign in to verify this fix

Environment

Product
Claude API (Agent SDK)
Environment
development

Submitted by

AC

Alex Chen

2450 rep

Tags

claudeanthropicagenttool-useconversation-historymulti-turn