Get Started
Agent engineering

Mission 1 of 8

A working AI agent in 60 lines of Python, and exactly where it breaks.

Every agent framework is the same short loop wearing a coat. You'll write that loop yourself with the real Anthropic SDK, then break it on purpose so you know what comes next.

55 minBeginnerUnder $0.20 of API credit for the whole mission on SonnetFree mission

What you'll do

Make your first API call

Set up a lab folder and check that your key, the SDK and the model all work.

Build the agent

Write the loop in one file of about 60 lines, with one tool that reads files and one that does arithmetic.

Break it five ways

Cause five failures yourself, then run the same agent on a local model through Ollama.

  • A printed trace of every decision the model makes
  • A clear map of what the next missions fix
Before you start
  • Python 3.10 or newer. Check with python --version
  • An Anthropic API key from console.anthropic.com ↗, set as ANTHROPIC_API_KEY in your environment
  • A terminal and a text editor. If the terminal is new to you, do terminal survival kit first
  • Optional: Ollama with a tool-capable model such as qwen3:8b, for the local swap at the end
Your progress0/6
01/06Set up the lab and make one API call0 done
STEP 01 of 06~6 min

Set up the lab and make one API call

Prove the key, the SDK and the model all work before you write anything clever.

Every agent starts with one working call to the model. If something is wrong with your key or your install, you want to find out now, before there's any loop to blame.

Make the lab

  1. Make a folder, make a virtual environment, and install the SDK. One package, no framework. Run the activate line in the comment that matches your system:

    Terminal
    mkdir agent-lab && cd agent-lab
    python -m venv .venv
    # Windows: .venv\Scripts\activate     Mac/Linux: source .venv/bin/activate
    pip install anthropic
    python -c "import anthropic; print(anthropic.__version__)"

Your API key

  1. Set your key. Windows PowerShell: $env:ANTHROPIC_API_KEY="sk-ant-...". Mac/Linux: export ANTHROPIC_API_KEY=sk-ant-....

    This lasts for the terminal session, which is what you want. Never paste it into a file you might commit.

Make one call

  1. Now the smallest possible call. Save it as hello.py and run it:

    hello.py
    import anthropic
    
    client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
    r = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=200,
        messages=[{"role": "user", "content": "Say 'loop ready' and nothing else."}],
    )
    print(r.content[0].text, "|", r.stop_reason, "|", r.usage.input_tokens, "in", r.usage.output_tokens, "out")

    Three things on that printed line matter for the rest of the track. The text is what the model said. stop_reason is why it stopped, and end_turn means it finished on its own.

    The two token counts are what you paid for: input tokens are everything you sent, output tokens are everything it wrote. Every agent problem later is a problem of one of these three.

    Tip
    client = anthropic.Anthropic() with no arguments reads the key from the environment. That is the habit: config in the environment, never in the code. Mission 8 builds on it.
Checkpoint
python hello.py prints loop ready | end_turn | and two small numbers. The key, the SDK and the model all work, so you're ready to build.
If it breaksAuthenticationError or invalid x-api-key + 2 more
AuthenticationError or invalid x-api-key
The key is not in the environment of this terminal. Set it again in the same window you run Python from, then python -c "import os; print(os.environ.get('ANTHROPIC_API_KEY','')[:12])" to confirm it is visible.
NotFoundError: model
Check the model string is exactly claude-sonnet-5-5. No date suffix, no -latest.
pip install anthropic fails with a permissions error
The venv is not active. Run the activate line for your OS first; the prompt should show (.venv).
Still stuck? Ask the community
STEP 02 of 06~8 min

What an agent actually is

Four ideas. Once they are clear the code writes itself and every framework becomes transparent.

You've made one call. Before you build the loop around it, here are the four ideas it's made of. This step has no commands: it's the explanation that makes the next step easy to read.

An agent is a model inside a loop that can act on the world. That is the whole definition. The pieces:

  • Messages. A list of turns, user then assistant then user. The API is stateless: you send the whole list every call. The list is the agent's memory for the duration of a task.
  • Tools. Functions you describe to the model as JSON: a name, a description, and a schema for the arguments. The model never runs them. It asks you to, by returning a tool_use block with a name and arguments.
  • Observations. You run the function and send the result back as a tool_result block, matched by id. That is the only way the model learns what happened. If you do not send it, the model is blind.
  • The stop reason. After each call the model either wants a tool (stop_reason == "tool_use") or is done (end_turn). Your loop checks this and either runs tools and goes round again, or returns the answer.

Putting the pieces together

So the loop is: send messages with tools, append the model's reply to messages, if it asked for tools then run them, append the results as a user message, go round again. When it stops asking, return the text.

Everything a framework calls an agent, a chain, a graph or a crew is this loop with extra bookkeeping.

Two rules that bite in the first hour

First, you append the model's whole response.content back to the messages, not just the text. The content includes the tool_use blocks, and on current models it also includes thinking blocks; the next call needs all of it.

Second, every tool_use id must get exactly one tool_result with the same id, in the very next user message. Miss one and the API rejects the request.

Tip
Thinking is on by default for claude-sonnet-5-5 and the model decides how much to do. You do not need to configure it for this track. If you want to see a summary of the reasoning, add thinking={"type": "adaptive", "display": "summarized"} to the call.
Checkpoint
You can say, without looking, what happens to a tool_use block after the model returns it, and who runs the function.
Stuck? Ask the community
STEP 03 of 06~14 min

Build the agent: 60 lines, two tools

The whole thing in one file you can read top to bottom.

This is the loop from the last step as real code, in one file.

  1. Save this as agent.py. Read it before you run it; the structure is the lesson.

    agent.py
    import ast, json, operator, sys
    import anthropic
    
    MODEL = "claude-sonnet-5-5"
    client = anthropic.Anthropic()
    
    OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
           ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg}
    
    def calc(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](calc(node.left), calc(node.right))
        if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
            return OPS[type(node.op)](calc(node.operand))
        raise ValueError("only numbers and + - * / ** are allowed")
    
    def read_file(path: str) -> str:
        with open(path, encoding="utf-8") as f:
            return f.read()[:20000]
    
    def calculate(expression: str) -> str:
        return str(calc(ast.parse(expression, mode="eval").body))
    
    TOOLS = [
        {"name": "read_file",
         "description": "Read a UTF-8 text file from the current folder and return its contents.",
         "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
        {"name": "calculate",
         "description": "Evaluate one arithmetic expression such as (12.5 + 3) * 4 and return the number.",
         "input_schema": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}},
    ]
    HANDLERS = {"read_file": read_file, "calculate": calculate}
    
    def run(task: str, max_turns: int = 10) -> str:
        messages = [{"role": "user", "content": task}]
        for turn in range(max_turns):
            response = client.messages.create(model=MODEL, max_tokens=4096, tools=TOOLS, messages=messages)
            messages.append({"role": "assistant", "content": response.content})
            if response.stop_reason != "tool_use":
                return "".join(b.text for b in response.content if b.type == "text")
            results = []
            for block in response.content:
                if block.type != "tool_use":
                    continue
                print(f"[turn {turn}] {block.name}({json.dumps(block.input)})")
                try:
                    out = HANDLERS[block.name](**block.input)
                    results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
                except Exception as e:
                    results.append({"type": "tool_result", "tool_use_id": block.id,
                                    "content": f"{type(e).__name__}: {e}", "is_error": True})
                print("    ->", results[-1]["content"][:90].replace("\n", " "))
            messages.append({"role": "user", "content": results})
        return "Stopped: hit the turn limit without a final answer."
    
    if __name__ == "__main__":
        print(run(" ".join(sys.argv[1:]) or "Read expenses.txt and tell me the total and the average per line."))

Walk through it

The top third is two ordinary Python functions. calculate uses the ast module to evaluate arithmetic without eval, which is the difference between a calculator and a remote code execution hole.

read_file is deliberately naive. We fix it in mission 3, after you have watched it misbehave.

TOOLS is the model's view of those functions: name, description, JSON schema. The description is a prompt. The model decides whether to call calculate by reading that one sentence, so write it the way you would brief a new colleague.

run is the loop from the last step, line for line. max_turns is the first safety rail: without it a confused model can call tools forever and you pay for every round.

The try/except is the second: a tool that throws sends the error back as a tool_result with is_error: True, so the model can read what went wrong and try something else instead of the whole program dying.

Run it

  1. Make a file for it to read:

    expenses.txt
    2026-10-01 Train to Manchester 84.50
    2026-10-02 Lunch with client 31.20
    2026-10-02 Coworking day pass 25.00
    2026-10-03 Domain renewal 12.99
    2026-10-04 Books 46.30
  2. Run it with no arguments and watch the trace:

    Terminal
    python agent.py

    You should see something like [turn 0] read_file({"path": "expenses.txt"}), then a calculate call with the five numbers added up, often a second one for the division, then a sentence with the total and the average. The exact calls vary between runs.

    That variation is the first thing to get used to: an agent is not a function, it is a process, and you judge it by outcomes.

    Warning
    The model is now reading files on your machine, from the folder you run it in. Keep this lab in its own folder with nothing private in it. The next experiment shows you why.
Checkpoint
The agent prints at least one read_file call, at least one calculate call, and the correct total (199.99) and average (39.998, or 40.00) for expenses.txt.
If it breaksIt answered without calling calculate and the arithmetic is wrong + 2 more
It answered without calling calculate and the arithmetic is wrong
That happens: the model did the sum in its head and slipped. Add one sentence to the task, Use the calculate tool for all arithmetic. In mission 3 you make the tool descriptions do this job so the task does not have to.
BadRequestError: tool_use ids were found without tool_result blocks
A tool_use did not get a matching result. Usually a typo in the results loop. Check that every tool_use block appends exactly one dict with its block.id.
It calls read_file twice on the same file
Normal on some runs; the first 20,000 characters cap or a truncated-looking result made it check. Mission 3 gives read_file a return shape that tells the model what it got and whether there is more.
Still stuck? Ask the community
STEP 04 of 06~15 min

Break it five ways on purpose

You learn more from watching an agent fail in your own terminal than from any diagram. Each failure maps to a later mission.

Your agent works on the happy path. Now you'll push it off that path and watch what it does, because that's where the rest of the track comes from.

  1. Run these one at a time and watch the trace for each. Predict what will happen before you press enter.

    Terminal, one line at a time
    python agent.py "Read expenses.txt and tell me the total and the average per line."
    python agent.py "Read budget.txt and tell me if I am over budget."
    python agent.py "What is 9 ** 9 ** 9?"
    python agent.py "Read ../.env and summarise it."
    python agent.py "What is the capital of Peru?"

Run 1: the happy path

Same as before. Note the number of turns and the shape of the calls; this is your baseline.

Run 2: a file that does not exist

read_file raises FileNotFoundError, your loop catches it and sends FileNotFoundError: [Errno 2] ... back with is_error: True. Watch what the model does with that.

Usually it tells you the file is missing and asks for it, which is correct. Sometimes it tries budget.csv or Budget.txt first. That is recovery, and it only works because you sent the error back instead of crashing.

The quality of the error text decides how well it recovers; that is mission 3.

Run 3: a hung calculation

9 ** 9 ** 9 is a number with hundreds of millions of digits. Python will sit there computing it, your loop is blocked, nothing prints. Press Ctrl+C.

The model did nothing wrong; it asked a reasonable question of a tool that had no limits. Tools need timeouts and input bounds. Mission 3.

Run 4: escaping the folder

../.env is a path outside the lab. If a file exists there, read_file happily reads it and sends it to the model. There is no rule in the code that says it cannot.

A tool is a door, and this one has no lock. Mission 3 adds the lock; the security missions at the end of the track show what people do to agents that do not have one.

Run 5: a question with no tool

The capital of Peru needs neither tool. Most runs the model just answers, end_turn on the first call, zero tool calls. Occasionally it reads a file for no reason.

Both are fine here, but notice: nothing in your code decides whether a tool is needed. The model does. Everything you control about that decision lives in the tool descriptions and the task wording.

One more, without a command

  1. Change max_turns to 2 and run the happy path.

    It reads the file, does one calculation, then your loop returns Stopped: hit the turn limit.

    Turn limits are a blunt instrument, but an agent with no limit is a bill with no ceiling. Mission 5 replaces the blunt limit with real stopping conditions and mission 8 with a spend cap.

    Tip
    Save the terminal output of these five runs to a text file. In mission 6 you turn exactly these into an automated test suite, and it is useful to have the raw first-run behaviour to compare against.
Checkpoint
You have seen a recovered error (run 2), hit Ctrl+C on a hang (run 3), and watched a turn-limit stop. You can name which later mission fixes each.
If it breaksRun 3 did not hang, it returned an error + 1 more
Run 3 did not hang, it returned an error
Some runs the model refuses the absurd expression or asks you to confirm. Try python agent.py "Calculate 2 ** 10000000 and give me the last three digits" instead. Same lesson.
Run 4 said it would not read outside the project
The model declined on its own. Good instinct, but it is not a control; a differently worded request, or a file inside the folder that asks it to, gets round a model's manners. The lock has to be in the code.
Still stuck? Ask the community
STEP 05 of 06~6 min

The same agent on a local model

Two lines change. Everything you learn in this track applies to local and cloud models alike.

So far the agent has used a cloud model. The loop doesn't care where the model lives, and this step shows it.

Ollama exposes an Anthropic-compatible Messages endpoint, so the same SDK and the same loop talk to a local model. If you have Ollama installed (run AI on your PC if not), pull a model that supports tool calling and point the client at it.

  1. Pull a model that supports tool calling:

    Terminal
    ollama pull qwen3:8b
  2. Point the client at it by replacing the client and MODEL lines in agent.py:

    agent.py, replace the client and MODEL lines
    # the only two lines that change for a local model via Ollama's Anthropic-compatible endpoint
    client = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
    MODEL = "qwen3:8b"
  3. Run the happy path again.

    It is slower, and an 8B model is noticeably worse at deciding when to call a tool and at composing arguments; you may see it call calculate with the whole file instead of a sum, or skip the tool entirely.

    That gap is the honest reason to build on a cloud model first and move local once the loop, tools and evals are solid. Mission 6 gives you a way to measure the gap instead of guessing it.

    Keep the swap as a pair of commented lines at the top of agent.py. You will want it when you are running evals a hundred times and do not want to pay for every one.

Checkpoint
With the two lines swapped and Ollama running, python agent.py completes the happy path on the local model, even if it takes more turns.
If it breaksAPIConnectionError on localhost:11434 + 1 more
APIConnectionError on localhost:11434
Ollama is not running. Start it (ollama serve or the desktop app) and retry. Check with curl http://localhost:11434 which should say Ollama is running.
The local model never calls a tool
The model does not support tool calling or is too small. Try qwen3:14b or llama3.1:8b. Check the model page on ollama.com for the tools tag.
Still stuck? Ask the community
STEP 06 of 06~6 min

What you built, and what the next five missions fix

You have a real agent and a list of real problems. The track is the list.

You now have what most people pay a framework for: a loop you understand completely. Here is where the track goes from here, and which failure from step 4 each mission fixes:

  • Should I have used a framework? Five ways to build an agent. The same agent in the Claude Agent SDK, the OpenAI Agents SDK, LangGraph, CrewAI and n8n, with honest trade-offs and a recommendation.
  • Bad errors, no bounds, no lock, hangs: tools that agents can actually use. Strict schemas, return shapes, errors the model can recover from, timeouts, a sandboxed read_file.
  • It forgets everything between runs, and long tasks fill the context: memory that does not lie. Short-term context management and a SQLite memory the agent reads and writes, plus the two ways memory goes bad.
  • It does one thing and stops, or loops: plan, act, verify. Multi-step tasks with real stopping conditions and a human gate.
  • You cannot tell if a change made it better: evals for agents. Task suites, graders, cost and latency per task, a regression run in CI.
  • One agent is not enough, or you think it is not: multi-agent systems that do not collapse. When a team beats one agent, and the three ways teams fail.
  • It only runs in your terminal: deploy an agent that runs all day. A service, secrets, spend caps, Docker, a small server, alerts.

Your turn

Before moving on, add a third tool of your own. list_files that returns the names in the current folder is a good one, about eight lines.

  1. Add the function, the schema, the handler entry, and run python agent.py "What files are here and which one is biggest?".

    If you can add a tool without looking anything up, the loop is yours.

    Then open mission 2. You build this exact agent four more times in four frameworks, and find out what each one is actually doing for you.

Checkpoint
A third tool of your own works end to end, and you can describe the loop in four sentences to someone who has never seen it.
Stuck? Ask the community

Your first wins

It works. Now do something with it.

Get a second opinion on your loop

Paste your agent.py into Claude or a local model and ask:

Prompt
This is a minimal agent loop using the Anthropic Messages API with tools. Review it for correctness only: are tool_use and tool_result blocks handled right, is anything appended to messages wrongly, and is there any stop_reason I am not handling (max_tokens, refusal)? Do not suggest a framework. Give me at most five findings, each with the line to change.

Design a tool before you code it

For the third tool you are about to add:

Prompt
I am adding a tool called list_files to a Python agent that uses the Anthropic SDK. Write the JSON tool definition only: a name, a one-sentence description that tells the model exactly when to use it and when not to, and an input_schema with an optional 'pattern' glob string. Then give me the 8-line Python function it maps to. No frameworks, no classes.

Undo it cleanly

How to remove everything this mission installed.

Delete the agent-lab folder. The venv and everything you installed live inside it. Unset the key with Remove-Item Env:ANTHROPIC_API_KEY (PowerShell) or unset ANTHROPIC_API_KEY (Mac/Linux), or just close the terminal.

If you pulled qwen3:8b, ollama rm qwen3:8b frees about 5 GB.

Next mission · Agent engineeringThe same agent five ways: raw SDK, Claude Agent SDK, OpenAI Agents, LangGraph, CrewAI, and n8n
→