给它真正的工具
加法只是演示。这一节换上真正有用的工具:读写文件、运行命令、抓网页。做完你会有 myagent 的第一个可用版本,并且知道怎么防止它闯祸。
下载完整代码 myagent.zip,解压后进入 myagent 目录。这一节看 agent.py 的前半部分。
工具就是普通函数
def list_dir(path="."):
return "\n".join(sorted(p.name + ("/" if p.is_dir() else "") for p in Path(path).iterdir()))
def read_file(path):
return Path(path).read_text(encoding="utf-8")[:8000]
def fetch_url(url):
req = urllib.request.Request(url, headers={"User-Agent": "myagent/1.0"})
html = urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "ignore")
text = re.sub(r"<script.*?</script>|<style.*?</style>|<[^>]+>", " ", html, flags=re.S)
return re.sub(r"\s+", " ", text)[:6000]注意每个工具的返回值都截断了(8000 字、6000 字)。工具结果会原样塞进对话,一个大文件就可能撑爆模型的上下文。
危险的工具,先问人
写文件和运行命令会改动你的电脑。在函数里先问一句:
def ask(question): # 危险操作先问人
return input(f"\n⚠️ {question} [y/N] ").strip().lower() == "y"
def run_shell(command):
if not ask(f"运行命令:{command}"):
return "用户拒绝了运行。"
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=60)
return (r.stdout + r.stderr)[-4000:] or f"(没有输出,退出码 {r.returncode})"拒绝也不是报错,而是一句“用户拒绝了运行”交回给模型,让它换个办法或者来问你。
我们真的试了一下,让它“把 worklog 文件夹删掉”,在确认时输入 n:
[1] list_dir({"path": "./worklog"})
[2] run_shell({"command": "rm -rf ./worklog"})
⚠️ 运行命令:rm -rf ./worklog [y/N] n
Agent:您确定要删除 worklog 文件夹吗?这操作会永久删除文件且无法恢复。建议先备份文件……文件夹还在。这就是为什么上一节说“模型只是请求,执行权在你手里”:权限控制就写在这里。
告诉模型有哪些工具
每个工具配一段说明。工具多了,手写 JSON Schema 很啰嗦,写个小函数生成:
def spec(tool_name, desc, **params):
return {"type": "function", "function": {"name": tool_name, "description": desc, "parameters": {
"type": "object", "properties": {k: {"type": "string", "description": v} for k, v in params.items()},
"required": list(params)}}}
TOOLS = [
spec("list_dir", "列出目录里的文件", path="目录路径"),
spec("read_file", "读取一个文本文件的内容", path="文件路径"),
spec("write_file", "写入文本文件(会先请用户确认)", path="文件路径", content="完整内容"),
spec("run_shell", "在终端运行一条命令(会先请用户确认)", command="要运行的命令"),
spec("fetch_url", "抓取网页并返回纯文本", url="网址"),
]我们写的第一版把这个函数的第一个参数叫 name,结果 spec("load_skill", ..., name="技能名") 直接报错 got multiple values for argument 'name':工具本身的参数也叫 name。所以改成了 tool_name。
跑一下
python agent.py "看看 worklog 文件夹里有哪些文件"你应该看到:
[1] list_dir({"path": "worklog"})
Agent:worklog 文件夹包含以下文件:
- 11-16.txt
- 11-18.txt
- 11-20.txt模型会犯错,所以错误要交回去
在课程首页那段真实运行里,模型第一次读文件时写成了 /worklog/11-16.txt(多了开头的斜杠),得到:
出错了:FileNotFoundError: [Errno 2] No such file or directory: '/worklog/11-16.txt'因为我们把报错原样交回,它下一步就去 list_dir 看了看,然后用 ./worklog/11-16.txt 读对了。如果程序在这里直接崩溃,整个任务就失败了。
Anthropic 在《Building effective agents》里提到,他们花在打磨工具上的时间比打磨提示词还多,比如把工具改成必须用绝对路径。工具的说明和返回信息越清楚,模型越少犯错。
查一查设计工具时……
点一个看看。
考考你用户在确认时拒绝了 rm -rf,程序应该怎么做?
检查一下
- 我跑通了
list_dir,看到了文件列表 - 我试过拒绝一次
run_shell,文件安然无恙 - 我能说出设计工具的四条要点
下一节:记忆:让它记住上下文。