Skip to content

Lesson 14 of 40Agents

Build an Agent

Write a working agent with the Claude API in Python, first with a manual tool loop, then with the SDK tool runner, and add guardrails.

18 min read0/5 questions

In the last lesson you saw an agent loop with a fake model. Now you will write the real one against the Claude API. It is shorter than you might expect: one tool definition, one while loop, and a few rules about how tool calls and results are shaped. Once you can write this loop by hand, every agent product (Claude Code included) stops being magic, and you can debug them when they misbehave. You will also see the SDK helper that writes the loop for you, and the guardrails every real agent needs.

Setup

You need Python 3, the official SDK, and an API key from your Anthropic account (the official docs show where to create one).

pip install anthropicexport ANTHROPIC_API_KEY="sk-ant-..."

The client reads the key from the ANTHROPIC_API_KEY environment variable, so it never needs to appear in your code. Never commit a key to git.

Everything goes through one endpoint, the Messages API. The API is stateless: it remembers nothing between requests, so you send the whole conversation every time. In an agent, "the conversation" grows with every tool call and every result.

The examples use claude-opus-5-5. Model names change over time, so check the docs for the current list.

Step 1: describe a tool

A tool definition is a dictionary with three keys. The name is what the model will call. The description tells the model what the tool does and when to use it. The input_schema is a JSON Schema describing the inputs.

agent.py
import anthropic
 
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
 
tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string", "description": "City name, e.g. Paris"}},
        "required": ["city"],
    },
}]
 
def run_tool(name, tool_input):
    if name == "get_weather":
        return f"18°C and cloudy in {tool_input['city']}"  # a real app would call a weather API
    raise ValueError(f"unknown tool {name}")

The model never sees run_tool. It sees only the name, description and schema. Your Python function is the part that does the work. Write the description as if for a new teammate: what it returns, and when to use it. A vague description is the most common reason a model picks the wrong tool or skips a useful one.

Quick check
Which parts of a tool does the model actually read?
Need a nudge? A hint rules out a wrong answer.

Step 2: the manual loop

Each response carries a stop_reason that says why the model stopped writing:

stop_reasonMeaningWhat your loop does
end_turnFinished its answerStop and show it
tool_useWants one or more toolsRun them, send results, call again
max_tokensHit your max_tokens capCut off; raise the cap or continue
refusalDeclined the requestStop and handle it
pause_turnPaused partway through a turnCheck the docs for how to resume

When the stop reason is tool_use, response.content is a list of blocks. Some are text (the model explaining itself), and some are tool_use blocks, each with an id, a name and an input. You run each tool and answer with a tool_result block whose tool_use_id matches the request's id. That id is how the model knows which result belongs to which call when it asks for several at once.

agent.py (continued)
user_input = "Should I bring a jacket in Paris?"
messages = [{"role": "user", "content": user_input}]
 
while True:
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages,
    )
    if response.stop_reason == "end_turn":
        break
    messages.append({"role": "assistant", "content": response.content})
    results = []
    for block in response.content:
        if block.type == "tool_use":
            output = run_tool(block.name, block.input)  # your code
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
    messages.append({"role": "user", "content": results})
 
for block in response.content:
    if block.type == "text":
        print(block.text)

After one tool round, the messages list you send on the second request looks like this:

messages, on request 2
  1. user: "Should I bring a jacket in Paris?"the original question
  2. assistant: text + tool_use (id toolu_01)response.content, appended as-is
  3. user: tool_result (tool_use_id toolu_01)your code's output

The conversation starts with one user message.

1/4

Three rules are easy to get wrong:

  1. Append the assistant turn first. The model's response, tool calls included, goes into messages before your results. The API checks that every tool_result answers a tool_use in the turn before it.
  2. All results go in one user message. If the model asked for three tools, send back three tool_result blocks together in a single "role": "user" message.
  3. Never drop a failed tool. If a tool crashes, still return a tool_result for it, with "is_error": True and a useful message. The model can read the error and try something else.
Two requests, one tool
Your codeClaude APIget_weathermessages + toolsstop_reason: tool_userun_tool(...)18°C and cloudy+ tool_result toolu_01stop_reason: end_turn

Request 1: the user's question and the tool list.

1/6

Simulate it

The block below runs the exact loop shape above, but fake_create stands in for client.messages.create and returns API-shaped objects. On the first turn the "model" asks for two tools at once, and one of them has a typo in the city. Watch the error come back with is_error, and the model correct itself on the next turn.

Python
from types import SimpleNamespace as NSimport json # --- The tools: real Python functions ---def get_weather(city): data = {"Paris": "18C and cloudy", "Cairo": "31C and sunny"} if city not in data: raise ValueError(f"unknown city {city!r}; try Paris or Cairo") return data[city] TOOLS = {"get_weather": get_weather} def run_tool(name, tool_input): return TOOLS[name](**tool_input) # --- A fake client.messages.create: returns API-shaped responses ---calls = 0def fake_create(messages): global calls calls += 1 last = messages[-1]["content"] if isinstance(last, str): # first turn: ask for two tools at once return NS(stop_reason="tool_use", content=[ NS(type="text", text="I'll check both cities."), NS(type="tool_use", id="toolu_01", name="get_weather", input={"city": "Paris"}), NS(type="tool_use", id="toolu_02", name="get_weather", input={"city": "Pariss"}), ]) errors = [r for r in last if r.get("is_error")] if errors: # read the error message and retry with a fixed input return NS(stop_reason="tool_use", content=[ NS(type="tool_use", id="toolu_03", name="get_weather", input={"city": "Cairo"}), ]) return NS(stop_reason="end_turn", content=[ NS(type="text", text="Paris needs a jacket; Cairo does not."), ]) # --- The manual loop, same shape as the real API code ---messages = [{"role": "user", "content": "Jacket for Paris or Cairo?"}]MAX_TURNS = 5for turn in range(MAX_TURNS): response = fake_create(messages) if response.stop_reason == "end_turn": break messages.append({"role": "assistant", "content": response.content}) results = [] for block in response.content: if block.type == "tool_use": try: output = run_tool(block.name, block.input) results.append({"type": "tool_result", "tool_use_id": block.id, "content": output}) except Exception as e: results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(e), "is_error": True}) print(f"turn {turn + 1}:", json.dumps(results)) messages.append({"role": "user", "content": results})else: print("stopped: hit MAX_TURNS") print("final:", response.content[0].text)print("API calls:", calls)
Output
Press Run (⌘ Enter) to see what happens.

Two upgrades over the bare loop are already in there: the try/except that turns a crash into an is_error result, and a for with MAX_TURNS instead of while True. Python's for ... else runs the else only if the loop finished without break, which is exactly "we ran out of turns".

Predict the outputPython

What does this print?

results = []
for block_id in ["toolu_01", "toolu_02"]:
  results.append({"type": "tool_result", "tool_use_id": block_id})
print(len(results), results[1]["tool_use_id"])
Need a nudge? Hints walk you through it.
Put it in order4 steps

Put the messages of a one-tool conversation in the order they appear in messages.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Step 3: let the SDK run the loop

Writing the loop by hand teaches you how it works. In real code you can let the SDK's tool runner (a beta helper) do it. You write ordinary Python functions, decorate them with @beta_tool, and the SDK builds the tool definition from the function's name, type hints and docstring. Then it runs the loop: call the model, run tools, send results, repeat until done.

runner.py
import anthropic
from anthropic import beta_tool
 
client = anthropic.Anthropic()
 
@beta_tool
def get_weather(city: str) -> str:
    """Get the current weather for a city.
 
    Args:
        city: City name, e.g. Paris.
    """
    return f"18°C and cloudy in {city}"
 
runner = client.beta.messages.tool_runner(
    model="claude-opus-5-5",
    max_tokens=16000,
    tools=[get_weather],
    messages=[{"role": "user", "content": "Should I bring a jacket in Paris?"}],
)
for message in runner:
    print(message)

Each item the runner yields is one model response, so you can watch, log or stop the loop as it goes. The docstring now does the job of the description, so write it with the same care. Because it is a beta helper, its details may change; check the SDK docs for the current options.

When should you use which? The tool runner is the default for simple agents. Write the loop yourself when you need full control: custom approval steps, unusual logging, or tools that run somewhere other than this Python process.

Guardrails

A demo agent is ten lines. A safe one adds limits around the loop:

  • Max turns. Never ship while True. Cap the number of model calls, and treat hitting the cap as a failure you log.
  • Error results, not crashes. Wrap every tool. Return is_error with a message that says what went wrong and what would work. "unknown city 'Pariss'; try Paris or Cairo" lets the model recover. A bare stack trace usually does not.
  • Approvals for risky tools. Before running anything that deletes, pays, sends or deploys, ask a human. In the manual loop that is a simple input("Run delete_file? [y/N] ") before run_tool. Claude Code's permission prompts are this guardrail.
  • Least privilege. Only give the tools the task needs. A tool that reads one folder is safer than one that runs any shell command.
  • Validate inputs. The schema helps, but your tool should still check paths, ranges and sizes. The model can be wrong, and so can text injected into its context.
  • Budget and logs. response.usage reports input and output tokens on every call. Add them up, stop past a limit, and log every tool call with its inputs so you can see what happened.
  • Handle the other stop reasons. Check for refusal and max_tokens before reading content, so a cut-off answer is not treated as a finished one.
Quick check
Your read_file tool raises FileNotFoundError. What should your loop send back?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match each piece of the API to its job.

Choose an item, then its match on the other side.
Key terms
Messages API
The single Claude API endpoint for sending a conversation and getting the model's next turn.
stop_reason
A field on each response saying why the model stopped: end_turn, tool_use, max_tokens, refusal or pause_turn.
tool_use block
A content block in the model's response that names a tool, gives inputs, and carries an id.
tool_result
A block you send back with the tool's output, linked to the request by tool_use_id.
tool runner
A beta SDK helper that builds tools from decorated functions and runs the agent loop for you.
guardrail
A limit around the loop, such as a turn cap, an approval step, input checks or a token budget.
Claude Agent SDK
A library that packages Claude Code's full harness so you can run it from your own code.