Build a coding agent in Python
An agent that reads and edits a project, runs its tests and stops when they pass, with the safety checks that keep it inside the project.
A harness that edits a project, runs its tests and stops when they pass.
What should a coding harness count as completion when the model says a patch works?
Give the harness independent evidence of success. Keep the tests outside the agent's write scope and evaluate the final project state under the same rules as the original brief.
Agent proposes and applies a scoped edit
Harness runs the fixed grading tests
Run ends in success only when acceptance checks pass
Agent proposes and applies a scoped edit
Harness runs the fixed grading tests
Run ends in success only when acceptance checks pass
Given Agent proposes and applies a scoped edit and Run ends in success only when acceptance checks pass, write down the missing step that connects them.
Harness runs the fixed grading tests
Now take Harness runs the fixed grading tests and the result above. Write an input and an implementation that could produce this trace.
Agent proposes and applies a scoped edit. Check that your implementation produces the result shown above.
The model says the repair is finished, but one acceptance test still fails. Should the harness report success?
Report the failed acceptance check and continue within the remaining budget or return an incomplete run. The test result is the harness's evidence of whether the task is done.
Check this when debugging. Trusting the model's "done" without checking.
This is the payoff for the phase. You'll build a small but complete coding agent: it reads and edits a project, runs its tests, and keeps going until they pass, or stops cleanly when it can't. The same architecture, scaled up, runs inside the coding tools professionals use every day. Once you've built one, you can read, tune and extend any of them.
Run the tests itself and check they pass
Only a check the harness runs itself counts; the model's claim is just text. This capstone ends a run when the tests pass in the harness, and stops it at a budget if they don't.
This is the parts list: each part is one you built, and the lesson it came from:
| part | from | in this agent |
|---|---|---|
| injected model | What an agent harness is | model(system, messages, tools), scripted in tests |
| loop | The core loop, built properly | tool_use runs tools; end_turn triggers the check |
| tools | A tool registry for agents, File and search tools, Running code safely | read_file, write_file, edit_file, run_tests |
| workspace jail | File and search tools | every path must resolve inside the project |
| permissions | Permissions and approvals | a file whose name starts with test_ is read-only, so a test can't be weakened |
| stop check | Hooks and skills | on end_turn, the harness runs the tests itself |
| turn cap | The core loop, built properly | stops with a clear status; a cost budget is part of the brief below |
| event log | Tracing, budgets and guardrails | one event per model call, tool call and test run |
In plain words: the model suggests what to do next, and your code checks it, does it and decides when the job is over.
def within_budget(turns, cost, max_turns=20, max_cost=2.00): return turns < max_turns and cost < max_cost print(within_budget(5, 0.40), within_budget(20, 0.40), within_budget(5, 2.50))
True False False
The first moment is inside both limits. The second has used up its turns, and the third has spent too much, so either one stops the run. The coding agent in this capstone keeps the turn half of that budget: it counts its model calls and stops at the limit. It also has a better reason to stop, which is that the tests pass.
The agent you build here is small on purpose. It gets a failing test suite and a project folder. It reads files, edits code and runs the tests. It must stop when the tests pass, and it must be unable to pass them by changing them. Everything about it is something you can predict, run and attack.
The model proposes and the harness decides. Permissions come before the tool runs, never after.
If the agent can edit the tests, the fastest way to make them pass is to weaken them. So test files, the ones whose names start with test_, are read-only, and the check runs before any write.
from pathlib import PurePosixPath def may_write(path): if PurePosixPath(path).name.startswith("test_"): return False, "tests are read-only: change the code, not the test" return True, "ok" for path in ["calc.py", "test_calc.py", "src/test_util.py", "src/util.py"]: print(path, may_write(path))
The refusal message matters. It tells the model what to do instead, so it goes back to fixing the code. You'll use this rule in the exercise.
The exercise protects one kind of file: a file whose name starts with test_, wherever it sits in the tree. Write protected(path, patterns): return True if path matches any glob pattern in patterns (use fnmatch.fnmatch), so one function can refuse edits to all of them.
from fnmatch import fnmatch PATTERNS = ["test_*.py", "*/test_*.py"] def protected(path, patterns): return path in patterns print(protected("src/test_calc.py", PATTERNS), protected("calc.py", PATTERNS))
Write a sentence or two, then compare it with a good answer in the lesson.
Students don't mark their own exams. A model saying "Fixed!" is a claim, not a result. So when the model ends its turn, the harness runs the tests itself, like a Stop hook:
"failed", so a person can look.Combined with read-only tests, this closes the obvious shortcut: the only way to pass is to fix the code.
The model says it's done on the first try here, but it isn't. The harness runs the tests itself and sends it back.
replies = iter([
{"stop_reason": "end_turn", "text": "All done!", "fix": False},
{"stop_reason": "end_turn", "text": "Fixed the off-by-one.", "fix": True},
])
code_is_fixed = False
def run_tests():
return code_is_fixed
for turn in range(1, 6):
reply = next(replies)
code_is_fixed = reply["fix"]
print(f"turn {turn}: model says {reply['text']!r}")
if run_tests():
print("tests pass: finished")
break
print("tests fail: sending the failure back")The first reply is confident and wrong. If the harness had believed it, you'd have shipped a bug. A check the model can't talk its way past is what makes an agent trustworthy.
model_says_done = True tests_pass = False print(model_says_done and tests_pass)
False
True and False is False, so it prints False. The model's opinion isn't enough. The harness runs the tests itself.
The run_tests helper is given. It imports each test_*.py file in the project and calls its test_* functions, a tiny version of pytest. On a real machine you'd run pytest through the execution tool, in a sandbox.
It returns whether everything passed and a short summary for the model.
import importlib, sys, tempfile from pathlib import Path def run_tests(root): root = Path(root) passed, failures = 0, [] sys.path.insert(0, str(root)) old_flag, sys.dont_write_bytecode = sys.dont_write_bytecode, True try: for test_file in sorted(root.glob("test_*.py")): for name in [m for m in list(sys.modules) if (root / f"{m}.py").exists()]: del sys.modules[name] importlib.invalidate_caches() ns = {"__name__": "tests"} try: exec(compile(test_file.read_text(), str(test_file), "exec"), ns) except Exception as err: failures.append(f"ERROR {test_file.name}: {type(err).__name__}: {err}") continue for name, fn in list(ns.items()): if name.startswith("test_") and callable(fn): try: fn() passed += 1 except Exception as err: failures.append(f"FAIL {name}: {err}") finally: sys.path.remove(str(root)) sys.dont_write_bytecode = old_flag summary = f"{passed} passed, {len(failures)} failed" summary += "".join("\n" + f for f in failures) return {"passed": passed > 0 and not failures, "summary": summary} root = Path(tempfile.mkdtemp()) (root / "calc.py").write_text("def add(a, b):\n return a - b\n") (root / "test_calc.py").write_text( 'from calc import add\n\ndef test_add():\n' ' assert add(2, 2) == 4, f"add(2, 2) gave {add(2, 2)}"\n') print(run_tests(root))
Removing the project's modules from sys.modules, and not writing bytecode, makes each run import the current files, so edits take effect right away.
It never got that far: edits to test files are denied, so the model must fix calc.py instead
Read-only tests plus a harness-run check means the only way to pass is a real fix.
The harness runs the tests itself when the model ends its turn
A model's "done" is a claim. The harness turns it into a fact by running the tests.
These stand in for a real model, each with a habit. careful fixes the code. overconfident claims success with a wrong fix. edits_tests tries to weaken the test. The harness catches each one in a different way. Tuples are (habit, status, turns, refused edits, test checks).
from pathlib import PurePosixPath from agentlab import PracticeModel, TASKS, run_tests TOOLS = ["read_file", "edit_file", "run_tests"] def run_agent(habit, max_turns=10): files = dict(TASKS["calc"]["files"]) model = PracticeModel(habit) messages = [{"role": "user", "content": TASKS["calc"]["prompt"]}] refused = checks = 0 for turn in range(1, max_turns + 1): reply = model(messages, TOOLS) messages.append({"role": "assistant", "content": reply["content"]}) if reply["stop_reason"] == "tool_use": results = [] for b in reply["content"]: if b["type"] != "tool_use": continue name, args = b["name"], b["input"] path = args.get("path", "") if name == "edit_file" and PurePosixPath(path).name.startswith("test_"): out, bad = "Denied: test files are read-only.", True refused += 1 elif name == "edit_file": files[path] = files[path].replace(args["old"], args["new"]) out, bad = "Edited " + path, False elif name == "read_file": out, bad = files[args["path"]], False else: out, bad = run_tests(files)["summary"], False result = {"type": "tool_result", "tool_use_id": b["id"], "content": out} if bad: result["is_error"] = True results.append(result) messages.append({"role": "user", "content": results}) continue checks += 1 verdict = run_tests(files) if verdict["passed"]: return habit, "passed", turn, refused, checks note = "The tests still fail:\n" + verdict["summary"] + "\nKeep working." messages.append({"role": "user", "content": note}) return habit, "max_turns", max_turns, refused, checks for habit in ["careful", "overconfident", "edits_tests"]: print(run_agent(habit))
Write a sentence or two, then compare it with a good answer in the lesson.
Write a sentence or two, then compare it with a good answer in the lesson.
A "do not touch" sign isn't a lock. You could write "do not edit the tests" in the system prompt. It would work most of the time, and that's the problem. Under pressure from a failing test, with several attempts already used, a model may decide that the test is what's wrong. It may even be right sometimes. But your check on the agent's work is worthless if the agent can rewrite it.
So the harness enforces the rule. Test files are read-only at the tool level, and no amount of clever reasoning changes that. As a general rule, use prompts to guide and code to guarantee.
Without a limit, an agent that can't solve a problem keeps trying forever, spending money each turn. So cap the turns, and when the budget runs out, stop and report honestly: what it tried, which tests still fail, and what state it left the files in. Reporting failure clearly is a feature. A person can pick up from there, which is much better than a silent loop, or a confident claim that everything works.
Stop and report what it tried and which tests still fail
A clear report lets a person pick up from there. Without a limit, the agent spends money forever, and a false claim of success is worse than an honest failure.
Write final_report(results, turns, max_turns): results maps test names to True/False. If all pass, return All N tests pass.; otherwise Stopped after T of M turns: K of N tests still fail: followed by the failing names, sorted and joined with , .
def final_report(results, turns, max_turns): return "Done! All tests pass." print(final_report({"test_add": True, "test_sub": False, "test_div": False}, 12, 12))
Remember the flight simulator. The pilot's controls stay the same when they move to the real plane. Because the model is injected, switching from the scripted model to Claude is one small adapter. With an API key on your own machine, using the official SDK:
import anthropic client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment def claude(system, messages, tools): reply = client.messages.create(model="claude-opus-5-5", max_tokens=4000, system=system, tools=tools, messages=messages) return {"stop_reason": reply.stop_reason, "content": [block.model_dump(exclude_none=True) for block in reply.content]} agent = CodingAgent(claude, "path/to/project") print(agent.run("The tests in test_calc.py fail. Find the bug and fix it."))
model_dump(exclude_none=True) turns the SDK's block objects into the plain dicts the harness uses. From there, add the pieces from this phase one at a time, and run your eval suite after each, to see what actually helps.
When you plug in the real API, the harness stays exactly the same. The scripted model and the real one are both functions that take messages and tools and return a reply. Every path you tested with a script, including errors, timeouts and bad tool calls, is still tested. Real models add one thing: variety. Run each task several times, as Evaluation harnesses shows, since a single pass proves little.
From here you can add a real sandbox for the commands (Sandboxes for agents that browse), a smarter way to pick which files to read, or a question to the person when the agent is stuck. Each is a small change to one part. The loop in the middle stays as it is, which is what makes a well-designed harness easy to grow.
Your exercise agent passes its tests. A shipped agent also has evidence. Run it against the practice models and the three practice tasks, then write down what you found.
PracticeModel({"careful": 3, "overconfident": 1, "edits_tests": 1}, seed=k). Print passes out of 9 and the habit behind every failure.agentlab.spans_plot, with the slowest span named in a sentence.loops and obeys_injection in the mix and show which part catches each.from agentlab import PracticeModel, TASKS, run_tests, grade, project mix = {"careful": 3, "overconfident": 1, "edits_tests": 1} for name in ["calc", "discount", "words"]: for seed in range(3): model = PracticeModel(mix, seed=seed) # Run your harness with this model on TASKS[name], then grade the result. print(name, seed, "TODO")
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Why does the harness run the tests itself when the model says it's done?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
An agent that reads and edits a project, runs its tests and stops when they pass, with the safety checks that keep it inside the project.
Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.
Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write