Please enable JavaScript to use CodeHS

How to Build an Agent Harness

The agent loop

A large language model can talk, but it cannot act on its own. An agent harness is the code that runs a loop: ask the model to think, execute a tool, and feed the result back. This tutorial builds the simplest possible harness.

Python ~12 min Advanced
The Big Idea

Why a harness?

An LLM is a text predictor. If you ask it “what is the weather in San Francisco?” it can guess a sentence, but it cannot open a browser or call an API. To make the model useful, you wrap it in harness code that gives it tools and runs it in a loop.

The harness is the difference between a chatbot and an agent. It decides:

  • what tools the model can use,
  • how to translate the model's output into a function call,
  • when to stop looping,
  • what to do when a tool fails.

Key idea: the harness is the operating system; the LLM is the CPU. The harness provides memory, tools, and control flow.


CS Minute

Think, act, observe

Most agent harnesses use a ReAct-style loop:

  1. Think: the model looks at the current situation and decides what to do next.
  2. Act: the harness parses that decision and calls a tool.
  3. Observe: the tool returns a result, which is added back to the model's context.

Each pass through the loop is called a step. The loop continues until the model decides it is finished, or until a safety limit like max_steps is reached.


Code

A minimal harness

Below is a tiny but real harness. It defines a list of tools, runs a loop, and uses a fake call_llm function so you can see the control flow without needing an API key.


Interactive

Step through the loop

Click Next step to watch the harness ask, act, and observe. The fake model pretends to call the weather tool, then finishes once it sees the result.

Ready. Click "Next step" to begin.

Your Turn

Check yourself

Why does the harness need max_steps even when the model is supposed to call finish?

Your answer:

Sample answer: A model can get stuck in a loop or keep calling tools forever. max_steps is a guardrail that guarantees the harness stops, even if the model never decides to finish.


Check Yourself

Quick quiz

1. What is the main job of an agent harness?

2. In the loop, what does the dispatch function do?

3. What is the purpose of appending tool results back into messages?

Keep learning

The loop is the skeleton. Next, give the harness a real set of tools and a clean way to call them.

Part of the “How to Build an Agent Harness” series.