四 第二编 · 第一章 · · 约 4 分钟读完

Tool

让模型能"动手"的东西 —— 函数、API、命令。

能力层 函数 动作

一定义

Tool(工具)是模型被允许调用的外部函数。模型本身只能生成文本,通过 Tool,它才能查天气、读数据库、发邮件、改文件 ——真正改变外部世界。

二为什么重要

Tool 是从"聊天"到"做事"的关键。没有 Tool,模型就是一本会说话的百科全书;有了 Tool,它才能像一个能跑代码、查系统、调接口的工程师。

三典型结构

每个 Tool 通常需要声明三件事:

  • 名字 —— get_weather
  • 描述 —— 告诉模型这个工具是干啥的、何时该用
  • 参数 schema —— 用 JSON Schema 描述参数形状

四最小可跑的例子

import json
from openai import OpenAI

client = OpenAI()

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "查询某城市的当前天气。",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名,例如 'Beijing'"}
            },
            "required": ["city"]
        }
    }
}]

def get_weather(city):
    return {"city": city, "temp": 22, "sky": "晴"}

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
    tools=tools,
)
call = resp.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
result = get_weather(**args)
print(result)  # {'city': 'Beijing', 'temp': 22, 'sky': '晴'}

五常见误区

  • Tool 太多 —— 模型一次能稳定选择的不超过 10 个,多了就开始乱点。
  • 描述写得像技术文档 —— 描述是写给模型看的,要直白、带例子、带边界。
  • Tool 没做幂等保护 —— 模型可能重试同一调用,写操作要带幂等键。
  • 把 Tool 当 Skill —— Tool 是原子动作,Skill 是多个 Tool + 规则的组合(详见 Skill 章)。