Module 7: Project — Build a Mini Coding Agent

Module 7: Project — Build a Mini Coding Agent

Description

Modules 1-6 gave you the theory: how LLMs work, what an agent is, the agentic loop, tools, how to direct the agent, and the R→P→E→V workflow. This module is where it all converges in practice: you're going to build a coding agent from scratch.

It's not a production agent. It's an educational agent — ~200-300 lines of Python — that implements the real agentic loop, has functional tools, and lets you observe from the inside how an agent reasons. Building one, even a simple one, gives more understanding than 100 hours of just using one.

By completing the 5 capsules, you'll have built a functional mini coding agent with 4 tools (read_file, write_file, list_directory, run_command), logging that shows each decision, and an analysis document with 5+ insights observed from its behavior. The code and the document are, literally, the proof that you understand how agents work.


What You're Going to Build

┌──────────────────────────────────────────────────┐
│              MINI CODING AGENT                    │
│                                                  │
│  ┌──────────┐     ┌──────────────────────┐       │
│  │ LLM API  │ ←→  │ TOOLS               │       │
│  │ (Claude  │     │ → read_file          │       │
│  │  or GPT) │     │ → write_file         │       │
│  └────┬─────┘     │ → list_directory     │       │
│       │           │ → run_command        │       │
│       │           └──────────────────────┘       │
│       │                                          │
│  ┌────▼─────────────────────┐                    │
│  │     AGENTIC LOOP         │                    │
│  │ prompt → LLM → tool call │                    │
│  │ → execute → result →     │                    │
│  │ LLM → ... → response     │                    │
│  └──────────────────────────┘                    │
│       │                                          │
│  ┌────▼─────────────────────┐                    │
│  │     LOGGING              │                    │
│  │ Every decision recorded  │                    │
│  │ step by step             │                    │
│  └──────────────────────────┘                    │
│                                                  │
│  ~200-300 lines of Python                        │
│  A single file: mini_agent.py                    │
│                                                  │
└──────────────────────────────────────────────────┘

What you WILL implement

✅ The agentic loop (observe → think → act → observe)
✅ Real tool calling (the LLM decides which tool to use)
✅ 4 functional tools (file read/write, list dir, run command)
✅ Basic safety (restrictions on run_command, limited directory)
✅ Logging of every decision (for later analysis)
✅ The ability to process real tasks in a test directory

What you will NOT implement

❌ A usable product (this is educational)
❌ Web search (we simplify to file + shell)
❌ Multi-turn conversation (one task per execution)
❌ A complete permission system (only basic safety)
❌ Advanced context window management (the project is small)
❌ A UI (it's a terminal script)

Why Building an Agent Changes Your Understanding

There's a categorical difference between "knowing how something works" and "having built it." The concepts from module 03 (the agentic loop) and module 04 (tool calling) take their final form when you implement them with your own hands.

BEFORE BUILDING:
→ "The agent decides what to do" (abstract)
→ "The agent uses tools" (vague)
→ "The agentic loop works" (theoretical)

AFTER BUILDING:
→ "The LLM generates a JSON with a tool name and args,
   my code executes the tool, and the result
   is sent back as a message" (concrete)
→ "The tool is a Python function that I defined,
   and the LLM only chooses which one to call" (specific)
→ "The loop is a while True with a stop
   condition when the LLM doesn't generate a tool call" (implementable)

The key revelation

WHEN YOU BUILD, YOU DISCOVER THAT:

1. The LLM isn't magic — it's an API that returns JSON
2. The tools are simple functions — you define them
3. The agentic loop is a while loop — you control it
4. The "intelligence" comes from the LLM, the "capacity" comes from your tools
5. The agent is YOUR code + the LLM's API

After this module, when you use Claude Code, Cursor, or Copilot, you're going to see the pattern underneath: the API call, the JSON with tool calls, the loop, the functions the model invokes. That's deep understanding — and it's what an employer or client can recognize in a technical interview.


The Project's Silhouette: Minimal Skeleton

So you have a concrete mental image before starting, this is the shape of the project you're going to build. It's not the solution — it's the silhouette. Capsules 02-04 lead you to complete it.

# mini_agent.py — skeleton (~30 lines, NOT functional yet)
# Capsules 02-04 teach you to fill in each gap.

import anthropic  # or openai
from pathlib import Path

client = anthropic.Anthropic()

# 1) Define the tools (Capsule 02 + 04)
TOOLS = [
    {"name": "read_file",      "input_schema": {...}},
    {"name": "write_file",     "input_schema": {...}},
    {"name": "list_directory", "input_schema": {...}},
    {"name": "run_command",    "input_schema": {...}},
]

def execute_tool(name: str, args: dict) -> str:
    """Dispatch the tool the LLM requested. (Capsule 04)"""
    ...

def log(step: int, event: str, payload: dict) -> None:
    """Record every decision and its result. (Capsule 03)"""
    ...

# 2) The agentic loop (Capsule 03)
def run_agent(user_task: str) -> str:
    messages = [{"role": "user", "content": user_task}]
    step = 0
    while True:
        response = client.messages.create(
            model="claude-haiku-4-5", tools=TOOLS, messages=messages
        )
        log(step, "llm_response", response)

        if response.stop_reason == "end_turn":
            return response.content[0].text          # stop condition

        # Execute all the tool calls of this turn
        tool_results = [
            {"type": "tool_result", "tool_use_id": tu.id,
             "content": execute_tool(tu.name, tu.input)}
            for tu in response.content if tu.type == "tool_use"
        ]
        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": tool_results})
        step += 1

if __name__ == "__main__":
    print(run_agent("Read README.md and summarize its content in 3 bullets."))

This skeleton:

  • ✅ Shows you how many pieces the project has (~5 functions + a loop)
  • ✅ Defines the build order (tools → executor → logger → loop)
  • ❌ Is not executable yet — the ... are your job
  • Doesn't include safety (Capsule 04) or the analysis document (Capsule 05)

By the end of the module, your file will be 5-10× longer than this, with error handling, sandboxing of run_command, and readable logging.


Technical Prerequisites

Option A: With an API key (recommended)

YOU NEED:
→ Python 3.10+
→ pip (package manager)
→ An Anthropic (Claude) OR OpenAI (GPT) API key
→ A terminal
→ A text editor

ESTIMATED COST:
→ Anthropic: ~$0.50-2.00 for the whole project
→ OpenAI: ~$0.50-2.00 for the whole project
→ The cheaper models (Haiku, GPT-4o-mini) are enough

SETUP:
→ Capsule 02 guides you step by step
→ ~15 minutes of setup

Option B: Without an API key (alternative)

IF YOU DON'T HAVE AN API KEY:
→ You can do the analysis without building
→ Use public transcripts from the METR study
→ Analyze the decisions of real agents
→ The analysis document is the most valuable part

CAPSULE 05 has instructions for both options.

The Connection with Each Module

Module 02 (LLMs):
→ You'll configure temperature, max_tokens in the API
→ You'll see next-token prediction in action
→ You'll observe hallucinations firsthand

Module 03 (Agents):
→ You'll implement LLM + tools + loop + autonomy
→ You'll see real tool calling (JSON schema → function)
→ The agentic loop will be YOUR while loop

Module 04 (Toolbox):
→ You'll implement read_file, write_file, list_directory, run_command
→ You'll see how the agent "sees" a directory
→ You'll implement basic safety

Module 05 (Developer as director):
→ You're the "circuit breaker" of your mini-agent
→ You'll observe when the agent makes correct and incorrect decisions
→ You'll calibrate your confidence with real data

Module 06 (Workflow):
→ You'll use R→P→E→V to build the project
→ You'll observe anti-patterns in the agent's behavior
→ You'll verify your implementation step by step

Project Structure

mini-agent/
├── mini_agent.py        ← The complete agent (~200-300 lines)
├── requirements.txt     ← Dependencies (anthropic or openai)
├── .env                 ← Your API key (do NOT commit)
├── test_workspace/      ← The directory where the agent works
│   ├── example.py       ← Test files
│   └── ...
└── analysis.md          ← Your analysis document

Module Roadmap

Capsule 01 — Project introduction (this capsule)

What you'll build, why, prerequisites, structure, skeleton.

Capsule 02 — Setup: API and tool calling

Install dependencies. Configure the API key. Make your first API call. Understand tool definitions in JSON schema.

Capsule 03 — Implement the agentic loop

The central loop: prompt → LLM → tool call → execute → result → LLM → ... The stop condition. Logging of each step.

Capsule 04 — Add tools: file and shell

Implement the 4 tools. Basic safety (limited directory, restricted commands). Test with real tasks.

Capsule 05 — Analysis and documentation

Run the agent on 3-5 tasks. Observe decisions. Write the analysis document with 5+ insights.

Progression map

Capsule 01 (this)    → What and why
Capsule 02           → Setup and first API call
Capsule 03           → The loop (the heart of the agent)
Capsule 04           → The tools (the agent's hands)
Capsule 05           → Analysis (the deep understanding)

Difficulty: ⭐⭐ ────────────────────────▶ ⭐⭐⭐⭐

Evaluation Rubric (Self-Verification)

This rubric is your self-verification as you close the project. The project passes with 70 points or more (out of 100, with up to +10 extra). Mark each criterion when you meet it.

Functionality — 25 pts

  • (10 pts) Functional agentic loop: the while loop correctly executes prompt → LLM → tool call → execute → result → LLM, with a stop condition when the model finishes.
  • (8 pts) Real tool calling: the LLM chooses which tool to use; your code executes it and returns the result to the LLM.
  • (4 pts) Error handling: if a tool fails (nonexistent file, invalid command), the agent receives the error and can continue or report it.
  • (3 pts) Terminates in a controlled way: it doesn't enter infinite loops; it respects a maximum iteration limit for safety.

Tools implemented — 20 pts

  • (5 pts) read_file works in the working directory
  • (5 pts) write_file creates/modifies files correctly
  • (5 pts) list_directory lists content without infinite recursion
  • (5 pts) run_command with basic safety (allowlist of commands or a restrictive pattern)

Logging and observability — 15 pts

  • (8 pts) Each step of the loop generates a log: iteration number, which tool the LLM requested, what arguments, what result it returned
  • (4 pts) The logs are readable (humans can trace the agent's reasoning)
  • (3 pts) Errors and unexpected behavior are recorded

Analysis document — 25 pts

  • (15 pts) 5+ insights observed, each with: description + a concrete example from the log + a connection with a module (02-06)
  • (5 pts) A comparison with a commercial agent (Claude Code, Cursor, Copilot) — at least 3 points
  • (5 pts) Reflection on the limitations of your mini-agent and what you'd add for production

Code quality — 15 pts

  • (5 pts) Well-named functions with a single responsibility
  • (4 pts) Error handling with try/except on I/O operations and API calls
  • (3 pts) requirements.txt up to date and .env documented (not committed)
  • (3 pts) A minimal README with usage instructions

Extra credit (optional, up to +10 pts)

  • (+3 pts) You implemented a 5th tool (web_search, grep, edit_file)
  • (+3 pts) Multi-turn: the agent remembers context between tasks in the same session
  • (+2 pts) Metrics: you count tokens consumed per session and total time
  • (+2 pts) Pretty logging: output with colors or structured format (rich, JSON, etc.)

Total: 100 pts (+10 extra) · Passing: ≥ 70 pts


Common Errors in This Project

Five errors that appear specifically in this project. Anticipate them before starting.

Error 1: Infinite loop

Symptom: Your agent keeps calling tools without stopping and consumes API credits.

Why it happens: You didn't clearly define the stop condition. The LLM always returns something — if you don't validate that the stop_reason is end_turn (Anthropic) or that there are no tool_calls in the response (OpenAI), the loop never ends.

How to fix it: Define two stop conditions: (1) the natural one (the LLM doesn't ask for more tools), and (2) a hard limit of iterations (MAX_ITERATIONS = 20) as a safety net.

Error 2: Confusing "the LLM requested the tool" with "the tool executed"

Symptom: Your agent "responds" but never reads real files.

Why it happens: The LLM only returns a structured message saying "I want to use read_file with args X." YOU have to execute that function and return the result. It's the distinction from Module 03.

How to fix it: Your code must (1) parse the tool calls from the response, (2) execute them with your execute_tool function, (3) append the results to messages with role user and type tool_result, and (4) call the LLM again with the updated context.

Error 3: Over-designing the toolbox

Symptom: You've spent 4 hours and only have half of 8 tools, none tested together.

Why it happens: More tools = more decision complexity for the LLM and more bug surface for you. Four tools are enough for the project to demonstrate the complete agentic loop.

How to fix it: Start with read_file + list_directory (the two simplest). Confirm the loop works. Then add write_file. Only at the end add run_command (the most dangerous). If there's time left, consider the extra credit.

Error 4: Skipping the analysis document

Symptom: The code works, but you got stuck on "it's done, I don't know what to write."

Why it happens: Building seems like "the real work" and the document seems like an "optional task." The rubric tells you the opposite: the analysis is worth 25%, the same as the functional agent. Employers and clients value your articulated understanding more than your code.

How to fix it: While you run your agent with 3-5 tasks, keep a notes.md file open and jot down raw observations. Don't edit them — just record them. In the end, those notes become the analysis document with a bit of structure.

Error 5: run_command without sandboxing

Symptom: Your agent deletes important files, modifies system configuration, or runs dangerous commands.

Why it happens: You implemented run_command with subprocess.run(cmd, shell=True) without restrictions. The LLM can generate any command — including rm -rf, curl ... | sh, or worse.

How to fix it: Implement at least one of these three protections (Capsule 04 develops all three):

  1. Command allowlist: you only allow ls, cat, python, pytest, etc.
  2. Restricted workspace: all commands run with cwd=test_workspace/, not in your HOME.
  3. Human confirmation: before executing, you print the command and ask y/n.

For an educational project, the first two are enough. Without one of these, don't run the agent with non-trivial tasks.


What to Do if You Get Stuck?

If the setup doesn't work (capsule 02):
  → Check the Python version: python --version (≥3.10)
  → Check that pip installed the deps: pip list | grep anthropic
  → Check that the API key loads: echo $ANTHROPIC_API_KEY

If the loop doesn't end (capsule 03):
  → Print stop_reason on each iteration
  → Confirm you have MAX_ITERATIONS as a safety net
  → Check the format of the tool_results in messages

If a tool isn't invoked (capsule 04):
  → Print the complete response from the LLM
  → Verify that the tool's JSON schema is valid
  → Confirm that the tool's description clearly indicates when to use it

If the analysis feels empty (capsule 05):
  → Run the agent again with harder tasks
  → Compare the transcript with that of a commercial agent
  → Ask yourself: what surprised me? what failed in an interesting way?

How to Work Through This Module

RECOMMENDATION: USE R→P→E→V (from Module 06)

RESEARCH (15 min):
→ Read the 5 capsules before coding
→ Understand the complete architecture
→ Identify what's unclear to you

PLAN (10 min):
→ Decide: Anthropic or OpenAI
→ Confirm you have Python and pip
→ Plan the implementation order

EXECUTE (45 min):
→ Setup (capsule 02): 15 min
→ Agentic loop (capsule 03): 15 min
→ Tools (capsule 04): 15 min

VALIDATE (30 min):
→ Test with 3-5 real tasks
→ Observe the logging
→ Write the analysis (capsule 05)

TOTAL: ~1.5 hours

What's Next: Applying What You Learned

This is the last module of the guide. What you built here doesn't stay in this project — it connects with the whole Agentic Development path:

Next stepHow what's in this module applies
Claude Code Foundations (Guide #2 of the path)You're going to recognize the tool calling pattern when you use the real Claude Code. The difference with your mini-agent is scale, not concept.
Prompt Engineering with Claude Code (Guide #3)When you write prompts, you'll know what happens on the inside: how the model decides which tool to invoke, what tokens it consumes, what stop reason it expects.
Debugging & Code Review (Guide #6)You'll debug agents with judgment: when the agent "doesn't understand," you'll already know whether it's a prompt problem, a tool description problem, or a loop problem.
Your real workNow you can evaluate coding agents (Cursor vs Claude Code vs Copilot Agent) with technical vocabulary — not by marketing.

Before closing this module, you should be able to:

  • Show your mini_agent.py running on a non-trivial task
  • Trace a session of your agent step by step (which tool, what args, what result)
  • Articulate 5+ insights observed in your analysis document
  • Compare your mini-agent with a commercial agent on at least 3 dimensions
  • Recognize the concepts from modules 02-06 in your own implementation

If the 5 points are in place, you've completed the guide. You now have the conceptual and practical foundation to be Developer B from Module 05 — the one who directs the agent with judgment instead of accepting everything it produces.


Summary

This module transforms the theory of modules 1-6 into practical understanding.

What you'll build:

  • A mini coding agent in Python (~200-300 lines) with an agentic loop, 4 tools, and logging
  • An analysis document with 5+ insights observed from your agent

Why it matters:

  • Building an agent, even a simple one, gives more understanding than just using it
  • The analysis document is the articulated proof of your understanding
  • It's the most portfolio-worthy output of the entire guide

What it produces:

  • Real technical vocabulary for discussing agents in interviews or with your team
  • The judgment to evaluate commercial tools (Claude Code, Cursor, Copilot)
  • A project that lives on your GitHub as evidence of understanding

Next capsule: 02 — Setup: API and tool calling — configure Python, install the SDK (anthropic or openai), save your API key, make the first API call, and understand how a tool is declared in JSON schema.


Resources for the Project

  1. Anthropic Tool Use Documentation — Complete reference for tool calling with the Claude API (the API we'll use by default)
  2. OpenAI Function Calling Guide — The equivalent for OpenAI; useful if you choose that API
  3. Anthropic Python SDK — The SDK repository with usage examples
  4. Anthropic Cookbook: Tool Use Examples — Complete examples of agents with tool use
  5. Anthropic: Building Effective Agents — Design patterns that your mini-agent reflects on a small scale
  6. Python subprocess Documentation — To implement run_command correctly with sandboxing