Skip to content

Build the agent loop

Write an agent loop that branches on stop_reason and returns tool results in the shape the API expects, and pick between the tool runner, a custom loop, the Agent SDK and Managed Agents for stated constraints.

Scenario

Your order-lookup agent worked in the demo. In staging, every conversation where Claude calls a tool fails with a 400 error: "tool_use ids were found without tool_result blocks immediately after".

The tool ran and returned the right data. The bug is one friendly line you added before the results: "Here is what I found:".

Explanation

An agent is a model using tools in a loop. With the Messages API you write that loop, and the API is stateless: every request carries the whole conversation.

One turn of the loop:

  1. Send messages and tools.
  2. Append the assistant's content to messages unchanged, including its tool_use blocks.
  3. Branch on stop_reason, not on whether the response contains text. Claude often writes "Let me check that" in the same response as a tool call.
stop_reason Meaning Your loop
tool_use Claude wants your tools run Run them, send the results, loop
end_turn Finished Return the answer
pause_turn A server tool (such as web search) hit its iteration limit Send the response back as it is, loop
max_tokens Cut off Raise max_tokens or continue; an incomplete tool_use block means retry with more room
model_context_window_exceeded The response filled the model's context window Treat it as truncated, never as an answer; trim or compact the history before going on
stop_sequence Claude emitted one of your stop_sequences Read stop_sequence to see which one fired, and act on it
refusal Declined Read stop_details, and retry on a fallback model where that fits; don't loop

The tool result shape. Answer every tool_use block in one user message:

  • one tool_result block per call, with tool_use_id set to that block's id;
  • content holding the output (a string or content blocks);
  • is_error: true when the tool failed, with a message Claude can act on;
  • the tool_result blocks first in the message, with any text after them, and no other message between the assistant's tool call and your results.

Add a stopping condition. Cap the number of iterations, so a confused agent can't loop forever.

You don't always write the loop yourself.

Option Who runs the loop Fits when
Custom loop (Messages API) You You need approval steps, custom logging or conditional execution
Tool runner (client SDK, beta) The SDK, in your code Your own functions as tools, no special control
Agent SDK (Python, TypeScript) Claude Code's loop as a library, in a process you operate You want built-in file, bash and search tools, permissions, hooks and sessions
Managed Agents (beta) Anthropic's hosted harness Long-running or asynchronous work, sandbox in Anthropic's cloud or self-hosted on your infrastructure

Worked example

Before. The results go back with a text block in front of them, so the request fails with the 400 from the Hook:

results = [run_one(b) for b in resp.content
           if b.type == "tool_use"]
messages.append({"role": "user", "content": [
    {"type": "text", "text": "Here is what I found:"},
    *results,
]})

After. The loop branches on the stop reason, returns only a finished answer, and stops after a fixed number of steps:

for _ in range(MAX_STEPS):
    resp = client.messages.create(model=MODEL,
        max_tokens=4096, tools=TOOLS, messages=messages)
    messages.append({"role": "assistant",
                     "content": resp.content})
    stop = resp.stop_reason
    if stop == "tool_use":
        messages.append({"role": "user",
                         "content": run_tools(resp)})
    elif stop == "end_turn":
        return resp
    elif stop != "pause_turn":  # pause_turn: resend as is
        raise StopReasonError(resp)  # truncated or refused
raise RuntimeError("step limit reached")

And run_tools answers every call, failures included:

def run_tools(resp):
    results = []
    for block in resp.content:
        if block.type != "tool_use":
            continue
        try:
            out = TOOLS_BY_NAME[block.name](**block.input)
            results.append({"type": "tool_result",
                "tool_use_id": block.id, "content": out})
        except Exception as e:
            results.append({"type": "tool_result",
                "tool_use_id": block.id,
                "content": str(e), "is_error": True})
    return results

A failed lookup now reaches Claude as an error result it can explain or retry, instead of crashing the loop or leaving a call unanswered.