Menu
CoddyTech

读取工具调用

本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 2 课,共 22 课。

一个 tool_use 块包含三样内容:name(哪个工具)、input(模型选择的参数字典,包含你的 schema 的键)以及 id(例如 toolu_... 这样的唯一 ID,下一课会随结果一起发回)。你的代码会读取它们并调用对应的 Python 函数。

def get_hours(day):
    return HOURS.get(day, "closed")

for block in response.content:
    if block.type == "tool_use" and block.name == "get_hours":
        print(block.id.startswith("toolu_"))
        print(get_hours(block.input["day"]))

对于 What are your opening hours on Saturday?,这会打印 True,然后是 10 am to 2 pm。

参数来自模型,因此要像对待用户输入一样对待它们:它指定的项目可能并不在你的数据中。一个好的函数会在这种情况下返回明确的信息,而不是崩溃,因为该信息是模型接下来要读取的内容。

challenge icon

挑战

简单

运行模型要求的工具。起始代码定义了 get_price、工具以及调用。

  1. 找到 type 为 "tool_use" 的块。
  2. 打印 Tool: 及其名称。
  3. 打印 Item: 以及来自其输入的 item 参数。
  4. 使用该 item 调用 get_price,并打印 Result: 及其返回值。

例如,对于输入 What is the price of the lamp?,程序输出:

Tool: get_price
Item: lamp
Result: The lamp costs 40 dollars.

亲手试试

import coddy_ai as anthropic  # 在生产环境中:import anthropic

client = anthropic.Anthropic()

PRICES = {"lamp": 40, "desk": 120, "chair": 65}


def get_price(item):
    if item in PRICES:
        return f"The {item} costs {PRICES[item]} dollars."
    return f"No price for {item}."


price_tool = {
    "name": "get_price",
    "description": "Look up the price of an item in dollars",
    "input_schema": {
        "type": "object",
        "properties": {"item": {"type": "string", "description": "The item to price"}},
        "required": ["item"],
    },
}

question = input()
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=300,
    tools=[price_tool],
    messages=[{"role": "user", "content": question}],
)

# 对于 tool_use 块:打印 "Tool: <name>", "Item: <item>",
# 然后使用该 item 运行 get_price,并打印 "Result: <what it returns>"
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

工具与 Agent中的所有课

自己练习: Python 在线编译器