Give it real tools
Addition was just a demo. In this section we swap in genuinely useful tools: reading and writing files, running commands, fetching web pages. When you're done, you'll have the first usable version of myagent, and you'll know how to keep it out of trouble.
Download the full code myagent.zip, unzip it and enter the myagent directory. This section covers the first half of agent.py.
Tools are just ordinary functions
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]Note that every tool's return value is truncated (8000 characters, 6000 characters). Tool results go into the conversation as-is, so one large file could blow up the model's context.
Dangerous tools: ask the user first
Writing files and running commands modify your computer. Ask first inside the function:
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})"A refusal isn't an exception either—it's just a message saying "the user declined to run it" handed back to the model, so it can try another approach or ask you.
We actually tried it: we told it to "delete the worklog folder," and entered n at the confirmation prompt:
[1] list_dir({"path": "./worklog"})
[2] run_shell({"command": "rm -rf ./worklog"})
⚠️ Run command: rm -rf ./worklog [y/N] n
Agent: Are you sure you want to delete the worklog folder? This operation will permanently delete the files and they cannot be recovered. It's recommended to back up the files first…The folder is still there. This is why the previous section said "the model only makes requests; the power to execute is in your hands": permission control is written right here.
Tell the model which tools exist
Each tool gets a description. Once you have many tools, hand-writing JSON Schema gets tedious, so write a small function to generate it:
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="网址"),
]In the first version we wrote, the first parameter of this function was called name, and spec("load_skill", ..., name="技能名") immediately threw the error got multiple values for argument 'name': the tool's own parameter is also called name. So we renamed it to tool_name.
Run it
python agent.py "看看 worklog 文件夹里有哪些文件"You should see:
[1] list_dir({"path": "worklog"})
Agent: The worklog folder contains the following files:
- 11-16.txt
- 11-18.txt
- 11-20.txtThe model makes mistakes, so errors must be handed back
In that real run on the course homepage, the model wrote the file path as /worklog/11-16.txt on its first read (with an extra leading slash), and got:
出错了:FileNotFoundError: [Errno 2] No such file or directory: '/worklog/11-16.txt'Because we passed the error back as-is, its next step was to take a look with list_dir, and then read it correctly with ./worklog/11-16.txt. If the program had crashed right there, the whole task would have failed.
In "Building effective agents," Anthropic mentions that they spend more time polishing tools than polishing prompts—for example, changing a tool to require absolute paths. The clearer a tool's description and return information, the fewer mistakes the model makes.
Look it upWhen designing tools…
Click one to see.
Quiz timeThe user rejected rm -rf at the confirmation step. What should the program do?
Check yourself
- I got
list_dirrunning and saw the file list - I declined once with
run_shell, and the file survived unharmed - I can state the four key points of designing tools
Next section: Memory: letting it remember context.