Menu
CoddyTech

定义工具

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

模型只能生成文本。为了让它查找信息或执行操作,你可以向它提供工具:即你的程序中它可能会要求你运行的函数。你通过名称、描述和一个 input_schema(其参数的 JSON schema)来描述每个工具,并将这个列表作为 tools 传递。

time_tool = {
    "name": "get_time",
    "description": "Get the current local time in a city",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
}
response = client.messages.create(model="claude-opus-5-5", max_tokens=300,
    tools=[time_tool], messages=[{"role": "user", "content": "What time is it in Lima?"}])
print(response.stop_reason)
print(response.content[0].name, response.content[0].input)

这会输出 tool_use,然后输出 get_time {'city': 'Lima'}。

模型并没有运行任何内容:它返回了一个 tool_use 块,指明了所选的工具和参数,并且停止原因为 "tool_use"。当问题不需要工具时,它会以文本形式回答并以 "end_turn" 结束,因此在读取工具调用之前请先检查。

challenge icon

挑战

简单

给模型提供一个天气工具,并打印它所要求的内容。

  1. 定义一个名为 get_weather 的工具,描述为 Get the current weather for a city,以及一个必填的字符串属性 city。
  2. 使用 tools=[...]、model="claude-opus-5-5" 和 max_tokens=300 发送问题。
  3. 打印 Stop: 和停止原因。
  4. 对于类型为 "tool_use" 的每个块,打印 Tool: 、工具的名称、一个空格及其输入。

例如,对于输入 What is the weather in Oslo?,程序会输出:

Stop: tool_use
Tool: get_weather {'city': 'Oslo'}

对于不需要天气信息的问题,仅打印其停止行。

亲手试试

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

client = anthropic.Anthropic()

question = input()

# 1. 定义一个名为 "get_weather" 的工具,描述为 "Get the current weather for a city"
#    以及一个必需的字符串属性 "city"。

# 2. 发送问题,使用 tools=[...]、model="claude-opus-5-5" 和 max_tokens=300。

# 3. 打印 "Stop: " 和停止原因,然后针对每个 tool_use 块打印 "Tool: <name> <input>"。
quiz icon自我测试

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

工具与 Agent中的所有课

自己练习: Python 在线编译器