Build

Harness Engineering Tutorial: Build Your First AI Agent

Harness engineering tutorial: build a Python AI agent harness with fixed tools, a step budget, checkpoints and verification. Runs offline.

Abhishek Ashtekar at a laptop beside a terminal panel and Build Your First AI Agent text.
On this page
  1. What you will build
  2. What you need
  3. Step 1: Download the files
  4. Step 2: Run the agent
  5. Step 3: Read the complete harness
  6. Step 4: The model interface
  7. Step 5: The tool contract
  8. Step 6: Verification
  9. Step 7: Stop rules
  10. Step 8: Checkpoint and resume
  11. Step 9: Run the tests
  12. Troubleshooting
  13. Common mistakes in a first agent harness
  14. What this harness does not do
  15. Extend it
  16. Frequently asked questions
  17. Learn the full system with my book
  18. Final thoughts
  19. Sources and further reading

In brief

This harness engineering tutorial builds a working AI agent harness in 114 lines of standard-library Python. A scripted model requests actions. The harness checks each one against three fixed tools, saves a checkpoint after every step and stops at a four-step budget. It accepts "done" only after an independent check passes. Everything runs offline and comes with eight tests.

If you have used a coding agent for long, you have probably been told that a task was finished when it was not. It is an annoying moment, and it raises a good question. Which part of the system should have noticed?

You will understand the answer when you build a small harness yourself, so that is what we will do. You will run a tiny agent, read each line of the harness around it and then break it on purpose, one control at a time. I show you the exact output to expect, so you will know straight away whether a control works.

What you will build

You will build an agent that reads a task list and writes a one-line report of the finished tasks. Before the run ends, the harness proves that the report is correct. You do not need an AI to count finished tasks, of course. I chose the job because you can check the answer in your head, which leaves all your attention for the controls around the model.

If the word "harness" is new to you, start with what harness engineering is. The harness is everything around the model that decides what it sees, what it may do and when its work counts as finished. Anthropic's article Building effective agents describes agents as "LLMs using tools based on environmental feedback in a loop". This tutorial builds that loop and the controls that keep it honest.

The example has six parts. Each part maps to named code that you will read later.

Part What it does Where it lives in agent_harness.py
Model interface Takes the history and returns one action scripted_model()
Tool contract Allows three tools with exact arguments and three file names The if and elif branches in run(), plus path()
Agent loop Asks for an action, runs it, records the result, repeats The while loop in run()
Verification Recounts the source data and compares it with the saved report verify()
Stop rules Ends the run as complete, budget_exhausted or with an error max_steps and the statuses in run()
Checkpoint and resume Saves the history after every step and continues from it save() and the start of run()

The model can request only read_tasks, write_report or done, so it has no way to name a file or run a shell command. This is the first lesson of the tutorial. The model proposes an action, and the harness decides whether it runs.

What you need

You need Python 3 and a terminal. The harness and its tests use only the standard library, so you install nothing with pip and set up no API key. Every command and output in this guide comes from a run on Python 3.14 on macOS.

The commands use python3, the usual name on macOS and Linux. On Windows, type py instead, or python if that is how you installed it. Python's guide to using Python on Windows explains both commands.

Keep this exercise in its own folder, away from real projects and valuable data. The harness touches only three files inside a folder it creates, and a practice folder is easy to delete when you have finished.

Step 1: Download the files

Download the three example files from the "Example files" box on this page: agent_harness.py, test_agent_harness.py and AGENTS.md. Then create a new folder and open a terminal in it:

bash
mkdir harness-tutorial
cd harness-tutorial

Move the three downloaded files into harness-tutorial. Before you run anything, your folder looks like this:

text
harness-tutorial/
  AGENTS.md
  agent_harness.py
  test_agent_harness.py

agent_harness.py holds the whole harness and a small demo. test_agent_harness.py holds eight tests that prove each control works. AGENTS.md is a short instruction file for a coding agent, which you will use in Step 9.

Step 2: Run the agent

Run the demo from inside the folder:

bash
python3 agent_harness.py

On the first run, the program prints two lines:

text
complete
Completed tasks: 2

The first line is the final status of the run, and the second is the report that the agent wrote. If you look in the folder, you will also find a new demo-workspace with three files:

  • tasks.json holds three sample tasks, and two of them are done.
  • report.txt holds the report, Completed tasks: 2.
  • state.json holds the checkpoint, which records every step and the final status.

Open state.json. The last entry and the status look like this:

text
    {
      "tool": "done",
      "args": {},
      "result": "verified"
    }
  ],
  "status": "complete"
}

Above that entry, you will find a read_tasks step with the three tasks and a write_report step with the text of the report. This file is your first trace, and it is the first place to look when a run goes wrong.

Run python3 agent_harness.py a second time. You see the same two lines, but the agent does not repeat its work. The harness finds a checkpoint marked complete, checks the report against the tasks again and returns. Step 8 shows how.

Step 3: Read the complete harness

Here is the complete harness. It is the same file you downloaded.

python
"""Small offline harness. Fixed tools, saved progress, budget and verification."""
from copy import deepcopy
from pathlib import Path
import json
import tempfile


class HarnessError(Exception):
    pass


def scripted_model(history):
    """A deterministic stand-in for a model, used to inspect the loop offline."""
    if not history:
        return {"tool": "read_tasks", "args": {}}
    if history[-1]["tool"] == "read_tasks":
        count = sum(task["done"] for task in history[-1]["result"])
        return {"tool": "write_report",
                "args": {"content": f"Completed tasks: {count}\n"}}
    return {"tool": "done", "args": {}}


class Harness:
    def __init__(self, workspace, max_steps=4):
        self.root = Path(workspace).resolve()
        self.root.mkdir(parents=True, exist_ok=True)
        self.max_steps = max_steps

    def path(self, name):
        if name not in {"tasks.json", "report.txt", "state.json"}:
            raise HarnessError("File is outside the fixed tool scope")
        p = self.root / name
        if p.is_symlink() or p.resolve().parent != self.root:
            raise HarnessError("Unexpected file location")
        return p

    def tasks(self):
        try:
            data = json.loads(self.path("tasks.json").read_text())
        except (OSError, ValueError) as exc:
            raise HarnessError("Cannot read valid tasks.json") from exc
        if not isinstance(data, list) or any(
            not isinstance(t, dict) or type(t.get("done")) is not bool
            for t in data
        ):
            raise HarnessError("Tasks must be a list with boolean done fields")
        return data

    def verify(self):
        expected = f"Completed tasks: {sum(t['done'] for t in self.tasks())}\n"
        p = self.path("report.txt")
        if not p.is_file() or p.read_text() != expected:
            raise HarnessError("Report does not match the source tasks")

    def save(self, history, status):
        # A local checkpoint, not a distributed transaction mechanism.
        state = self.path("state.json")
        with tempfile.NamedTemporaryFile(
            "w", dir=self.root, delete=False, encoding="utf-8"
        ) as tmp:
            json.dump({"history": history, "status": status}, tmp, indent=2)
            temporary = Path(tmp.name)
        temporary.replace(state)

    def run(self, model=scripted_model, resume=True):
        history = []
        state = self.path("state.json")
        if resume and state.exists():
            saved = json.loads(state.read_text())
            history = saved["history"]
            if saved["status"] == "complete":
                self.verify()
                return {"status": "complete", "history": history}
        while len(history) < self.max_steps:
            action = model(deepcopy(history))
            if not isinstance(action, dict) or set(action) != {"tool", "args"}:
                raise HarnessError("Expected tool and args fields")
            tool, args = action["tool"], action["args"]
            if not isinstance(args, dict):
                raise HarnessError("Tool args must be an object")
            if tool == "read_tasks" and not args:
                result = self.tasks()
            elif tool == "write_report" and set(args) == {"content"}:
                content = args["content"]
                if not isinstance(content, str) or len(content) > 2000:
                    raise HarnessError("Report content is invalid")
                self.path("report.txt").write_text(content)
                result = {"written": "report.txt"}
            elif tool == "done" and not args:
                self.verify()
                history.append({"tool": tool, "args": args, "result": "verified"})
                self.save(history, "complete")
                return {"status": "complete", "history": history}
            else:
                raise HarnessError("Tool or arguments are not allowed")
            history.append({"tool": tool, "args": args, "result": result})
            self.save(history, "active")
        self.save(history, "budget_exhausted")
        return {"status": "budget_exhausted", "history": history}


if __name__ == "__main__":
    root = Path("demo-workspace")
    root.mkdir(exist_ok=True)
    tasks = root / "tasks.json"
    if not tasks.exists():
        tasks.write_text(json.dumps([
            {"title": "Read about loops", "done": True},
            {"title": "Inspect tools", "done": True},
            {"title": "Add recovery", "done": False}
        ]))
    result = Harness(root).run()
    print(result["status"])
    print((root / "report.txt").read_text(), end="")

Read it once from top to bottom before you go on, even if some of it is not clear yet. run() holds the loop, and every other method serves it. In each pass of the loop, run() asks the model for an action and checks its shape. Then it runs an allowed tool, records the result and saves a checkpoint. Steps 4 to 8 take that loop apart, one responsibility at a time.

Step 4: The model interface

The model interface is a function that takes the run's history and returns one action. Here is the scripted stand-in:

python
def scripted_model(history):
    """A deterministic stand-in for a model, used to inspect the loop offline."""
    if not history:
        return {"tool": "read_tasks", "args": {}}
    if history[-1]["tool"] == "read_tasks":
        count = sum(task["done"] for task in history[-1]["result"])
        return {"tool": "write_report",
                "args": {"content": f"Completed tasks: {count}\n"}}
    return {"tool": "done", "args": {}}

With an empty history, it asks to read the tasks. After a read, it counts the finished tasks and asks to write the report. After anything else, it asks to finish. This function is a fixed script with no language model behind it, so every run is predictable while you learn the loop.

Three details in this interface carry over to real agents:

  1. One action shape. Every action is a dictionary with exactly two keys, tool and args. The harness rejects anything else before it looks at the tool name.
  2. A copy of the history. The harness passes deepcopy(history) to the model. The model can read the past but cannot change it. Only the harness adds entries to the history.
  3. No direct access. The model never touches the workspace. It returns a request, and the harness decides whether to run it.

Connect a real model

Real model APIs follow the same pattern. Anthropic's tool use documentation explains that Claude returns a tool_use block when it wants a tool. Your code runs the operation and sends back a tool_result. OpenAI's function calling guide describes the same round trip with a function_call item. It adds that setting strict to true makes calls "reliably adhere to the function schema".

To use a real model, write an adapter function with the same signature as scripted_model. The adapter turns the history into messages and calls the provider. Then it converts the tool call into {"tool": ..., "args": ...}. Keep the harness validation, because a schema on the provider side does not decide what your application allows. Keep API keys in environment variables, never in the source file.

If you prefer a free, local model, Ollama supports tool calling through a server on your own computer. The adapter pattern is the same. Project 1 of my free companion course, Build an Agent Loop from Scratch, includes a run_real.py script for Anthropic and OpenAI models. Real models give different answers from run to run, so finish this offline version first.

Step 5: The tool contract

The tool contract is the list of actions the harness will run and the exact arguments each one accepts. In this example, it lives in four branches of run():

python
            if tool == "read_tasks" and not args:
                result = self.tasks()
            elif tool == "write_report" and set(args) == {"content"}:
                content = args["content"]
                if not isinstance(content, str) or len(content) > 2000:
                    raise HarnessError("Report content is invalid")
                self.path("report.txt").write_text(content)
                result = {"written": "report.txt"}
            elif tool == "done" and not args:
                self.verify()
                history.append({"tool": tool, "args": args, "result": "verified"})
                self.save(history, "complete")
                return {"status": "complete", "history": history}
            else:
                raise HarnessError("Tool or arguments are not allowed")
Tool Arguments it accepts What happens
read_tasks None Reads and validates tasks.json
write_report Exactly one, content, a string of 2,000 characters or fewer Writes report.txt
done None Runs verify(), then ends the run as complete
Anything else Not applicable Raises HarnessError and stops the run

The path() method adds a second fence around the file system:

python
    def path(self, name):
        if name not in {"tasks.json", "report.txt", "state.json"}:
            raise HarnessError("File is outside the fixed tool scope")
        p = self.root / name
        if p.is_symlink() or p.resolve().parent != self.root:
            raise HarnessError("Unexpected file location")
        return p

Every file access goes through this method. It accepts three names and refuses a symbolic link, so a link called report.txt cannot point the harness at a file outside the workspace. The model never sends a file name at all, because the harness picks the file for each tool.

Set up an experiment file

You will test each control with a badly behaved model. Create a file called try_it.py in the same folder with this content:

python
import json
import shutil
from pathlib import Path
from agent_harness import Harness, HarnessError, scripted_model


def fresh(max_steps=4):
    shutil.rmtree("lab", ignore_errors=True)
    Path("lab").mkdir()
    Path("lab/tasks.json").write_text(json.dumps(
        [{"done": True}, {"done": False}, {"done": True}]))
    return Harness("lab", max_steps=max_steps)


def attempt(label, model):
    try:
        result = fresh().run(model)
        print(label, "->", result["status"], len(result["history"]), "steps")
    except HarnessError as exc:
        print(label, "->", "HarnessError:", exc)


# Experiments go below this line.

fresh() rebuilds a lab folder with three tasks, two of them done. attempt() runs one model against it and prints the status or the error. Put each experiment under the last comment, replacing the one before it, and then run python3 try_it.py.

Try to break the contract

Paste these lines under the comment:

python
attempt("scripted model", scripted_model)
attempt("shell tool", lambda history: {"tool": "shell", "args": {"cmd": "ls"}})
attempt("extra argument", lambda history: {
    "tool": "read_tasks", "args": {"path": "/etc/passwd"}})
attempt("missing args", lambda history: {"tool": "read_tasks"})
attempt("huge report", lambda history: {
    "tool": "write_report", "args": {"content": "x" * 5000}})

Expected output:

text
scripted model -> complete 3 steps
shell tool -> HarnessError: Tool or arguments are not allowed
extra argument -> HarnessError: Tool or arguments are not allowed
missing args -> HarnessError: Expected tool and args fields
huge report -> HarnessError: Report content is invalid

The well-behaved model finishes in three steps. The one that asks for a shell is refused, even though its request looks harmless, and so is the one that slips a path into read_tasks. You could have described these rules in a prompt. Only this code can enforce them.

Step 6: Verification

Verification is the check that decides whether "done" is true. The harness does not trust the model's claim. It recounts the source data and compares the result with the file on disk:

python
    def verify(self):
        expected = f"Completed tasks: {sum(t['done'] for t in self.tasks())}\n"
        p = self.path("report.txt")
        if not p.is_file() or p.read_text() != expected:
            raise HarnessError("Report does not match the source tasks")

This verifier is independent for two reasons. It reads tasks.json again instead of trusting what the model saw, and it compares the saved file with the expected line while ignoring the model's message. Anthropic's agent guide says agents need "ground truth" from the environment at each step, and this check is that ground truth for the final step.

Replace your experiment with these lines:

python
def wrong_count(history):
    if not history:
        return {"tool": "write_report",
                "args": {"content": "Completed tasks: 3\n"}}
    return {"tool": "done", "args": {}}


attempt("done first", lambda history: {"tool": "done", "args": {}})
attempt("wrong count", wrong_count)

Expected output:

text
done first -> HarnessError: Report does not match the source tasks
wrong count -> HarnessError: Report does not match the source tasks

The first model claims success before it has written anything, and the second writes a confident report with the wrong number. Both runs fail, and that is what you want to happen when an agent says "done" and is wrong.

For your own tasks, design the check around the failure you fear most. A report might need a source for every figure. A code change might need a passing test and a look at the result a user sees. The guide on how to test AI agents shows how to turn checks like these into an evaluation set.

Step 7: Stop rules

Stop rules decide when a run ends and what the ending means. This harness has three exits:

  • complete, returned only after verify() passes.
  • budget_exhausted, returned when the history reaches max_steps, which is 4 by default.
  • A HarnessError, raised when an action breaks the contract or verification fails.

The budget lives in the loop condition, while len(history) < self.max_steps:. When the loop ends without a done, these two lines run:

python
        self.save(history, "budget_exhausted")
        return {"status": "budget_exhausted", "history": history}

Test it with a model that gets stuck. Replace your experiment with these lines:

python
attempt("stuck model", lambda history: {"tool": "read_tasks", "args": {}})
print(json.loads(Path("lab/state.json").read_text())["status"])

Expected output:

text
stuck model -> budget_exhausted 4 steps
budget_exhausted

The stuck model keeps asking to read the tasks, and after four steps the harness stops it and writes budget_exhausted to the checkpoint. Keep that status apart from complete, both in your logs and in what you tell users, because a run that ran out of steps did not finish its job.

A step count is the simplest stop rule. Anthropic's guide calls it common to add stopping conditions "such as a maximum number of iterations". Larger systems also cap time, tokens and cost. For the full diagnosis of agents that loop or stall, read why AI agents fail.

Step 8: Checkpoint and resume

A checkpoint is a saved copy of the run's history and status. The harness writes it after every step, so a later run can continue. Here is the save method:

python
    def save(self, history, status):
        # A local checkpoint, not a distributed transaction mechanism.
        state = self.path("state.json")
        with tempfile.NamedTemporaryFile(
            "w", dir=self.root, delete=False, encoding="utf-8"
        ) as tmp:
            json.dump({"history": history, "status": status}, tmp, indent=2)
            temporary = Path(tmp.name)
        temporary.replace(state)

The method writes the new state to a temporary file in the same folder, then renames that file over state.json. Python's pathlib documentation maps Path.replace() to os.replace(). The os.replace documentation says a successful rename "will be an atomic operation (this is a POSIX requirement)". If the program crashes during the write, the old checkpoint stays whole.

The resume logic sits at the start of run():

python
        if resume and state.exists():
            saved = json.loads(state.read_text())
            history = saved["history"]
            if saved["status"] == "complete":
                self.verify()
                return {"status": "complete", "history": history}

If a checkpoint exists, the harness loads its history and continues from there. If the checkpoint says complete, the harness runs the verifier again before it agrees. A saved claim of success must pass a fresh check.

Replace your experiment with these lines:

python
first = fresh(max_steps=1).run()
print("first run:", first["status"], [s["tool"] for s in first["history"]])
second = Harness("lab").run()
print("second run:", second["status"], [s["tool"] for s in second["history"]])

Expected output:

text
first run: budget_exhausted ['read_tasks']
second run: complete ['read_tasks', 'write_report', 'done']

The first run had a budget of one step, so it read the tasks and stopped. The second run loaded that checkpoint, kept the read_tasks step and finished the work without repeating it.

This works because every tool here is safe to repeat, and writing the same report twice gives you the same file. Sending an email or charging a card is different. For those, record an operation ID before the action and check it when you resume, or a retry may do it twice.

Step 9: Run the tests

Run the eight tests from the same folder:

bash
python3 -m unittest -v test_agent_harness.py

On Python 3.14 the output looks like this. The time on the "Ran" line changes from run to run, and older Python versions print shorter test names.

text
test_invalid_task_schema_is_rejected (test_agent_harness.HarnessTests.test_invalid_task_schema_is_rejected) ... ok
test_premature_completion_fails (test_agent_harness.HarnessTests.test_premature_completion_fails) ... ok
test_resume_preserves_previous_action (test_agent_harness.HarnessTests.test_resume_preserves_previous_action) ... ok
test_step_budget_stops_repetition (test_agent_harness.HarnessTests.test_step_budget_stops_repetition) ... ok
test_symlink_file_is_rejected (test_agent_harness.HarnessTests.test_symlink_file_is_rejected) ... ok
test_unknown_tool_is_rejected (test_agent_harness.HarnessTests.test_unknown_tool_is_rejected) ... ok
test_verified_completion (test_agent_harness.HarnessTests.test_verified_completion) ... ok
test_wrong_report_fails_verification (test_agent_harness.HarnessTests.test_wrong_report_fails_verification) ... ok

----------------------------------------------------------------------
Ran 8 tests in 0.007s

OK

Python's unittest module sorts test methods by name before it runs them, so the list does not follow the order in the file. Each test proves one control from this tutorial:

Test What it proves
test_verified_completion The scripted model finishes and the report says Completed tasks: 2
test_unknown_tool_is_rejected A shell tool request raises HarnessError
test_premature_completion_fails done before a report fails verification
test_step_budget_stops_repetition A model stuck on read_tasks ends as budget_exhausted after four steps
test_resume_preserves_previous_action A second run continues a stopped run without repeating steps
test_wrong_report_fails_verification A report that says 99 tasks fails the check
test_invalid_task_schema_is_rejected A task with "done": "yes" is refused
test_symlink_file_is_rejected A symbolic link named report.txt is refused

Run these tests after every change to the harness. When you add a control, write the test that proves it first.

Give a coding agent the same rules

If you ask a coding agent to extend this example, give it the rules in writing. The download includes this AGENTS.md file:

markdown
# Project instructions

This folder is an offline harness teaching example.

- Keep the model function separate from tool execution.
- Keep tools limited to the named local task and report files.
- Do not add a shell tool, remote connector or credential to the example.
- Verify report contents before marking a run complete.
- Run: python -m unittest -v test_agent_harness.py
- Report the actual result and any remaining limitation.

AGENTS.md describes itself as "a simple, open format for guiding coding agents". Codex, Cursor and Gemini CLI read it. Claude Code (2.1.277 or later) reads it by default when no project CLAUDE.md file takes its place. The test command in the file uses python, so change it to python3 or py in your copy if your system needs that.

Remember the difference between the two layers. The file guides the agent, while the Python validation and the tests enforce the rules. The comparison of harness, prompt and context engineering explains why instructions alone are not enough.

Troubleshooting

Most problems in this tutorial come from the working folder or from an old checkpoint. Each Python error message in this table comes from a real run of the example files.

Symptom Cause Fix
python3 is not recognised on Windows Windows installs use other command names Use py or python in every command
ModuleNotFoundError: No module named 'agent_harness' You ran try_it.py from another folder Run it from the folder that holds agent_harness.py
ImportError: Failed to import test module: test_agent_harness You ran the tests from another folder cd into the tutorial folder first
demo-workspace appears in an unexpected place The demo creates it in your current folder Run python3 agent_harness.py from the tutorial folder
HarnessError: Report does not match the source tasks after you edit tasks.json The old checkpoint says complete, but the new tasks no longer match the old report Delete demo-workspace/state.json and run the demo again
The run returns budget_exhausted at once The checkpoint already holds max_steps steps Delete state.json, or create the harness with a larger max_steps
HarnessError: Cannot read valid tasks.json The task file is missing or is not valid JSON Fix the JSON, or delete the file so the demo writes a new one
HarnessError: Tasks must be a list with boolean done fields A task has a done value such as "yes" Use true or false
json.decoder.JSONDecodeError from run() Someone edited state.json by hand and broke it Delete state.json, because the harness trusts its own checkpoint format

When you change the source data, the harness refuses to repeat its earlier "complete". The saved report no longer matches the tasks, so the old success no longer counts.

Common mistakes in a first agent harness

This small harness was built to prevent the mistakes below. Have a look at your own agent and see how many of them it could make.

  • Trusting the model's "done". Without an independent check like verify(), a confident message ends the run. Recheck the real result instead.
  • Letting the model name files or commands. If the model chooses paths or shell commands, one bad output reaches your whole machine. Map each tool to fixed targets in the harness.
  • No hard budget. A model that repeats itself runs until something outside stops it. Put the limit in the loop, where the model cannot change it.
  • Reporting budget_exhausted as success. A stopped run did not finish. Keep the statuses separate.
  • Rules only in the prompt. Instructions guide the model, but only code and tests enforce rules.

What this harness does not do

This example teaches you the shape of a harness, and it leaves out several protections that a production system needs.

The file-name list and the symbolic-link check are application rules, not an operating-system sandbox. They control what this code does. They would not contain a shell tool or untrusted code in the same Python process. The guide to harness engineering tools compares real sandboxes, such as Docker and the Codex CLI sandbox.

The model function here is code that you can trust, and a real model is not. Once a real model is connected, treat every field it sends as untrusted input, as the validation in Step 5 already does.

The checkpoint is one local file for one process. It does not handle two workers writing at once, or actions in other systems. Each of those needs its own design and its own tests.

Extend it

If you would like to keep going, change one component at a time and keep all eight tests passing. Each exercise below points to the companion project that covers it in depth. For more practice, use the 5 Hands-On Harness Engineering Projects PDF in my free resource pack.

  1. Connect a real model. Write an adapter with the scripted_model signature and compare its trace with the scripted one. Project 1 shows the loop with Anthropic and OpenAI models.
  2. Return errors the model can act on. Replace the bare HarnessError for a bad tool call with a message that lists the allowed tools. Project 2 covers tool design and helpful errors.
  3. Add smarter stop rules. Stop when the model repeats the same action twice in a row, and add a time budget. Project 5 builds budgets, repeat detection and a circuit breaker.
  4. Make work survive a crash. Write a progress log next to state.json and re-verify recorded steps on resume. Project 4 adds checkpoints, a resume routine and rollback.
  5. Add a human approval step. Save the proposed report, set the status to awaiting_approval and continue only after a person approves it. Project 9 builds a graph workflow with human approval.
  6. Measure reliability. Run a real model on ten task files and count how often verify() passes. Project 8 builds an evaluation kit for this job.

For an approval step, show the reviewer the exact action, its target and its input. Before you act on an approval, check that the target has not changed since the request. The list of harness engineering projects describes all eleven projects and suggests an order.

Frequently asked questions

For questions about choosing a framework or building your own harness, read how to build and choose a harness.

1. Do I need a framework like LangChain to build my first AI agent?

No. This harness uses only the Python standard library, and building one by hand shows you what a framework would be doing for you. Move to something like LangGraph later, when you need features such as durable checkpoints or a pause for human approval.

2. Do I need an API key or a paid plan for this harness engineering tutorial?

No. The tutorial runs offline with a scripted model, so it costs you nothing. You need a key only when you connect a real hosted model, and a chat subscription will not cover that. OpenAI's help centre says API usage "is billed separately from your ChatGPT subscription".

3. Can I use a local model such as Ollama instead of a paid API?

Yes. Ollama supports tool calling through a local server, so you can write an adapter for it in the same way as for a hosted model. Small local models make more mistakes in the format of their tool calls, which is a good reason to keep the checks from Step 5.

4. How does an agent know when its task is done?

It does not get to decide that alone. The harness checks the real result. In this tutorial, verify() recounts the tasks and compares the expected line with the saved report. If they differ, the run fails, however confident the model sounds.

5. How do you test an agent when the model gives different answers each time?

Test the two halves separately. Use scripted models to test the harness, as the eight tests here do, because the result is the same on every run. Then give the real model many tasks and count how often the check passes.

6. What is the difference between an AI agent and a workflow?

In a workflow, you decide the steps in advance, which Anthropic describes as "predefined code paths". In an agent, the model decides what to do next. The program in this tutorial is a small agent, because the model picks each action and the harness limits which actions exist.

7. How much Python do I need before I build an agent?

You need functions, dictionaries, loops and exceptions, and you should be able to read and write files and JSON. The harness uses those and one class. If you can follow agent_harness.py from top to bottom, you know enough to begin.

8. What is an agent harness?

An agent harness is everything around an AI model that controls its context, its tools and when its work counts as finished. My guide to harness engineering for beginners has the full explanation.

9. How much of an AI agent is the framework, and how much is the loop?

The basic agent is a loop, and a framework is optional code around it. In agent_harness.py, the while loop takes 24 of the 114 lines. The other code covers the scripted model, file access, checks and checkpoints. A graph framework such as LangGraph earns its place when a run needs branches, durable state and a way to resume after failures or pauses.

10. What should a tool return when it finds nothing?

Return a normal result that says nothing matched, because the lookup worked. Keep three cases separate:

  • Nothing matches: Return an empty list and say that the search finished.
  • The name does not exist: Name the unknown value and list the valid ones.
  • The lookup failed: Say what failed and what to try next.

Anthropic's page on handling tool calls says to set is_error when a tool fails or a call is invalid. In this tutorial, an empty task list gives Completed tasks: 0. A missing tasks.json stops the run with HarnessError, which keeps the example short. In your own harness, turn that error into a result the model can act on.

Learn the full system with my book

What you have built here is the skeleton of one harness. I wrote The Harness Engineering Blueprint about the rest of the body, which includes tools, boundaries, memory, checks, loops, graphs and human control. It is my own book, so treat this as the author's recommendation when I say that I believe it is the best book to learn harness engineering.

You can practise each chapter with the eleven projects in the free companion course. The 30-day roadmap shows how the book, the projects and this tutorial fit together. If you learn better from video, I have listed ten courses as well.

Final thoughts

You now have a harness engineering tutorial project that runs, fails when you break it and passes its tests. The six parts in the table at the top are the same parts you will find in much larger agents.

Open the record of a recent run from one of your own agents and look for those six parts. One of them is probably missing. If you have no check like verify(), begin there.

Sources and further reading