工具调用
工具调用允许模型选择业务函数,但函数本身必须由你的应用执行。蜀农 API 不会直接运行你的代码。
声明工具
在请求的 tools 中声明函数名称、用途和参数结构:
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取城市当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名称"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
请求工具调用
response = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "北京天气如何?"}],
tools=[weather_tool],
tool_choice="auto",
)
模型可能在 choices[0].message.tool_calls 中返回一个或多个调用。应用应校验函数名和参数后再执行:
tool_call = response.choices[0].message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)
result = get_weather(arguments["location"])
返回工具结果
将 assistant 消息和对应的 tool 消息追加到历史后再次请求:
messages = [
{"role": "user", "content": "北京天气如何?"},
response.choices[0].message,
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result, ensure_ascii=False),
},
]
final_response = client.chat.completions.create(
model="auto",
messages=messages,
tools=[weather_tool],
)
安全建议
- 对模型生成的参数进行类型、范围和权限校验。
- 只允许调用明确注册的函数,不要动态执行模型返回的代码。
- 为外部请求设置超时、重试次数和资源限制。
- 将工具调用日志与用户请求关联,方便审计和排查。