← Building with AI

The tool loop

Ask, run tools, send results back, until the model answers.

Start this lesson

A full tool conversation is a loop. Send the question. If the reply is text, you are done. If it is a tool request, run the tool, add the result to the messages, and ask again. The model may ask for several tools in a row (for example the weather in two cities) before it writes its final answer. Put a maximum on the number of steps so a confused model can't loop forever.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
# (tools and run_tool defined as in the earlier lessons)
messages = [{"role": "user", "content": "Is it warmer in Lima or Oslo?"}]
for step in range(5):
    reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=500,
                                   tools=tools, messages=messages)
    if reply.stop_reason != "tool_use":
        print(reply.content[0].text)
        break
    messages.append({"role": "assistant", "content": reply.content})
    results = []
    for block in reply.content:
        if block.type == "tool_use":
            results.append({"type": "tool_result", "tool_use_id": block.id,
                            "content": str(run_tool(block.name, block.input))})
    messages.append({"role": "user", "content": results})

In the real API, the model's tool request is saved as an assistant message, and your results go back in a user message as tool_result blocks with the matching id.

The pretend model is simpler: after a tool_use reply, you append one message {'role': 'tool', 'tool_use_id': reply['id'], 'content': str(result)} and ask again.

Many SDKs also offer helpers that run this loop for you. Writing it once yourself makes those helpers easy to understand.