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.
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.
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.
Step 2: the manual loop
Each response carries a stop_reason that says why the model stopped writing:
stop_reason | Meaning | What your loop does |
|---|---|---|
end_turn | Finished its answer | Stop and show it |
tool_use | Wants one or more tools | Run them, send results, call again |
max_tokens | Hit your max_tokens cap | Cut off; raise the cap or continue |
refusal | Declined the request | Stop and handle it |
pause_turn | Paused partway through a turn | Check 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.
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:
The conversation starts with one user message.
Three rules are easy to get wrong:
- Append the assistant turn first. The model's response, tool calls included, goes into
messagesbefore your results. The API checks that everytool_resultanswers atool_usein the turn before it. - All results go in one user message. If the model asked for three tools, send back three
tool_resultblocks together in a single"role": "user"message. - Never drop a failed tool. If a tool crashes, still return a
tool_resultfor it, with"is_error": Trueand a useful message. The model can read the error and try something else.
Request 1: the user's question and the tool list.
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.
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".
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"])Put the messages of a one-tool conversation in the order they appear in messages.
- Tap the steps below in the right order.
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.
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_errorwith 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] ")beforerun_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.usagereports 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
refusalandmax_tokensbefore reading content, so a cut-off answer is not treated as a finished one.
read_file tool raises FileNotFoundError. What should your loop send back?Match each piece of the API to its job.
- 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.