编程-学习-思考

s01:Agent Loop——一个循环就够了

s01:Agent Loop——一个循环就够了

“一个循环 + Bash,就是一个 Agent。”

问题

你给大模型提了一个问题:”帮我读一下目录下有哪些文件,然后执行 test.py。”

模型输出了一条 bash 命令。但输出完就停了——它不会自己跑,也不会看到结果后继续推理。

你可以手动把命令复制到终端执行,再把输出粘贴回对话框。模型看到结果,接着生成下一条命令。你再跑,再贴……

每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。

解决方案

一个 while True 循环:模型调用工具就继续,不调用就停。整个过程只有两个信号:

信号 含义 循环动作
stop_reason == "tool_use" 模型说”我要用工具” 执行工具 → 结果喂回去 → 继续
stop_reason != "tool_use" 模型说”我做完了” 退出循环

工作原理

把过程翻译成代码,分五步:

第 1 步:把用户的问题作为第一条消息。

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

第 2 步:将消息和工具定义一起发给 LLM。

response = client.messages.create(
    model=MODEL, system=SYSTEM, messages=messages,
    tools=TOOLS, max_tokens=8000,
)

第 3 步:追加模型回答,检查它是否调了工具。没调 → 结束。

messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
    return

第 4 步:执行模型要求的工具,收集结果。

results = []
for block in response.content:
    if block.type == "tool_use":
        output = run_bash(block.input["command"])
        results.append({
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": output,
        })

第 5 步:把工具结果作为新消息追加,回到第 2 步。

messages.append({"role": "user", "content": results})

组装为一个完整函数——不到 30 行:

def agent_loop(messages):
    while True:
        response = client.messages.create(
            model=MODEL, system=SYSTEM, messages=messages,
            tools=TOOLS, max_tokens=8000,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":
            return

        results = []
        for block in response.content:
            if block.type == "tool_use":
                output = run_bash(block.input["command"])
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": output,
                })
        messages.append({"role": "user", "content": results})

这就是最小可运行的 agent harness 内核。它不是智能本身,而是让模型能持续行动的最小运行框架。

后面 19 个章节都在这个循环上叠加机制。循环本身始终不变。

关键理解

模型负责决策,harness 负责执行。 模型决定调不调工具、调哪个;harness 只是”调了就执行,结果喂回去”。不要混淆这层边界。

试一下

pip install -r requirements.txt
cp .env.example .env
# 编辑 .env,填入 API key
python s01_agent_loop/code.py

试试这些 prompt:

  1. Create a file called hello.py that prints "Hello, World!"
  2. List all Python files in this directory
  3. What is the current git branch?

观察重点:模型什么时候调用工具(循环继续),什么时候不调用(循环结束)?

接下来

s02 —— 给它 5 个真正的工具(read、write、edit、glob),会发生什么?模型会不会一次调用多个工具?