工具调用
工具调用允许模型要求应用运行一个具名函数,例如查询天气、查询数据库、调用内部服务或执行业务逻辑。模型不会亲自运行工具,而是返回结构化工具调用;应用解析参数、运行函数,并把结果发回模型,以便模型继续对话。
AISIX AI 网关通过 OpenAI 兼容 Chat Completions 路径承载这些工具调用请求,并在 OpenAI 风格和 Anthropic 风格工具格式之间进行有针对性的转换。应用可以把服务提供方凭证和模型路由留在 AISIX 后面,同时保留 SDK 或智能体框架期望的工具循环。
本指南将通过 AISIX 发送工具定义,查看后续工具循环,并选择与客户端格式匹配的请求路由。
准备工作
请先准备以下内容:
- 一个可以处理代理请求的 AISIX 网关。
- 一个可以访问该模型别名的调用方 API Key。
- 一个由支持工具调用的服务提供方和模型支撑的模型别名。
发送工具调用请求
下面示例使用 OpenAI 兼容 Chat Completions 路径。它发送函数定义,并要求模型调用该函数:
curl -sS -X POST "http://127.0.0.1:3000/v1/chat/completions" \
-H "Authorization: Bearer YOUR_CALLER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-prod",
"messages": [
{"role": "user", "content": "What is the weather in Paris? Use the tool if needed."}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}
],
"tool_choice": {
"type": "function",
"function": {"name": "get_weather"}
}
}'
响应仍保持 OpenAI 兼容格式。你应在 assistant message 中看到工具调用:
{
"choices": [
{
"message": {
"role": "assistant",
"tool_calls": [
{
"id": "call_***",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
}
}
]
}
如果模型返回普通文本,请先确认选中的上游模型支持工具调用,并且请求确实要求工具调用。
继续工具调用循环
模型返回工具调用后,应用解析工具参数、运行函数,并通过同一个 Chat Completions 路由发回结果。请使 用 assistant message 返回的 tool_call_id,让模型能够将工具结果关联到原始调用。
将工具结果作为后续消息发送:
curl -sS -X POST "http://127.0.0.1:3000/v1/chat/completions" \
-H "Authorization: Bearer YOUR_CALLER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-prod",
"messages": [
{"role": "user", "content": "What is the weather in Paris? Use the tool if needed."},
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_***",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_***",
"content": "Sunny, 21 C."
}
]
}'
对于后续请求,网关会保持相同的调用方认证和模型别名行为。服务提供方凭证和上游模型 ID 仍留在 AISIX 内部。