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

加工具只加一行Tool Use

循环不用动,新工具注册进 dispatch map 就行

解决什么问题 · 只有 bash 时,模型读文件要 cat、改文件要 sed,既容易写错,也没法限制它乱翻文件。这一章加四个专用工具(读、写、改、找),把「调哪个函数」从硬编码变成查表。

思路

  1. 每个工具 = 一个 handler 函数 + 一份 JSON Schema;
  2. 所有 handler 收进一张字典 TOOL_HANDLERS,工具名 → 函数;
  3. 循环里把 run_bash(...) 换成 TOOL_HANDLERS[name](**args);
  4. 所有文件路径先过 safe_path,出不了工作目录。
s02_tool_use/code.py · L1–208 GitHub 原文 ↗
1#!/usr/bin/env python3
2"""
3s02_tool_use.py - Tools
4 
5The agent loop from s01 does not change. This lesson adds four tools
L1–5

本章地图:循环不变,只加四个文件工具和一张分发表。

6and a dispatch map:
7 
8 +----------+ +-------+ +--------------------------+
9 | User | ---> | LLM | ---> | Tool Dispatch |
L6–9

五个工具名都汇到同一张表,循环只认表,不认具体工具。

10 | prompt | | | | bash -> run_bash |
11 +----------+ +---+---+ | read_file -> run_read |
12 ^ | write_file -> run_write |
13 | | edit_file -> run_edit |
14 +----------+ glob -> run_glob |
15 tool_result+--------------------------+
16 
17 + run_read / run_write / run_edit / run_glob
18 + TOOL_HANDLERS instead of a hard-coded run_bash call
L10–18

本章三个新增点:四个文件工具、dispatch 表、safe_path。

19 + safe_path to keep file tools inside the workspace
20 
21Key insight: the loop stays the same; only tool registration and dispatch grow.
L19–21

本章最重要的一句:加工具不需要动循环。如果你为了加个工具要改循环,说明分发结构没做好。

22"""
23 
24import os
L22–24

多引入 pathlib;SDK、dotenv 与 s01 相同。

25import subprocess
26from pathlib import Path
27 
28try:
29 import readline
L25–29

readline 只影响输入体验,缺失也不影响运行。

30 readline.parse_and_bind('set bind-tty-special-chars off')
31 readline.parse_and_bind('set input-meta on')
32 readline.parse_and_bind('set output-meta on')
33 readline.parse_and_bind('set convert-meta off')
34except ImportError:
35 pass
36 
37from anthropic import Anthropic
L30–37

SDK 初始化:base_url 可走中转,模型名从环境变量取。

38from dotenv import load_dotenv
39 
40load_dotenv(override=True)
L38–40

读 .env 并覆盖同名变量;走中转时删掉 AUTH_TOKEN。

41if os.getenv("ANTHROPIC_BASE_URL"):
42 os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
43 
44WORKDIR = Path.cwd()
L41–44

把工作目录固定成一个 Path 对象。所有文件工具都拿它当根,越界一律拒绝。

45client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
46MODEL = os.environ["MODEL_ID"]
47 
48ENVIRONMENT_PROMPT = (
49 "Windows: the bash tool runs through cmd.exe; use cmd.exe syntax, not Unix "
50 "Bash or PowerShell syntax, and prefer dedicated file tools for file operations"
51 if os.name == "nt"
52 else "Unix-like: the bash tool runs the system shell"
53)
54 
55SYSTEM = (
L45–55

system prompt 就三句:在哪、什么环境、先动手。

56 f"You are a coding agent at {WORKDIR}. Environment: {ENVIRONMENT_PROMPT}. "
57 "Use tools to solve tasks. Act, don't explain."
58)
59 
60 
61# -- From s01 (unchanged) --
62 
63def run_bash(command: str) -> str:
64 dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]
L56–64

s02 仍保留 s01 的粗糙黑名单,真正的权限在 s03。

65 if any(d in command for d in dangerous):
66 return "Error: Dangerous command blocked"
67 try:
68 r = subprocess.run(command, shell=True, cwd=WORKDIR,
L65–68

执行 shell:固定 cwd、合并输出、120 秒超时。

69 capture_output=True, text=True, errors="replace",
70 timeout=120)
71 out = (r.stdout + r.stderr).strip()
72 return out[:50000] if out else "(no output)"
L69–72

截断到 5 万字符,空输出也给一句话。

73 except subprocess.TimeoutExpired:
74 return "Error: Timeout (120s)"
75 except (FileNotFoundError, OSError) as e:
76 return f"Error: {e}"
77 
78 
79# -- New in s02: four tools --
80 
81def safe_path(p: str) -> Path:
L73–81

文件工具的守门员:相对路径先拼成绝对路径,再检查是不是还在工作目录里。

82 path = (WORKDIR / p).resolve()
83 if not path.is_relative_to(WORKDIR):
84 raise ValueError(f"Path escapes workspace: {p}")
L82–84

先 resolve 再判断越界;越界抛异常,由调用方转成错误字符串。

85 return path
86 
87 
88def run_read(path: str, limit: int | None = None) -> str:
L85–88

读文件支持 limit:先读 50 行看看,需要再往下读,不用一次把大文件塞进上下文。

89 try:
90 lines = safe_path(path).read_text(encoding="utf-8").splitlines()
91 if limit and limit < len(lines):
92 lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
L89–92

截断时告诉模型「还有多少行」。只截断不提示,它会以为文件就这么长。

93 return "\n".join(lines)
94 except Exception as e:
95 return f"Error: {e}"
96 
97 
98def run_write(path: str, content: str) -> str:
99 try:
100 file_path = safe_path(path)
101 file_path.parent.mkdir(parents=True, exist_ok=True)
L93–101

写文件顺手建父目录。不然模型得先 mkdir 再 write,多一轮对话就多一份上下文。

102 file_path.write_text(content, encoding="utf-8")
103 return f"Wrote {len(content)} bytes to {path}"
104 except Exception as e:
105 return f"Error: {e}"
106 
107 
108def run_edit(path: str, old_text: str, new_text: str) -> str:
109 try:
110 file_path = safe_path(path)
111 text = file_path.read_text(encoding="utf-8")
112 if old_text not in text:
L102–112

找不到原文就明确报错,让模型重新读一遍再改,而不是「尽力而为」地瞎写。

113 return f"Error: text not found in {path}"
114 file_path.write_text(text.replace(old_text, new_text, 1), encoding="utf-8")
L113–114

只替换第一次出现。这是 edit 工具的语义:改一处就是改一处,不会把同名代码全改掉。

115 return f"Edited {path}"
116 except Exception as e:
117 return f"Error: {e}"
118 
119 
120def run_glob(pattern: str) -> str:
L115–120

glob 也以 WORKDIR 为根:去重、排序、最多 200 条。

121 import glob as g
122 try:
123 matches = sorted({
L121–123

glob 结果先去重再排序。集合推导里的条件又检查了一次越界——文件工具的安全检查做了两层。

124 match for match in g.glob(
125 pattern, root_dir=WORKDIR, recursive=True)
126 if (WORKDIR / match).resolve().is_relative_to(WORKDIR)
127 })
128 shown = matches[:200]
L124–128

最多返回 200 条,超了提示「还有更多,请缩小范围」。列表太长同样是上下文炸弹。

129 if len(matches) > 200:
130 shown.append("... (more matches omitted; narrow the pattern)")
131 return "\n".join(shown) if shown else "(no matches)"
132 except Exception as e:
133 return f"Error: {e}"
134 
135 
136# -- New in s02: tool definitions (one tool in s01, five in s02) --
137 
138TOOLS = [
L129–138

五个工具的 schema 全是手写 JSON。真实产品会用装饰器或类型注解生成,本质一样。

139 {"name": "bash", "description": "Run a shell command.",
140 "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
141 {"name": "read_file", "description": "Read file contents.",
L139–141

每个工具一份 schema;参数名就是 handler 的形参名。

142 "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}},
143 {"name": "write_file", "description": "Write content to a file.",
L142–143

写文件工具的参数:path + content。

144 "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
145 {"name": "edit_file", "description": "Replace exact text in a file once.",
146 "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
147 {"name": "glob", "description": "Find files matching a glob pattern; ** matches recursively.",
148 "input_schema": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}},
149]
150 
151# -- New in s02: dispatch map (replaces s01's hard-coded run_bash call) --
152 
153TOOL_HANDLERS = {
L144–153

dispatch map:工具名 → 函数。加工具只需要在这张表里加一行。

154 "bash": run_bash, "read_file": run_read, "write_file": run_write,
155 "edit_file": run_edit, "glob": run_glob,
L154–155

表 key 是模型看到的工具名,value 是 Python 函数。

156}
157 
158 
159# -- The agent loop keeps the same shape as s01; only dispatch changes --
160# s01: output = run_bash(block.input["command"])
161# s02: output = TOOL_HANDLERS[block.name](**block.input)
L156–161

s01 固定调 run_bash;s02 改成查表 + 展开参数,加工具不用动循环。

162 
163def agent_loop(messages: list):
L162–163

循环主体和 s01 一样,只把固定调用换成查表。

164 while True:
165 response = client.messages.create(
166 model=MODEL, system=SYSTEM, messages=messages,
167 tools=TOOLS, max_tokens=8000,
168 )
169 messages.append({"role": "assistant", "content": response.content})
170 
171 tool_calls = [
172 block for block in response.content if block.type == "tool_use"
173 ]
174 if not tool_calls:
L164–174

没有工具调用就结束这一轮。

175 return
176 
177 results = []
178 for block in tool_calls:
179 print(f"\033[33m> {block.name}\033[0m")
180 handler = TOOL_HANDLERS.get(block.name)
L175–180

用 get 而不是 []:模型偶尔会编出不存在的工具名,这时返回「未知工具」,而不是让程序崩掉。

181 output = handler(**block.input) if handler else f"Unknown: {block.name}"
L181–181

**block.input 把 JSON 参数展开成关键字参数——schema 名字必须和形参一致。

182 print(str(output)[:200])
L182–182

控制台只打印前 200 字,完整结果仍回填给模型。

183 results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
184 
185 messages.append({"role": "user", "content": results})
186 
187 
188if __name__ == "__main__":
L183–188

命令行入口:输入问题,跑一轮,打印最终文字。

189 print("s02: Tool Use - four tools added to s01")
190 print("Enter a question, press Enter to send. Type q to quit.\n")
191 
192 history = []
L189–192

整场对话共用一份 history。

193 while True:
194 try:
195 # \001/\002 tell Readline the ANSI escapes have zero display width.
196 query = input("\001\033[36m\002s02 >> \001\033[0m\002")
L193–196

读一行输入;EOF 或 Ctrl-C 优雅退出。

197 except (EOFError, KeyboardInterrupt):
198 break
199 if not query.strip():
200 continue
201 if query.strip().lower() in ("q", "exit"):
202 break
203 history.append({"role": "user", "content": query})
204 agent_loop(history)
205 for block in history[-1]["content"]:
L197–205

只打印最后一条回复里的文本块。

206 if getattr(block, "type", None) == "text":
207 print(block.text)
208 print()

记住这几条

加工具 = schema + handler + 表里一行

在这套 dispatch 结构里,加工具不需要碰循环。

先 resolve 再判断

路径安全检查必须在解析完 .. 和符号链接之后做,否则形同虚设。

参数名必须对齐

schema 里的 key 就是 Python 的 kwarg 名,错一个字母就是 TypeError。

工具只返回字符串

成功、失败、空结果,一律是字符串;模型的世界里没有异常。

容易踩的坑

  • 用 `WORKDIR / p` 但不 resolve,`../` 一路能跑到根目录。
  • edit 用 replace 不带次数限制,改一处结果全文件同名代码都被改了。
  • read 不限行数,模型一条命令读了 5000 行日志,这一轮的上下文基本就废了。
  • 注意:safe_path 只约束「文件工具」的路径,bash 仍然能访问工作区外的任何东西——它不是沙箱。

动手改一改

加一个 `list_dir` 工具:写 handler、加一段 schema、在 TOOL_HANDLERS 里加一行。验收:循环代码一个字没改,模型能成功调用它;再给 read_file 传 `../../etc/hosts`,应返回 `Error: Path escapes workspace`。