编写工具描述
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 11 课,共 22 课。
模型永远看不到你的 Python 函数。它仅仅根据工具的 name 和 description 来决定是否调用工具以及调用哪一个。像 Useful helper. 这样的描述没有提供任何参考依据,因此它会在不使用工具的情况下直接回答。
vague = {"name": "helper", "description": "Useful helper.", "input_schema": schema}
clear = {
"name": "get_tides",
"description": "Get today's high and low tide times for a harbour. Use it for any question about tides.",
"input_schema": schema,
}当被询问 When is high tide in Dover? 时,模型单独回答 vague(停止原因为 end_turn),并调用 clear(停止原因为 tool_use)。
一个好的描述会说明三件事:工具的作用或返回值、何时使用它,以及模型必须了解的关于参数的任何信息(单位、格式、限制)。也要为每个参数提供各自的 description。替身程序会在请求和描述之间匹配词语;真实模型会理解其中的含义,但如果描述中什么都没写,它也会以同样的方式失败。
挑战
中等图书馆助手从不使用它的 lookup 工具,因为描述什么也没说。修复该描述;保持名称、schema 和循环不变。
- 将
Looks things up.替换为一到两句话的描述。 - 说明该工具用于获取图书馆分馆的营业时间。
- 说明当有人询问分馆何时开门或关门时使用它。
循环会打印每次工具调用和答案。例如,对于输入 When does the Riverside branch open?,程序会输出:
Tool: lookup {'branch_name': 'Riverside'}
Answer: Here is what I found: Riverside: 9 am to 6 pm亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
HOURS = {"Riverside": "9 am to 6 pm", "Hill": "10 am to 4 pm", "Oak": "8 am to 8 pm"}
# 重写描述,让模型知道何时使用此工具
TOOLS = [
{
"name": "lookup",
"description": "Looks things up.",
"input_schema": {
"type": "object",
"properties": {"branch_name": {"type": "string", "description": "The branch name, such as Riverside"}},
"required": ["branch_name"],
},
}
]
def lookup(branch_name):
return f"{branch_name}: {HOURS.get(branch_name, 'no such branch')}"
request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
results.append({"type": "tool_result", "tool_use_id": block.id, "content": lookup(**block.input)})
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
工具与 Agent中的所有课
自己练习: Python 在线编译器