ProjekinAja. Agentic AI Stage 4 · Building Agents Lesson 4.7
● Stage 4 · Lesson 4.7

A Real Working Agent — End to End

Now we assemble everything — the loop, the tools, the memory — into one complete, working agent you could actually run. This is the payoff of the whole course.

⏱ ~18 min read 🏗️ The capstone build 🐍 One full program

🎯 By the end you'll understand

How the pieces you built separately — the agent loop (4.4), tools (4.5), and memory (4.6) — fit together into one coherent Python program with a goal, a step budget, and a stop condition; how a single run flows from goal to result; and exactly how to run it yourself.

KEY INSIGHTThe one idea to take away

A working agent is not a framework you import. It's a system prompt, a few tools, a memory file, and a loop with a budget — about a hundred lines you can read top to bottom and fully understand.

For three lessons you've built the parts in isolation: the loop that keeps spinning (4.4), the tools that let it act (4.5), the memory that lets it remember across runs (4.6). This lesson does the one thing left: snaps them together into a single program that actually does a job.

We'll pick a concrete, useful little agent — a personal research assistant — give it three tools and a memory file, and walk the whole program from the first import to the final saved note. Then we'll trace one complete run, beat by beat, and show you how to run it on your own machine.

🔑 Hold onto this

Every part of this program maps to something you already learned. The system prompt is the goal + constraints (3.2). The tools are the hands (4.5). The memory load/save is persistence (4.6). The while loop with a step budget is the heartbeat with a stop condition (2.1, 2.9). Nothing new — just everything, at once.

PRACTICALThe mini-project: a personal research assistant

Abstract "agents" are forgettable. A concrete job sticks. So we'll build something small but genuinely useful: an agent you hand a topic, and it researches it and saves you a summary note — then remembers what it's looked into before.

To do that job, it needs exactly three tools — its hands on the world:

🔎

web_search(query)

Looks something up and returns findings. We'll stub it (return canned text) so the program runs offline with no extra keys — swapping in a real search API later is a one-function change.

🧮

calculator(expression)

Evaluates a small arithmetic expression. Handy when the topic involves numbers, and a clean example of a pure tool with no side effects.

📝

save_note(title, body)

Writes a note to disk — the agent's actual deliverable. This is a tool with a real side effect, which is exactly why we'll be careful with it.

And one more thing that isn't a tool: a memory file (4.6). At startup the agent reads what it already knows; at shutdown it writes back anything new. That's what makes it feel less like a script and more like an assistant that's met you before.

▸ The whole agent in one sentence

An LLM (the brain), pointed at a goal via its system prompt, given three tools and a memory file, run in a loop with a step budget. That's the formula from Lesson 1.1 — finally fully assembled.

FRAMEWORKThe four parts, assembled

Before the code, hold the map in your head. The program has four sections, in this order, and each one is a lesson you've already done:

SectionWhat it isFrom lesson
① Setup & system promptimports, the client, the model id, and the goal+constraints prompt3.2 · 4.4
② Toolsthe three Python functions + the schemas the model sees4.5
③ Memorytwo functions: load the memory file, save it back4.6
④ The main loopthe while loop: call model → dispatch tools → repeat, with a step budget2.1 · 2.9

We'll write them in exactly that order — because that's how the file reads top to bottom, and because each section depends only on the ones above it. Setup first, then the hands, then the memory, then the engine that uses all three.

💡 Read it as one program, in pieces

The four code blocks below are one file — agent.py — split at natural seams so we can talk about each part. Concatenate them in order and you have the complete, runnable program. The comments tag each piece back to its lesson.

CORE CONCEPT① Setup & the system prompt

The top of the file does three things: import what we need, create the client (which reads the API key from the environment — 4.4), and write the system prompt. The system prompt is where we hand the agent its goal and its constraints (3.2) — it's the single most important paragraph in the whole program.

agent.py · ① setuppython
import os
import json
import anthropic                              # the SDK (pip install anthropic) — 4.4

client = anthropic.Anthropic()               # reads ANTHROPIC_API_KEY from the env — never hardcode
MODEL = "claude-sonnet-5"                  # the brain (1.3) — id may change over time
MEMORY_FILE = "agent_memory.json"          # where persistent memory lives — 4.6
MAX_STEPS = 8                                # the STEP BUDGET — our stop condition (2.9)

# The system prompt = goal + constraints (3.2). This is what makes it OUR agent.
SYSTEM_PROMPT = """You are a careful personal research assistant.
Your goal: research the user's topic, then save ONE concise summary note.

Constraints:
- Use web_search to gather facts before you summarize. Don't invent sources.
- Use the calculator for any arithmetic; never do mental math.
- When the summary is ready, call save_note exactly once, then stop.
- Be concise. If you already know the topic from memory, say so and skip redundant searches.
"""

Notice how much work the prompt does. It states the goal ("research, then save one note"), the constraints ("search before summarizing," "calculator for math," "save exactly once, then stop"), and even a nod to memory ("if you already know it… skip"). A vague prompt makes a vague agent; a precise one makes a predictable one. MAX_STEPS sits right up top as a constant so the budget is impossible to miss.

CORE CONCEPT② The tools

Each tool is two halves (4.5): a plain Python function that does the work, and a schema — a JSON description — that tells the model the tool exists, what it's for, and what arguments it takes. The model only ever sees the schemas; your loop runs the functions.

agent.py · ② toolspython
# --- the functions that do the actual work ---

def web_search(query):
    # STUB: returns canned text so the program runs offline.
    # Swap in a real search API here later — same signature, real results.
    return (f"Search results for '{query}': sea otters use rocks as tools "
            "to crack open shellfish; they are a keystone species in kelp forests.")

def calculator(expression):
    try:
        # tiny, locked-down eval: digits and basic operators only
        if not all(ch in "0123456789+-*/.() " for ch in expression):
            return "Error: only basic arithmetic is allowed."
        return str(eval(expression, {"__builtins__": {}}))
    except Exception as e:
        return f"Error: {e}"          # tools should return errors, not crash the loop

def save_note(title, body):
    fname = title.lower().replace(" ", "_") + ".md"
    with open(fname, "w") as f:
        f.write(f"# {title}\n\n{body}\n")
    return f"Saved note to {fname}."

# a dispatch table: tool name -> function (used by the loop below)
TOOL_FUNCTIONS = {
    "web_search": lambda a: web_search(a["query"]),
    "calculator": lambda a: calculator(a["expression"]),
    "save_note": lambda a: save_note(a["title"], a["body"]),
}

# --- the schemas the MODEL sees (name + description + inputs) ---
TOOLS = [
    {"name": "web_search",
     "description": "Search the web for facts about a topic.",
     "input_schema": {"type": "object",
        "properties": {"query": {"type": "string"}}, "required": ["query"]}},
    {"name": "calculator",
     "description": "Evaluate a basic arithmetic expression like '12 * (3 + 4)'.",
     "input_schema": {"type": "object",
        "properties": {"expression": {"type": "string"}}, "required": ["expression"]}},
    {"name": "save_note",
     "description": "Save a summary note to disk. Call this once, at the end.",
     "input_schema": {"type": "object",
        "properties": {"title": {"type": "string"}, "body": {"type": "string"}},
        "required": ["title", "body"]}},
]

Two details earn their keep. First, calculator catches its own errors and returns them as text — a tool that raises an exception would kill the loop; a tool that returns "Error: …" lets the model read the problem and try again. Second, the TOOL_FUNCTIONS dispatch table maps each tool name to the function that runs it, so the loop can look up "the model asked for web_search" → "call this function" in one line. (We keep the eval deliberately locked down — a real calculator tool would use a safe parser, not bare eval.)

CORE CONCEPT③ Load & save memory

Memory (4.6) is just a file the agent reads at the start and writes at the end. Here it's a JSON file holding a list of topics the agent has already researched. Two small functions, no magic:

agent.py · ③ memorypython
def load_memory():
    if os.path.exists(MEMORY_FILE):
        with open(MEMORY_FILE) as f:
            return json.load(f)               # {"topics": [...]} from a previous run
    return {"topics": []}                     # first run: start empty

def save_memory(mem):
    with open(MEMORY_FILE, "w") as f:
        json.dump(mem, f, indent=2)         # persist across runs

At startup we load_memory() and fold what it returns into the conversation, so the model begins the run already knowing what it's seen before. At the end we add the new topic and save_memory() it back. That round trip — load in, work, save out — is the entire idea of persistence. The file is the long-term memory; the messages list (2.3) is only the short-term memory for this one run.

CORE CONCEPT④ The main loop — the heart of it

This is where it all comes together. The loop is the agent loop from 4.4 plus one new branch: when the model asks to use a tool, we dispatch it — run the function, feed the result back — and go again. Read the highlighted block as the beating heart of the program.

agent.py · ④ the agent looppython
def run_agent(goal):
    mem = load_memory()                                   # ③ pull in what we already know
    known = ", ".join(mem["topics"]) or "(nothing yet)"

    messages = [{"role": "user",
        "content": f"Previously researched: {known}.\nNew goal: {goal}"}]

    for step in range(MAX_STEPS):                       # the LOOP, bounded by the step budget (2.9)
        response = client.messages.create(             # call the model (the brain) with the tools
            model=MODEL, max_tokens=1024,
            system=SYSTEM_PROMPT, tools=TOOLS, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":         # no tool wanted -> the agent is DONE
            break

        results = []                                    # DISPATCH every tool the model asked for
        for block in response.content:
            if block.type == "tool_use":
                fn = TOOL_FUNCTIONS.get(block.name)
                out = fn(block.input) if fn else f"Unknown tool: {block.name}"
                results.append({"type": "tool_result",
                    "tool_use_id": block.id, "content": str(out)})
        messages.append({"role": "user", "content": results})   # observe -> loop again
    else:
        print("⚠️ Step budget exhausted — stopping to avoid a runaway loop.")

    # final text the model produced (the human-facing answer)
    for block in response.content:
        if block.type == "text":
            print("Agent:", block.text)

    # ③ save memory: record the topic so the next run remembers it
    if goal not in mem["topics"]:
        mem["topics"].append(goal)
        save_memory(mem)

if __name__ == "__main__":
    run_agent("sea otters and why they matter")

Walk the highlighted heart slowly, because this is the whole agent:

📖 Dispatch

To dispatch a tool call is to look at the tool the model requested by name, find the matching function in your code, run it with the model's arguments, and send the result back. The dispatch table (TOOL_FUNCTIONS) is what turns "the model said save_note" into "actually write the file."

SEE ITRun the whole agent

Here's the assembled agent doing its job on one goal: "research sea otters and save a summary note." Press ▶ Step to walk one full run — watch the active section of the program, the messages list growing, and the tool bubbles as the agent acts and observes. Or hit Run all to watch it play out.

🏗️ Interactive · One complete run, beat by beat

Goal: “research sea otters and save a summary note.”  ·  Step budget: 8

Ready

Press ▶ Step to begin. We'll run the agent on one goal, end to end.

Active section: —

messages list (this run)
(empty)
Beat 0 of 9

Notice the rhythm: load memory → think → act → observe → think → act → observe → answer → save memory. The model never touches a file directly; it only ever asks for a tool, and your loop does the rest. And the step budget sits over the whole thing like a guardrail — if the model got stuck calling tools forever, the loop would still halt at step 8.

PRACTICALHow to actually run it

This isn't a thought experiment — paste the four sections into one agent.py and it runs. Three commands stand between you and a working agent on your own machine:

terminalshell
# 1. install the SDK
pip install anthropic

# 2. set your API key as an environment variable (never in the code — 4.4 / 4.10)
export ANTHROPIC_API_KEY="sk-...your-key..."

# 3. run it
python agent.py

What you'll see: the agent searches (the stub returns its canned otter facts), maybe runs a calculation, prints a short summary, and writes a file like sea_otters_summary.md to the folder. Run it a second time and check agent_memory.json — the topic is now remembered, and the agent will tell you it's seen this one before. That's the full loop, tools, and memory, working together on your laptop.

💡 Make it real in one edit

The only thing standing between this and a genuinely useful tool is the web_search stub. Replace its body with a call to a real search API (keeping the same def web_search(query) signature), and the rest of the program doesn't change at all. That's the payoff of clean tool boundaries.

FRAMEWORKWhere to go from here

You now have a real agent. It's simple on purpose — every line is readable — but "simple" leaves obvious next steps. Here's the upgrade path, each one a small, contained change:

🛡️

Error handling around tools

Wrap every dispatch in try/except so a single failing tool returns an error string instead of crashing the run. We did this inside calculator; do it for all of them.

🧰

More (and better) tools

A real web_search, a read_file, a send_email — each is just another function plus a schema in the same two lists. The loop never changes.

🧠

Better memory

Store summaries, not just topic names; let the agent search its own past notes. The JSON file becomes a small knowledge base (4.6).

🚧

Guardrails & evals

Confirm before a side-effect tool runs; measure whether the agent actually does its job. That's the focus of 4.9 (testing & evals) and 4.10 (security & deployment).

⚠️ This is a real agent — but not a production one

Be honest about what you built. It works, and it teaches every core idea. But it has no retries, no logging, a fake search tool, and an eval-based calculator you would never ship. A production agent adds reliability (retries, timeouts), evaluation (4.9), and security (4.10) on top of this same skeleton. The skeleton is correct; production is the skeleton hardened. Don't confuse the two.

WEAKNESSCommon mistakes to avoid

✗ No stop condition or step budget

A while True loop with no exit is a money fire in an agent — if the model keeps asking for tools, you keep paying for model calls forever. Always bound the loop: for step in range(MAX_STEPS), a turn cap, or a goal-reached check (2.9). The budget is not optional polish; it's a safety belt.

✗ No error handling around tools

If a tool raises an exception, it crashes the whole loop mid-run — and the model never gets a chance to recover. Tools should catch their own errors and return them as text (like our calculator does), so the model can read the failure and adapt instead of the program dying.

✗ Treating the simple agent as production-ready

It runs, so it's tempting to ship it. Don't. A stubbed search tool, a bare eval, no retries, no logging, no confirmation before save_note writes to disk — these are fine for learning and dangerous in production. Treat this as the correct foundation, then add reliability, evals (4.9), and guardrails (4.10) before it touches anything that matters.

KEY INSIGHTWhere this connects in your course

  • The agent loop (4.4) — the for loop here is the chat loop you built, with one new branch for tools.
  • Tools (4.5) — the three functions + schemas + the dispatch table are exactly the pattern from that lesson, now in service of a real goal.
  • Memory (4.6) — load_memory() / save_memory() bookend the run so the agent persists across sessions.
  • The agent formula (1.1) — LLM + tools + loop, pointed at a goal: this lesson is that sentence, fully assembled and running.
  • Stop conditions (2.9) — MAX_STEPS and the for…else are the step budget that keeps the loop from running away.
  • Evals (4.9) & security/deployment (4.10) — next: how you make this skeleton reliable, tested, and safe to ship.

This is the summit of Stage 4's "build it yourself" arc. You no longer use agents from the outside — you've written one from import to saved file, and you understand every line of it. The rest of the course makes it trustworthy.

GLOSSARYKey terms introduced

Capstone
The integrating build that assembles previously separate pieces — loop, tools, memory — into one coherent, working whole.
Main loop
The core for/while cycle of an agent: call the model, dispatch any tools it asks for, feed results back, repeat — until done or out of budget.
Dispatch
Looking up the function that matches a tool the model requested (via a name→function table), running it with the model's arguments, and returning the result.
Stop condition / step budget
The rule that ends the loop: a goal-reached check, a quit signal, or a cap on the number of steps (MAX_STEPS) that prevents a runaway, money-burning loop (2.9).
System prompt
The instruction that hands the agent its goal and constraints at the top of every model call — what makes a generic LLM into your specific agent (3.2).
Runnable program
A complete, self-contained file you can actually execute — here, agent.py plus an API key and pip install anthropic.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1What are the four sections of the assembled agent program, and which lesson does each come from?›

① Setup & system prompt (goal + constraints, 3.2 / 4.4), ② Tools (functions + schemas + dispatch table, 4.5), ③ Memory (load/save a file, 4.6), and ④ The main loop (call model → dispatch tools → repeat, with a step budget, 2.1 / 2.9). Concatenated in order, they form one runnable agent.py.

2What two things end the main loop, and why does a step budget matter?›

It ends when (a) the model replies with plain text instead of a tool request (stop_reason != "tool_use" → break) — the agent is done — or (b) the loop hits MAX_STEPS. The budget matters because without it, a model that keeps requesting tools would spin forever, burning tokens and money on every call. The budget is a hard safety belt.

3How does the loop turn "the model asked for save_note" into an actual saved file?›

By dispatch: it reads the tool_use block, looks the tool name up in the TOOL_FUNCTIONS table to find the matching Python function, calls it with the model's arguments, and appends the return value as a tool_result turn so the model can observe the outcome. The model only ever requests a tool; the loop runs it.

4Why is this a "real but simple" agent — what separates it from a production one?›

It genuinely works and teaches every core idea, but it has a stubbed search tool, a bare-eval calculator, no retries or logging, and no confirmation before it writes to disk. A production agent adds reliability (retries, timeouts), evaluation (4.9), and security/guardrails (4.10) on top of this same skeleton. The foundation is correct; production is that foundation hardened.

You built a whole agent. Next: more than one of them →