Learn Claude Code · 大白话教程
01
完整源码 · 36 处注解

一个循环就够了Agent Loop

一个工具 + 一个循环 = 一个 Agent

解决什么问题 · 模型只会说话不会动手。要让它干活,你得给它一条「行动—观察—再行动」的回路。这一章用 40 行左右把回路写出来,后面每一章都是往它外面加东西。

思路

  1. 把「有一个 bash 工具」这件事,用 JSON Schema 告诉模型;
  2. 发请求,拿回复;回复里除了文字,还可能有 tool_use(模型说:帮我执行这个);
  3. 你执行完,把结果包成 tool_result 塞回 messages;
  4. 再发一次请求,模型看到结果继续决策——直到它不再要工具。
s01_agent_loop/code.py · L1–153 GitHub 原文 ↗
1#!/usr/bin/env python3
2"""
3s01_agent_loop.py - The Agent Loop
4 
5The entire secret of an AI coding agent in one pattern:
L1–5

整本书的起点就这一句:AI 编程 Agent 的秘密是一个循环,不是一堆 if-else。

6 
7 while True:
8 response = LLM(messages, tools)
9 if response contains no tool_use:
10 break
11 execute tools
12 append results
L6–12

把这四行背下来:调模型 → 看有没有工具调用 → 执行 → 把结果塞回去。

13 
14 +----------+ +-------+ +---------+
15 | User | ---> | LLM | ---> | Tool |
16 | prompt | | | | execute |
17 +----------+ +---+---+ +----+----+
18 ^ |
19 | tool_result |
20 +---------------+
21 (loop continues)
L13–21

注意图里的箭头是闭环的:工具结果回到模型,模型再决定下一步。这是 Agent 和「一问一答」的本质区别。

22 
23This is the core loop: feed tool results back to the model
24until the model decides to stop. Later chapters add policy,
L22–24

停止条件只有一个:模型不再要求用工具。代码本身不判断「任务完成没」——这是 s17 才补的洞。

25hooks, and lifecycle controls around it.
26 
27Usage:
28 pip install anthropic python-dotenv
29 ANTHROPIC_API_KEY=... python s01_agent_loop/code.py
30"""
31 
32import os
33import subprocess
L25–33

只用了两个标准库:os 读环境变量,subprocess 执行 shell 命令。没有框架。

34 
35try:
36 import readline
37 # #143 UTF-8 backspace fix for macOS libedit
38 readline.parse_and_bind('set bind-tty-special-chars off')
39 readline.parse_and_bind('set input-meta on')
40 readline.parse_and_bind('set output-meta on')
41 readline.parse_and_bind('set convert-meta off')
42except ImportError:
L34–42

readline 只是为了输入体验(macOS 终端退格不乱码)。整段删掉,程序照样跑。

43 pass
44 
45from anthropic import Anthropic
46from dotenv import load_dotenv
L43–46

dotenv 读同目录的 .env,省得每次开终端都 export 一遍。

47 
48load_dotenv(override=True)
L47–48

override=True:.env 里的值覆盖 shell 里同名的。不加的话,你改了 .env 却发现不生效。

49 
50if os.getenv("ANTHROPIC_BASE_URL"):
51 os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
L49–51

走中转时 SDK 可能优先用 AUTH_TOKEN,导致「配了 key 却 401」;删掉它,只认 API_KEY。

52 
53client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
L52–53

base_url 为空走官方;填了就是你兼容 Anthropic 协议的地址,协议不兼容也跑不通。

54MODEL = os.environ["MODEL_ID"]
L54–54

模型名从环境变量来。教程里的示例名不保证你能用,按自己账号的权限填。

55 
56ENVIRONMENT_PROMPT = (
L55–56

先交代运行环境:Windows 上的 bash 其实是 cmd.exe,不提醒就会写出 ls、rm -rf。

57 "Windows: the bash tool runs through cmd.exe; use cmd.exe syntax, not Unix "
58 "Bash or PowerShell syntax"
59 if os.name == "nt"
60 else "Unix-like: the bash tool runs the system shell"
61)
62SYSTEM = (
L57–62

system prompt 就三件事:你是谁、你在哪个目录、你怎么干活。getcwd() 让相对路径有基准。

63 f"You are a coding agent at {os.getcwd()}. Environment: {ENVIRONMENT_PROMPT}. "
64 "Use bash to solve tasks. Act, don't explain."
L63–64

这半句很关键。模型天生爱解释,这句话把它往「先动手」推。删掉它,回答会长很多。

65)
66 
67# -- Tool definition: just bash --
68TOOLS = [{
69 "name": "bash",
L65–69

工具定义就是一份 JSON Schema:名字、描述、参数。模型只能通过这份描述知道「有这么个工具、怎么调」。

70 "description": "Run a shell command.",
71 "input_schema": {
72 "type": "object",
73 "properties": {"command": {"type": "string"}},
74 "required": ["command"],
L70–74

required 别漏。不写的话,模型偶尔会传个空对象过来,代码就 KeyError 了。

75 },
76}]
77 
78 
79# -- Tool execution --
80def run_bash(command: str) -> str:
L75–80

工具本体就是一个普通 Python 函数:输入字符串,输出字符串。没有基类、没有装饰器。

81 dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]
L81–81

这一版没有权限系统,只有一个最粗糙的黑名单。先能跑起来,权限是 s03 的事。

82 if any(d in command for d in dangerous):
83 return "Error: Dangerous command blocked"
L82–83

被拦截时返回的是一句话,不是抛异常。工具失败也要变成「结果」让模型看到,它才知道换条路。

84 try:
85 r = subprocess.run(command, shell=True, cwd=os.getcwd(),
L84–85

shell=True 才能用管道和重定向;cwd 固定工作目录;timeout=120 防止一条命令把整个会话挂死。

86 capture_output=True, text=True, errors="replace", timeout=120)
87 out = (r.stdout + r.stderr).strip()
L86–87

stdout 和 stderr 直接合并。模型不关心这是正常输出还是报错,它要的是「到底发生了什么」。

88 return out[:50000] if out else "(no output)"
L88–88

截断 + 空输出兜底。不截断的话,一条 dmesg 就能把上下文撑爆(s08 专门解决这个)。

89 except subprocess.TimeoutExpired:
L89–89

超时、文件找不到、系统错误,全都翻译成人话返回。别让 Python 堆栈打断循环。

90 return "Error: Timeout (120s)"
91 except (FileNotFoundError, OSError) as e:
92 return f"Error: {e}"
93 
94 
95# -- The core pattern: a while loop that calls tools until the model stops --
96def agent_loop(messages: list):
L90–96

核心循环。messages 是传引用:这个函数会往里 append,调用方拿到的就是同一份历史。

97 while True:
98 response = client.messages.create(
99 model=MODEL, system=SYSTEM, messages=messages,
100 tools=TOOLS, max_tokens=8000,
L97–100

每次请求都带完整历史和工具表。模型是无状态的,「记忆」全靠你每次重新传。

101 )
102 
103 # Append assistant turn
104 messages.append({"role": "assistant", "content": response.content})
L101–104

先把模型这轮说的话原样存进历史,包括 tool_use 块。后面要靠它的 id 把结果配对回去。

105 
106 # If the model didn't call a tool, we're done
107 tool_calls = [
108 block for block in response.content if block.type == "tool_use"
109 ]
110 if not tool_calls:
L105–110

没有工具调用 = 模型认为答完了 = 退出循环。这里的「完成」完全由模型自己声明。

111 return
112 
113 # Execute each tool call, collect results
114 results = []
115 for block in tool_calls:
L111–115

一轮里模型可能要调多个工具,一个个执行。这里先 for 循环,s02 换成查表分发。

116 print(f"\033[33m$ {block.input['command']}\033[0m")
117 output = run_bash(block.input["command"])
L116–117

block.input 就是模型给的参数,SDK 已经帮你解析成 dict 了。

118 print(output[:200])
119 results.append({
120 "type": "tool_result",
121 "tool_use_id": block.id,
L118–121

这个 id 必须原样回传。模型靠它把「我请求的调用」和「你给我的结果」对上号,对不上直接报错。

122 "content": output,
123 })
124 
125 # Feed tool results back, loop continues
126 messages.append({"role": "user", "content": results})
L122–126

tool_result 以 user 身份回填——Anthropic 协议就是这么规定的。

127 
128 
129# -- Entry point --
130if __name__ == "__main__":
131 print("s01: Agent Loop")
132 print("Enter a question, press Enter to send. Type q to quit.\n")
133 
134 history = []
L127–134

整场对话只有这一份历史,循环内外共用。这就是它能记住上一轮干了什么的原因。

135 while True:
136 try:
137 # \001/\002 tell Readline the ANSI escapes have zero display width.
138 query = input("\001\033[36m\002s01 >> \001\033[0m\002")
L135–138

一个极简 REPL:一行输入 = 一轮对话。q 退出。

139 except (EOFError, KeyboardInterrupt):
140 break
141 if not query.strip():
142 continue
143 if query.strip().lower() in ("q", "exit"):
L139–143

strip() 先去掉首尾空格,避免用户多敲一个空格就匹配不上。

144 break
145 history.append({"role": "user", "content": query})
146 agent_loop(history)
L144–146

每次输入都接着同一份 history 继续跑,而不是新开一段。

147 # Print the model's final text response
148 response_content = history[-1]["content"]
149 if isinstance(response_content, list):
L147–149

循环结束后,最后一条 assistant 消息里可能有好几个内容块,只打印文字。

150 for block in response_content:
151 if getattr(block, "type", None) == "text":
152 print(block.text)
153 print()

记住这几条

四步循环

问模型 → 执行工具 → 回填结果 → 再问。本课程后面每一章都沿用这个骨架。

停止 = 模型不再要工具

代码不判断任务完成度,这是 s17 Goal Loop 要补的洞。

模型无状态

messages 就是它的全部记忆,每轮完整传回,所以上下文管理(s08)才重要。

错误也是结果

工具失败返回字符串而不是抛异常,模型才能读到并自己纠错。

容易踩的坑

  • 回填 tool_result 时漏了 tool_use_id,或 id 对不上,API 会直接 400。
  • 忘了设 timeout 和输出截断,一条 `yes` 就能让会话一直转下去。
  • 把 tool_result 塞进 assistant 消息里,协议不认——它必须放在 user 消息中。

动手改一改

步骤:只改 s01 的 SYSTEM,删掉 `Act, don't explain.`;启动 `python s01_agent_loop/code.py`,问「看看这个目录有什么」,看完把这句话加回。确定性验收:`git diff` 只包含 SYSTEM 这一行改动,程序能进入 REPL,且本轮对话没有 Python 异常。观察项:回答可能变长、先解释再调工具,也可能不变——模型行为不稳定,不作为通过/失败标准。常见失败:`.env` 没填 ANTHROPIC_API_KEY 或 MODEL_ID、模型名无权限、改错字符串、忘记改回。