Lesson 3 / 25

Build the Loop from Scratch

Write a minimal agent loop with the Anthropic Python SDK and a step limit.

Fifty lines, no framework

The core of every framework is a loop: call the model, if it asked for tools run them and append the results, repeat until it answers in plain text. Writing it once yourself shows you exactly what frameworks automate.

A minimal agent loop

TOOLS is the schema list and run_tool dispatches to your Python functions. The range(10) cap prevents an endless loop. Use the current model ID from your provider's docs.

import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Weather in Pune?"}]

for _ in range(10):                      # step limit
    resp = client.messages.create(
        model="claude-sonnet-5-5", max_tokens=1024,
        tools=TOOLS, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":
        break                            # final answer
    results = [
        {"type": "tool_result", "tool_use_id": b.id,
         "content": run_tool(b.name, b.input)}
        for b in resp.content if b.type == "tool_use"
    ]
    messages.append({"role": "user", "content": results})

print(resp.content[0].text)

Always keep a cap

Without a step limit, a confused model can call tools forever. Add limits for steps, time and money from the very first version.

Quick check: When does the loop in the example stop on success?

  • When stop_reason is not "tool_use"
  • After exactly one call
  • Never
  • When the user closes the tab
Answer

When stop_reason is not "tool_use" — A reply that is not a tool request is the model's final answer.