AI Agent / 系统课时
定义工具描述与参数
定义工具描述与参数
工具定义决定模型能否选对能力、生成合法参数,并让应用安全执行。本课将用一个天气查询工具说明如何编写名称、用途、参数类型、必填项与边界约束,最终得到可直接交给模型的工具描述。
学习目标
- 能为工具编写明确且可区分的名称与用途说明
- 能使用 JSON Schema 描述参数类型、必填项和取值范围
- 能通过本地校验发现缺失字段与非法参数
工具描述包含什么
一份可靠的工具定义通常由三层信息组成:工具名称回答“调用谁”,用途说明回答“什么时候调用”,参数 Schema 回答“调用时必须提供什么”。模型会同时参考这三部分,因此任何含糊之处都可能造成误调用。
工具名称应稳定、简短并体现动作,例如 get_weather。用途说明要写清适用场景和限制,不要只写“查询天气”,而应指出按城市查询当前天气,并说明不提供历史数据。
编写参数 Schema
下面用同一份函数定义生成 Chat Completions 和 Responses 两种请求体中的工具项。前者把定义放在 function 对象内,后者把字段放在工具项顶层。调用接口时把对应的项放入 tools 数组。
严格模式要求对象禁用额外字段,并将所有声明属性列入 required。想允许温度单位未指定,可以将 unit 声明为字符串或 null,同时保留在必填列表中。此处采用 ℃ 作为业务默认值。模型供应商和模型版本对严格模式、Schema 子集的支持可能不同。
把代码保存为 tool_specs.py。接下来几节会从这个文件导入定义和本地校验函数。
python
WEATHER_FUNCTION = {
"name": "get_weather",
"description": "查询指定城市的当前天气。不处理历史天气或预报。",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "用户指定的城市名称"},
"unit": {"type": ["string", "null"], "enum": ["celsius", "fahrenheit", None]},
},
"required": ["city", "unit"],
"additionalProperties": False,
},
}
def weather_tool(protocol):
if protocol == "chat":
return {"type": "function", "function": WEATHER_FUNCTION}
if protocol == "responses":
return {"type": "function", **WEATHER_FUNCTION}
raise ValueError("unsupported protocol")
def validate_weather(args):
if not isinstance(args, dict) or args.keys() != {"city", "unit"}:
raise ValueError("invalid weather fields")
city, unit = args["city"], args["unit"]
if not isinstance(city, str) or not 1 <= len(city.strip()) <= 80:
raise ValueError("invalid city")
if unit not in ("celsius", "fahrenheit", None):
raise ValueError("invalid temperature unit")
return {"city": city.strip(), "unit": unit or "celsius"}
if __name__ == "__main__":
print(weather_tool("chat")["function"]["name"])
print(weather_tool("responses")["name"])
print(validate_weather({"city": " 上海 ", "unit": None}))预期输出
text
get_weather
get_weather
{'city': '上海', 'unit': 'celsius'}定义模型可见的范围
根据用户的实际权限与当前任务筛选可暴露的工具。天气工具只接受城市和单位。账号、租户、授权凭据由执行层从可信上下文获取,避免模型生成或覆盖这些数据。请求到达工具后仍要校验类型、范围与权限。下一课会用同一份定义解析两种接口的调用。
按自己的节奏,确认真正理解。