Tool Schema

工具定义

用 JSON Schema 描述一个工具:名字、做什么、需要什么参数。

详解

Tool Schema 是你在调用 Function Calling 时递给模型的「工具说明书」。它用 JSON Schema(一种描述数据结构的标准格式)描述三件事:工具叫什么名字(name)、用来做什么(description)、需要哪些参数(input_schema)。模型不会执行任何代码——它只靠读这份说明书来判断「这个工具适不适合当前场景、该传哪些参数」。写好 Tool Schema 有两个关键点:description 要说清楚「什么情况下该用这个工具」,参数列表要用 required 字段区分必填和可选,并为每个参数写 description,否则模型容易传错参数或根本不知道何时调用。

一个类比
就像餐厅菜单:名字是菜名,description 是菜品介绍,参数是「需要几分熟、要不要辣」。服务员(模型)靠菜单决定推荐什么,厨师(你的代码)才真正下厨。
举个例子
import anthropic

client = anthropic.Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "查询指定城市的当前天气。用户询问天气时调用。",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如北京"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位,默认 celsius"
                }
            },
            "required": ["city"]  # unit 是可选参数
        }
    }
]

resp = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "北京今天多少度?"}]
)
print(resp.content)  # 模型会返回一个 tool_use block,指定调用 get_weather
PYTHON 示例
相关概念