Skip to content
AgenticAIWiki
  1. Learn
  2. Part 0
  3. 0. Your first agent in 15 minutes
  4. 0.3

Lesson 0.3 · 3 of 5 · 7 min read · Reviewed 24 Nov 2026

Watch the loop in the trace

By the end, you can

  • Run the agent loop: request, tool_use, run the tool, tool_result, repeat until end_turn.
  • Read a run's trace to see each step and why it happened.

Put the last two lessons together and you have an agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done.: a model that decides which tools to call, in a loop, until the job is done.

The idea

const messages = [{ role: 'user', content: "What's the weather in Lisbon and Paris?" }];
for (let turn = 1; turn <= 5; turn++) {            // always cap the loop
  const res = await client.messages.create({ model: 'claude-sonnet-5-5', max_tokens: 500, tools, messages });
  messages.push({ role: 'assistant', content: res.content });
  if (res.stop_reason !== 'tool_use') break;        // end_turn: the answer is ready
  const results = [];
  for (const block of res.content) if (block.type === 'tool_use')
    results.push({ type: 'tool_result', tool_use_id: block.id, content: await getWeather(block.input.city) });
  messages.push({ role: 'user', content: results }); // every result, in one message
}

Watch it run

Run The tool useTool use: Letting a model call functions you define, by returning a structured request your code executes. loop in the Playground, open the TraceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. tab and choose Step through. Each step is one event: the request leaving your code, the model’s decision (with its reason), the call to the weather service, and the answer coming back. Asking for two cities makes the model call the tool twice in one turn. That is parallel tool useParallel tool use: The model requesting several tool calls in one turn, which your code can run concurrently., and both results go back together.

How it fails

Return a result with the wrong tool_use_id and the API rejects the next request with a 400. Forget the turn cap and a tool that keeps failing can loop until your budget runs out. The Playground’s failure lab has a scenario for exactly this.

Key points

  • An agent is a loop: send the conversation, run any tools the model asks for, send the results back, and stop at end_turn.
  • Each tool result goes back in a user message as a tool_result block, matched to the call by tool_use_id.
  • Always cap the loop. A model that keeps calling tools will not stop on its own.
Hands-on labRuns in the Playground

Build a capped agent loop

Run the full request, tool_use, tool_result loop until the model answers, with a hard turn cap.

You will have: An agent loop that answers a two-city weather question and prints turns used, tool calls and the answer.

Steps

  1. Wrap the model call in a loop capped at MAX_TURNS.
  2. Append each assistant reply to messages and stop when stop_reason is not tool_use.
  3. Run get_weather for every tool_use block and send all results in one user message, matched by tool_use_id.
  4. Print the turns used, the tool calls and the final answer, then step through the run in the Trace tab.

Done when

  • The final stop_reason is end_turn.
  • Two tool calls are made, one per city.
  • The loop can never run more than MAX_TURNS times.

Open in the Playground No API key needed.

Starter code (Python)
import json
import anthropic

client = anthropic.Anthropic()

WEATHER = {"lisbon": {"temp_c": 19, "conditions": "sunny"}, "paris": {"temp_c": 11, "conditions": "cloudy"}}

def get_weather(city):
    data = WEATHER.get(city.lower())
    if data is None:
        return json.dumps({"error": f"no data for {city}"}), False
    return json.dumps({"city": city, **data}), True

tools = [{
    "name": "get_weather",
    "description": "Get the current weather for one city. Returns temperature in Celsius and conditions. Use it for any question about the weather somewhere.",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}]

messages = [{"role": "user", "content": "What's the weather in Lisbon and Paris?"}]
MAX_TURNS = 5

response = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools, messages=messages)
print("first stop_reason:", response.stop_reason)
# TODO: wrap the call in a loop capped at MAX_TURNS
# TODO: append the assistant reply to messages; stop when stop_reason is not "tool_use"
# TODO: run get_weather for every tool_use block and send all tool_result blocks
#       (matched by tool_use_id) back in ONE user message
# TODO: print the turns used, the number of tool calls and the final answer
Show a solution
import json
import anthropic

client = anthropic.Anthropic()

WEATHER = {"lisbon": {"temp_c": 19, "conditions": "sunny"}, "paris": {"temp_c": 11, "conditions": "cloudy"}}

def get_weather(city):
    data = WEATHER.get(city.lower())
    if data is None:
        return json.dumps({"error": f"no data for {city}"}), False
    return json.dumps({"city": city, **data}), True

tools = [{
    "name": "get_weather",
    "description": "Get the current weather for one city. Returns temperature in Celsius and conditions. Use it for any question about the weather somewhere.",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}]

messages = [{"role": "user", "content": "What's the weather in Lisbon and Paris?"}]
MAX_TURNS = 5
tool_calls = 0

for turn in range(1, MAX_TURNS + 1):
    response = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools, messages=messages)
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        break
    results = []
    for block in response.content:
        if block.type == "tool_use":
            tool_calls += 1
            text, ok = get_weather(block.input["city"])
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": text, "is_error": not ok})
    messages.append({"role": "user", "content": results})  # every result, in one message
else:
    print("stopped: hit the turn cap")

answer = "".join(b.text for b in response.content if b.type == "text")
print("turns used:", turn, "| tool calls:", tool_calls)
print("final stop_reason:", response.stop_reason)
print("answer:", answer[:100])

Do it Build the loop, then step through its trace in the Playground. No API key needed.

Quick checkPut one turn of the agent loop in order.
  1. Your code runs the tool
  2. The model replies with end_turn and an answer
  3. Send the conversation and the tools
  4. The model replies with a tool_use block
  5. Send a tool_result matched by tool_use_id
How sure are you?
Pick how sure you are