Menu
CoddyTech

在工具之间进行选择

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

传递多个工具后,模型会读取每个工具的名称和描述,并选择最符合需求的那一个。接着,你的代码需要运行它所选的工具。针对 block.name 使用长长的 if/elif 链虽然可行,但使用从工具名称到函数的字典扩展性更好:每个工具只需要一行代码。

functions = {"add": add, "multiply": multiply}
name = "multiply"
arguments = {"a": 6, "b": 7}
print(functions[name](**arguments))

这会输出 42。**arguments 会将字典的键作为关键字参数传递,因此 block.input 可以直接传入参数名与 schema 的属性名相匹配的函数中。

将每个工具的名称都保留在字典中:模型只会调用你列出的工具,因此缺少条目是你程序中的 bug,而不是模型的选择问题。如果没有合适的工具,模型会以文本形式回答,并且没有需要运行的内容。

challenge icon

挑战

中等

初始代码为模型提供了三个工具:天气、当地时间和价格。运行它选择的任意一个工具。

  1. 创建一个字典,将每个工具名称映射到其对应的 Python 函数。
  2. 对于每个类型为 "tool_use" 的块,打印 Tool: 和它的名称,然后使用 **block.input 运行字典中的函数,并打印 Result: 以及该函数返回的内容。
  3. 对于类型为 "text" 的块,打印 Answer: 和它的文本内容。

例如,对于输入 What time is it in Rome?,程序会输出:

Tool: get_time
Result: Rome: 14:05

亲手试试

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

client = anthropic.Anthropic()

WEATHER = {"Rome": "21 C and sunny", "Tokyo": "16 C and cloudy", "Oslo": "4 C and windy"}
TIMES = {"Rome": "14:05", "Tokyo": "22:05", "Oslo": "14:05"}
PRICES = {"lamp": 40, "desk": 120}


def get_weather(city):
    return f"{city}: {WEATHER.get(city, 'no data')}"


def get_time(city):
    return f"{city}: {TIMES.get(city, 'no data')}"


def get_price(item):
    return f"{item}: {PRICES.get(item, 'no price')} dollars"


def city_schema():
    return {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}


tools = [
    {"name": "get_weather", "description": "Get the current weather for a city", "input_schema": city_schema()},
    {"name": "get_time", "description": "Get the current local time in a city", "input_schema": city_schema()},
    {"name": "get_price", "description": "Look up the price of an item in dollars",
     "input_schema": {"type": "object", "properties": {"item": {"type": "string"}}, "required": ["item"]}},
]

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

# 1. 创建一个字典,将每个工具名称映射到其 Python 函数。
# 2. 对于每个 tool_use 块,打印 "Tool: <name>",使用 **block.input 运行该函数
#    并打印 "Result: <what it returns>"。
# 3. 如果模型改为以文本形式回答,则打印 "Answer: <text>"。
quiz icon自我测试

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

工具与 Agent中的所有课

自己练习: Python 在线编译器