← BACK TO WRITING

Agents From First Principles

Agents From First Principles Cover

Introduction

The core idea behind an AI agent is fairly simple. An agent is just an LLM that is wrapped in a piece of software called the harness, which takes the actions outputted by the LLM, executes them, and feeds the results back to the model. This allows the model to take action, observe the results of its action, and continue to iterate until the task at hand is complete.

These "actions" that LLMs choose to make are called tool calls. Tools are essentially functions the harness exposes to the model, described by a name, a description, and an input schema. The surrounding harness reads the LLM's stream of output tokens, extracts the structured tool call it generates, and executes it. Once the execution of the tool call finishes, the harness sends the tool result, or observation, back into the conversation for the LLM to read.

This whole process loops until a stop condition is met. In most harnesses, the main stop condition is simply a response from the model that contains no tool calls. This is because there is nothing for the harness to execute if the model isn't asking for an action, so its reply is treated as a final response. Developers can also define deterministic boundaries in the harness as stop conditions, such as a maximum number of reasoning or tool call cycles, deterministic task completion checks with test suites or commands, token usage limits, and more.

The core agent loop: a user task goes to a model call. If the model's response has no tool calls, the loop is done. Otherwise the harness runs the requested tool, appends the tool result to the message history, and calls the model again. A dashed path shows the harness also stopping the loop when a limit such as a maximum number of steps is reached. User task Model call Full history in, next action out No tool calls Done Tool call(s) Harness runs the tool Executes the requested function Limit reached max steps, tokens, … Tool result (observation) appended to message history

The core agent loop. Every tool result is appended to the message history before the next model call, and the loop ends when the model replies without asking for a tool. The dashed path is a stop condition the harness enforces on its own, like a maximum number of steps.

With these key ideas in mind, it's important to note that the model itself never executes anything. It only produces special text used to describe the action it wants the harness to execute, which the harness reads and executes. Think of the model as the brain, and the harness as the body of an AI agent. It's also important to remember that each call to the model is independent, so the model doesn't have any memory of previous calls. To work around this, the harness sends the full message history (the task, every tool call, and every result so far) with each call. This history effectively acts as the model's working memory about the task so far.

Building an Agent

Let's build a very simple agent from scratch to further solidify these core ideas in code. I'll be using Python with the official Anthropic SDK, and Claude Opus 5.5 as the model.

The Setup

To start off, we'll simply get the Anthropic SDK set up and send in a request without building any of the harness, just to see how the model responds as a baseline.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-opus-5-5"

task = (
    "Which of my blog posts discuss attention? Reply with one line per post: "
    "the post's title, then one sentence on what it says about attention."
)

response = client.messages.create(
    model=MODEL,
    max_tokens=16000,
    messages=[{"role": "user", "content": task}],
)

print(response.stop_reason)
for block in response.content:
    print(block.type)
print("".join(block.text for block in response.content if block.type == "text"))

Running this gives the output below:

end_turn
thinking
text
I don't have access to your blog, so I can't see which posts mention attention. If you share the posts (pasted text, titles with excerpts, or an export file), I'll go through them and give you one line per relevant post: the title, then a sentence on what it says about attention.

Also, which kind of attention do you mean: the machine-learning mechanism (as in transformers), human attention and focus, or both? That will help me catch the right posts.

As expected, the model alone fails at the task. It needs a harness to read files on my machine. Let's go ahead and build the harness functionality, starting with the functions that will be executed upon a tool call.

from pathlib import Path

REPO = Path(".")  # run from the root of the repo you want to explore

def list_files(path: str) -> str:
    entries = sorted(
        p.name + ("/" if p.is_dir() else "")
        for p in (REPO / path).iterdir()
        if not p.name.startswith(".")
    )
    return "\n".join(entries)

def read_file(path: str) -> str:
    return (REPO / path).read_text(encoding="utf-8")

Describing Tools

With the functions for each tool call written, we now need to describe the available tools so the model knows what each one does and when each one should be called. This part is pretty straightforward. We just need to give it an accurate name and description, as well as an input schema that tells the model what parameters, data types, and arguments a tool or function expects.

tools = [
    {
        "name": "list_files",
        "description": (
            "List the files and folders in a directory of the repository. "
            "Folder names end with '/'. Call this before read_file to find "
            "out which files exist."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Directory relative to the repo root. Use '.' for the root.",
                },
            },
            "required": ["path"],
        },
    },
    {
        "name": "read_file",
        "description": (
            "Read the full contents of a file in the repository. Call this "
            "after list_files when you need to see what a specific file contains."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path relative to the repo root, e.g. 'writing.html'.",
                },
            },
            "required": ["path"],
        },
    },
]

Next we package the prompt into a 'messages' list, which acts as the working memory or current message history for the request being made.

messages = [{"role": "user", "content": task}]

response = client.messages.create(
    model=MODEL,
    max_tokens=16000,
    tools=tools,
    messages=messages,
)

Parsing and Executing Tool Calls

Now that the harness has made the request, it needs to read the response and act on it (depending on the type of response).

print(response.stop_reason)

tool_calls = [block for block in response.content if block.type == "tool_use"]
for call in tool_calls:
    print(call.id, call.name, call.input)

Let's take a look at the response's stop reason, which shows the model chose to invoke one or more tools, and the tool call itself:

tool_use
toolu_0192NqN1SzsRREs2NEjHzro1 list_files {'path': '.'}

Now that the model is provided with tool definitions, it made a list_files tool call to complete the task we gave it. The harness now needs to be able to dynamically execute the tool calls made by the model, pass the parameters requested by the model for each call, and return each output wrapped in a 'tool_result' block. Let's write a small function for this with exception handling included.

tool_functions = {"list_files": list_files, "read_file": read_file}

def run_tool(call):
    try:
        function = tool_functions[call.name]
        output = function(**call.input)
        return {"type": "tool_result", "tool_use_id": call.id, "content": output}
    except Exception as e:
        return {
            "type": "tool_result",
            "tool_use_id": call.id,
            "content": f"Error: {e}",
            "is_error": True,
        }

Notice how tool errors are returned to the model rather than being raised. This is because the model needs to be able to read the error associated with the tool call it made and correct itself.

Feeding Results Back

With our run_tool function written out, we can now append the output of the tool calls requested by the model onto the message history. A request is then made again with the new message history, and the process repeats until a stop condition is met.

messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": [run_tool(call) for call in tool_calls]})

response = client.messages.create(
    model=MODEL,
    max_tokens=16000,
    tools=tools,
    messages=messages,
)

Knowing When to Stop

Once a stop condition is met, the harness breaks out of the loop. The loop continues only while the model asks for a tool (tool_use); any other stop reason ends it. For example, end_turn when the model has finished, max_tokens when its output was cut off by the token budget, or refusal when the model refuses to work on the task. The code after the loop reports which stop reason happened.

messages = [{"role": "user", "content": task}]

while True:
    response = client.messages.create(
        model=MODEL,
        max_tokens=16000,
        tools=tools,
        messages=messages,
    )
    messages.append({"role": "assistant", "content": response.content})

    if response.stop_reason != "tool_use":
        break

    tool_calls = [block for block in response.content if block.type == "tool_use"]
    messages.append({"role": "user", "content": [run_tool(call) for call in tool_calls]})

if response.stop_reason == "end_turn":
    print("".join(block.text for block in response.content if block.type == "text"))
else:
    print(f"Stopped early: {response.stop_reason}")

Notice how we loop through all blocks and process those with the type 'tool_use'. This is because one response can contain several tool calls, so we need to run them all and return all results in one user message. It's also important to note that we package the outputs of tool calls as 'user' responses because the API only has assistant and user roles. Anything outside the text generated by the model should come from the user role.

The Full Agent

Now let's put it all together. This is the final code and output for our rudimentary agent, packaged with a fixed prompt and two exploratory tools.

ShowHide the full agent code
from pathlib import Path

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-opus-5-5"
REPO = Path(".")  # run from the root of the repo you want to explore


def list_files(path: str) -> str:
    entries = sorted(
        p.name + ("/" if p.is_dir() else "")
        for p in (REPO / path).iterdir()
        if not p.name.startswith(".")
    )
    return "\n".join(entries)


def read_file(path: str) -> str:
    return (REPO / path).read_text(encoding="utf-8")


tools = [
    {
        "name": "list_files",
        "description": (
            "List the files and folders in a directory of the repository. "
            "Folder names end with '/'. Call this before read_file to find "
            "out which files exist."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Directory relative to the repo root. Use '.' for the root.",
                },
            },
            "required": ["path"],
        },
    },
    {
        "name": "read_file",
        "description": (
            "Read the full contents of a file in the repository. Call this "
            "after list_files when you need to see what a specific file contains."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path relative to the repo root, e.g. 'writing.html'.",
                },
            },
            "required": ["path"],
        },
    },
]

tool_functions = {"list_files": list_files, "read_file": read_file}


def run_tool(call):
    try:
        function = tool_functions[call.name]
        output = function(**call.input)
        return {"type": "tool_result", "tool_use_id": call.id, "content": output}
    except Exception as e:
        return {
            "type": "tool_result",
            "tool_use_id": call.id,
            "content": f"Error: {e}",
            "is_error": True,
        }


def run_agent(task: str) -> str:
    messages = [{"role": "user", "content": task}]

    while True:
        response = client.messages.create(
            model=MODEL,
            max_tokens=16000,
            tools=tools,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":
            break

        tool_calls = [block for block in response.content if block.type == "tool_use"]
        messages.append({"role": "user", "content": [run_tool(call) for call in tool_calls]})

    if response.stop_reason != "end_turn":
        return f"Stopped early: {response.stop_reason}"
    return "".join(block.text for block in response.content if block.type == "text")


if __name__ == "__main__":
    task = (
        "Which of my blog posts discuss attention? Reply with one line per post: "
        "the post's title, then one sentence on what it says about attention."
    )
    print(run_agent(task))
ShowHide the agent's output
All three of your posts discuss attention; the ACL one only mentions it briefly.

**Transformers: The Architecture Behind Modern LLMs** — Calls attention the most important idea in the transformer and explains how it works: queries, keys and values, the four steps (score, scale, softmax, blend), the causal mask, and multi-head attention.

**Inside Frontier LLMs: What Changed Since the Transformer** — Covers "efficient attention" as the fix for a KV cache that keeps growing, comparing shrinking the cache (GQA, MQA, MLA), skipping tokens (sparse attention), and replacing most attention layers with linear ones (Gated DeltaNet hybrids).

**My ACL 2025 Experience** — Mentions it once, in a summary of another team's paper: steering sparse autoencoder latents in LLaMA controls its RAG behavior by changing where retrieval heads attend, either toward documents or toward refusal tokens.

Where It Breaks

With the key ideas now established in code, let's explore situations where this system breaks, and what production harnesses add to handle such issues.

Infinite Loops

Rudimentary agents like the one we just built are prone to entering infinite loops. This occurs when the agent keeps calling tools. For example, it could be repeatedly re-reading the same file, retrying a failed call with the same arguments, or exploring forever and never deciding that it's done. This happens because nothing in the loop ends it, except of course the model stating that it's done.

The minimal fix is to simply introduce a hard cap on the number of steps allowed, or even stop the current run when the model repeats identical calls too many times. Production harnesses handle this by introducing more advanced budgets and limits such as step caps, token budgets, real time limits, loop detection, and allowance of run interruption by users.

Hallucinated Tool Arguments

Models may also call tools using arguments that look right, but are completely hallucinated. For example, a model could pass a hallucinated path to the 'read_file' tool we defined earlier, a value of the wrong type, or miss a required field. It could even hallucinate a tool name that doesn't exist. This happens simply because of how LLMs are inherently built and trained. Sometimes language models can just go down the path of predicting plausible arguments rather than double checking them against anything.

Now this happens much less frequently with modern frontier models, but incorporating simple deterministic boundaries to handle this case doesn't hurt. This includes validating inputs at the harness level before running the tool, and returning a specific error as a result for the model to read it and self-correct. Production harnesses add validation and recovery, including schema validation, strict tool inputs via constrained decoding, structured error results, and retries that feed errors back to the model.

Context Growth

Since requests compound every previous message, the issue of context rot grows as every new request is made. On long-running tasks, models experience a sudden decline in output quality, or requests simply fail due to a breach of context window size.

A basic fix would be to truncate large tool outputs and add parameters to tools like 'offset' and 'limit' so the model can read a file in pieces. Production harnesses do this, while also incorporating context management. Context management is an entire topic in itself, but its main ideas include tool output truncation, clearing old tool results, conversation compaction, subagents that return short summaries, and more.

Prompt Injection

Since the model perceives tasks and the contents of tool results as just text in its context, there is a soft and unreliable boundary between a piece of text that can be trusted and one that can't. So if an agent reads a file containing a line like "ignore all previous instructions and do...", it may end up treating it as an instruction it should follow.

A basic fix for this would be to add a user approval requirement for every tool that changes something. This doesn't exactly stop a model from being fooled, but it limits what a fooled model can do. Most production harnesses nowadays come with an auto-approval mode, where a second model reviews each risky action before it runs, rather than the user. Prompt injections can't easily fool this second model, since it only sees the user's messages and the proposed tool calls. It does not see tool results or any other text produced by the agent.

What the Harness Adds

Now that we've covered some basic additions that harnesses add to mitigate certain basic issues, let's dive a bit deeper into what else harnesses wrap around models to create a well-functioning agent.

Different harnesses are designed for different purposes, so harnesses need a way to relay information to the model such as context on the purpose of the harness, expected behaviors, the role or identity of the agent, environmental context, and more. This is done by placing a system prompt at the front of the model's context window. Harnesses can also position additional information supplied from the user into the model's context window, typically in the form of project instruction files. A popular example of this is the CLAUDE.md file in Claude Code.

The agent we built above was packaged only with read-only tools; production harnesses give models more tools that allow the model to actually act, such as file edit tools, shell command execution, search, web page fetching, and more. Production harnesses also offer support for model context protocol (MCP) usage for plugging in external tools. MCPs allow an external platform's server to essentially advertise its tools, so the harness can pass them to the model in the same format as the built-in tools, allowing agents to interact with external platforms. Production harnesses also include sandboxing, which places operating-system level limits on which files and network hosts a command can reach.

Keeping work organized in a way that is optimal for a model's context window is critical, especially for long running tasks. Production harnesses assist with this by including planning modes and todo list tools. It's also important to note that tool calls are typically run in parallel by harnesses, allowing wall clock time to be cut down, even though the core agent loop runs a response's tool calls one after another.

There are plenty more complex systems that are integrated into harnesses with the goal of accurate responses and token-efficient runs kept in mind that I'll cover in my next post, but these are the basic ideas to understand for now.

Closing

In short, an agent is simply a language model with a harness wrapped around it. Think of the model as the brain, and the harness as the body. Without the surrounding harness, the model can't take action. Without the inner model, the harness can't intelligently convert your natural language prompt into a series of complex tasks to be completed.

Harnesses expose the functionality they are capable of (the tools it offers) to the model, so the model can pick and choose which tools to run and with which parameters to complete the task at hand. Harnesses solve complex problems associated with the inherent nature behind how large language models are designed, and are constantly adapting to the progressive frontier of model capabilities.

Understanding these core ideas is crucial to understanding what an agent is. In the next post, I'll cover more advanced harness engineering topics.