← nano-harness.github.io
nano articles · 2026-09-14

Build an Agent Loop in 100 Lines of Python

100 行 Python 手写一个 agent loop

The fastest way to understand what an agent actually is — and what it is not — is to write the loop yourself. Here is the harness-101 F1 minimal agent, taken apart line by line: the message list, the tool dispatch, and the one condition that decides when it stops.

理解 agent 到底是什么(以及不是什么)最快的方式,就是亲手把这个 loop 写出来。 本文把 harness-101 F1 的最小 agent 逐段拆开:消息列表、工具派发,以及那个决定它何时停下来的唯一条件。

01Why write one yourself为什么要亲手写一个

In 2026 the evidence for "small is real" is hard to ignore. Princeton and Stanford's mini-swe-agent — roughly a hundred lines of Python with a single bash tool — scores over 74% on SWE-bench Verified, a benchmark built from real GitHub issues. Run the same model behind a heavy agentic scaffold and the minimal loop matches or beats it; and because there is almost no scaffolding in the way, each new model generation's gains flow straight through to the benchmark score instead of being absorbed by the harness.

2026 年的证据已经很难忽视:Princeton 与 Stanford 的 mini-swe-agent——约一百行 Python、 只挂一个 bash 工具——在 SWE-bench Verified(由真实 GitHub issue 构成的基准)上超过了 74%。同一个模型, 套上重型 agent 脚手架反而跑不赢这个极简 loop;而且因为中间几乎没有脚手架的遮挡,每一次模型代际升级的 红利都会直接传导到跑分上,而不是被马具(harness)自己吃掉。

This is not a verdict against heavy harnesses — it is a division of labor. A minimal loop wins on legibility and on staying out of the model's way. A production harness earns its complexity elsewhere: permission models, sandboxing, audit trails, termination policies, context budgets that keep a twelve-hour session reliable. The mistake is using the heavy thing before you have ever seen the small one run. Write the loop once, and every harness feature you meet afterwards reads as an answer to a problem you have personally watched happen.

这并不是对重型马具的宣判,而是分工。极简 loop 胜在可读、胜在不挡模型的路;生产级马具的复杂度则花在 别的地方:权限模型、沙箱、审计、终止策略、让十二小时长会话依然可靠的上下文预算。真正的错误是在从未 见过小的跑起来之前就去用大的。亲手写一遍 loop,之后你遇到的每一个 harness 特性,都会读成「一个你 亲眼见过的问题的答案」。

The claim this article makes concrete: an agent is a state machine, not magic. Call the model → parse the tool call → execute the tool → feed the result back into context → call the model again, until the model stops asking for tools. Everything else is engineering around that loop.
本文要落实的一句话:agent 是一台状态机,不是魔法。调用模型 → 解析工具调用 → 执行工具 → 把结果塞回上下文 → 再次调用模型,直到模型不再请求工具为止。其余的一切都是围绕这个 loop 的工程。

02The whole state machine, in one formula整台状态机,一行公式

messages → model → (text ? done : tool_call → execute → append result → messages)
messages → 模型 →(返回文本?结束 : 工具调用 → 执行 → 追加结果 → messages)

Three ideas carry the entire implementation, and we will take them in order:

整个实现只靠三个想法,我们逐个拆:

  1. The message list is the whole state. There is no hidden memory — the conversation you send is the agent's mind.
  2. 消息列表就是全部状态。没有隐藏的记忆——你发出去的对话历史就是 agent 的大脑。
  3. Tools are just functions plus a description. The model reads the description, decides to call, and your code dispatches to a plain Python function.
  4. 工具就是函数加一段描述。模型读描述、决定调用,你的代码把它派发到一个普通的 Python 函数。
  5. Termination is one check. When the model answers with text instead of a tool call, the loop is over.
  6. 终止条件只有一次判断。当模型返回文本而不是工具调用时,循环结束。

The code below is a complete reference implementation. Try filling in the four main pieces yourself, then use this walkthrough to compare your understanding of the message list, tool dispatch, and termination.

下面是一份完整的参考实现。建议先亲手补全四个主要部分,再沿着本文对照理解消息列表、工具派发和终止条件。

03One tool, honestly described一个被认真描述的工具

The tool list is the agent's entire interface with the world. Note what the schema carries: not just a name and parameters, but a description that is really a prompt — it tells the model the command must be read-only. You will see in F2 how much depends on sentences like that.

工具列表就是 agent 与世界的全部接口。注意 schema 里装了什么:不只是名字和参数,还有一段 本质上是提示词的描述——它告诉模型命令必须是只读的。到 F2 你会看到,这样的句子值多少行代码。

import os, subprocess
from anthropic import Anthropic

client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

TOOLS = [{
    "name": "run_command",
    "description": "Run a command in the local shell and return stdout. "
                     "The command must be read-only (e.g. ping, cat, ls). "
                     "No write operations.",
    "input_schema": {
        "type": "object",
        "properties": {
            "cmd": {"type": "string", "description": "the shell command to run"}
        },
        "required": ["cmd"],
    },
}]

And the tool itself is deliberately boring — ten lines, with two quiet acts of harness engineering: a timeout so a hung command cannot hang the agent, and an error returned as a normal string so the model reads its own failure and corrects course, instead of the loop crashing on an exception.

工具本身刻意无聊——十来行,却藏了两处不动声色的 harness engineering:超时,让卡死的命令 无法拖死 agent;错误以普通字符串返回,让模型读到自己的失败并自我纠正,而不是让异常 把整个 loop 砸停。

def run_command(cmd: str) -> str:
    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True, text=True, timeout=10
        )
        return result.stdout or result.stderr
    except Exception as e:
        return f"command failed: {e}"

04The loop: dispatch and termination循环本体:派发与终止

Here is the heart of it. Read it once slowly — there is nothing else.

核心全在这里。慢慢读一遍——除此之外没有别的了。

def agent_loop(task: str, max_steps: int = 10):
    messages = [{"role": "user", "content": task}]   # the whole state
    for step in range(max_steps):               # the safety bound
        response = client.messages.create(
            model="claude-3-5-sonnet-latest",
            max_tokens=1024,
            messages=messages,
            tools=TOOLS,
        )

        # termination: the model answered in text, not tool calls
        if response.stop_reason != "tool_use":
            print(response.content[0].text)
            return

        # dispatch: find the tool_use block, run the matching function
        tool_use = next((b for b in response.content if b.type == "tool_use"), None)
        if not tool_use:
            return
        result = run_command(tool_use.input["cmd"])

        # feedback: append BOTH the call and its result to the state
        messages.append({"role": "assistant", "content": response.content})
        messages.append({
            "role": "user",
            "content": [{
                "type": "tool_result",
                "tool_use_id": tool_use.id,
                "content": result,
            }],
        })

Three details worth staring at

三个值得盯着看的细节

  • The message list is append-only memory. Both the assistant's tool call and the tool's result go back into messages. The next model call sees the full history — that is all "memory" an agent has. When courses later talk about context budgeting and compression, this list is the thing being budgeted and compressed.
  • 消息列表是只追加的记忆。assistant 的工具调用和工具返回的结果都要塞回 messages,下一次模型调用看到完整历史——这就是 agent 全部的「记忆」。后面课程讲上下文预算与压缩时,被预算、被压缩的就是这个列表。
  • Dispatch is a lookup, not magic. The model emits a structured tool_use block with a name and JSON input; your code finds the block and calls the Python function of the same name. There is no framework between the model's decision and your function — you can print it, log it, or refuse it.
  • 派发只是一次查表,不是魔法。模型吐出一个带名字和 JSON 参数的结构化 tool_use 块,你的代码找到这个块、调用同名 Python 函数。模型的决定和你的函数之间没有任何框架——你可以打印它、记录它,或者拒绝它。
  • Termination has two layers, and you need both. The primary exit is stop_reason != "tool_use" — the model declares itself done by answering in prose. The secondary exit is max_steps — the harness declaring the agent stuck. F4 exists because the first condition alone is not trustworthy; but you should see a loop without it first.
  • 终止有两层,缺一不可。主出口是 stop_reason != "tool_use"——模型用散文回答,即宣布完工;兜底出口是 max_steps——马具宣布 agent 卡住了。F4 之所以存在,是因为光靠第一个条件并不可信;但你应该先看一个没有它的 loop 长什么样。

Wire it up with agent_loop("check this machine's network latency to baidu.com") and watch: the model calls run_command with ping -c 4 baidu.com, reads the output, and answers in prose. Three steps, two tool calls, one loop. The magic is gone — and that is the point.

用 agent_loop("帮我查一下本机到 baidu.com 的网络延迟") 跑起来看:模型用 ping -c 4 baidu.com 调用 run_command,读输出,然后用散文回答。三步、两次工具 调用、一个 loop。魔法消失了——这正是目的。

05What this loop deliberately doesn't do这个 loop 刻意没做的事

Every line missing from these hundred is a chapter of harness engineering waiting for you: the tool does no parameter validation and the description is the only thing stopping a write (F2, F6); nothing detects an agent calling the same tool forever (F4); nothing watches the message list grow until the model degrades (F3, F13); and there is no trace to evaluate afterwards (F12). The minimal loop is not the destination — it is the instrument panel that makes every one of those concerns visible. This is also the honest answer to "if 100 lines beats the heavy harness, why does the heavy harness exist": benchmarks are single tasks with a grader; production is long sessions, real credentials, and irreversible actions. Reliability, safety, and auditability are exactly what the extra lines buy.

这一百行里缺的每一行,都是 harness engineering 等着你的一章:工具不做参数校验,阻止写操作的只有 描述里的那句话(F2、F6);没有东西检测 agent 无限重复调用同一个工具(F4);没有东西盯着消息列表 一路膨胀直到模型开始退化(F3、F13);跑完也没有可评估的 trace(F12)。极简 loop 不是终点——它是 一块仪表盘,让上面每一个问题都变得可见。这也诚实回答了「既然 100 行能赢重型马具,重型马具为什么 存在」:基准测试是带评分器的单任务;生产环境是长会话、真实凭据和不可逆操作。可靠性、安全性、可审计 性,正是那些多出来的行数买到的东西。

06Where to go next接下来去哪

Fill in the four TODOs in the starter yourself — an honest evening's work — then keep going with the Harness 12-Factor. Each factor is one idea, and each idea is anchored to a single file of running code in the nano series: concepts you read in an evening, code you take one file at a time.

先亲手把 starter 里的四个 TODO 填完——一个晚上诚实的功夫——然后沿着 Harness 12-Factor 继续。每个因素 是一个想法,每个想法都锚定到 nano 系列里一个正在运行的源码文件:概念一晚读完,代码按文件攻破。

Continue with running code
继续阅读运行中的代码

Explore nano-agent for a complete implementation, or browse the other nano projects for orchestration and practical engineering tools.

探索 nano-agent 的完整实现,或浏览其他 nano 项目的编排能力与实用工程工具。