模型与推断 / 工具调用
工具调用
工具调用(Tool Calling,也称 Function Calling)允许模型根据用户输入选择并调用外部工具或 API。应用可以借此连接外部数据源、查询实时信息或执行特定操作。
工作原理
工具调用通常包含以下步骤:
- 使用 JSON Schema 定义工具,包括工具名称、功能描述和参数。
- 将工具定义与用户消息一起发送给模型。
- 模型分析用户请求,并判断是否需要调用工具。
- 如果需要调用工具,模型会返回工具名称及对应参数。
- 应用执行相应工具,并将执行结果发送回模型,以生成最终回复。
快速示例
下面以天气查询为例,展示如何定义工具并向模型发送请求。模型负责生成工具调用请求,实际工具逻辑由应用实现。
定义工具并发送请求
Python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"]
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定地点的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称"
}
},
"required": ["location"]
}
}
}]
response = client.chat.completions.create(
model="YOUR_MODEL_ID",
messages=[{"role": "user", "content": "旧金山现在的天气怎么样?"}],
tools=tools,
temperature=0.1
)
print(response.choices[0].message.tool_calls)当模型决定调用工具时,响应中会包含工具名称和参数。
建议:对于需要稳定工具选择和参数生成的任务,可以尝试使用较低的 Temperature,并结合实际调用结果进行验证。
执行工具并返回结果
模型不会替应用执行外部函数。应用需要读取模型返回的工具调用,执行对应逻辑,再将结果作为 tool 消息追加到对话中。
Python · 完整调用流程
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["TOKENGRID_API_KEY"],
base_url=os.environ["TOKENGRID_BASE_URL"]
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定地点的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名称"}
},
"required": ["location"]
}
}
}]
# 1. 发送初始请求
messages = [{"role": "user", "content": "旧金山现在的天气怎么样?"}]
response = client.chat.completions.create(
model="YOUR_MODEL_ID",
messages=messages,
tools=tools,
temperature=0.1
)
# 2. 检查模型是否返回工具调用
assistant_message = response.choices[0].message
if assistant_message.tool_calls:
tool_call = assistant_message.tool_calls[0]
# 3. 执行应用侧工具逻辑
def get_weather(location):
return {"location": location, "temperature": 22, "condition": "晴"}
function_args = json.loads(tool_call.function.arguments)
function_result = get_weather(**function_args)
# 4. 将工具调用和结果加入对话
messages.append(assistant_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(function_result, ensure_ascii=False)
})
# 5. 再次请求模型生成最终回复
final_response = client.chat.completions.create(
model="YOUR_MODEL_ID",
messages=messages,
tools=tools,
temperature=0.1
)
print(final_response.choices[0].message.content)定义工具
工具通过 JSON Schema 描述。每个工具包含以下主要字段:
- name:工具的唯一名称,用于标识要调用的函数。
- description:工具功能的清晰说明,帮助模型判断何时使用该工具。
- parameters:使用 JSON Schema 描述函数参数,包括参数类型、说明和必填项。
提示:尽量提供清晰、具体的工具描述和参数说明。模型会根据这些信息判断工具是否适用,以及如何生成参数。
参数类型
| 类型 | 说明 |
|---|---|
| string | 字符串 |
| number | 数字 |
| integer | 整数 |
| object | 对象 |
| array | 数组 |
| boolean | 布尔值 |
| null | 空值 |
定义多个工具
Python
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定地点的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市或地区名称"},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}
},
{
"type": "function",
"function": {
"name": "search_restaurants",
"description": "根据菜系和位置搜索餐厅",
"parameters": {
"type": "object",
"properties": {
"cuisine": {"type": "string", "description": "菜系"},
"location": {"type": "string", "description": "城市或街区"},
"price_range": {
"type": "string",
"enum": ["$", "$", "$$", "$$"]
}
},
"required": ["cuisine", "location"]
}
}
}
]其他配置
工具选择(tool_choice)
| 取值 | 说明 |
|---|---|
| auto | 由模型自行判断是否调用工具。 |
| none | 不调用任何工具,直接生成回复。 |
| required | 要求模型至少调用一个工具。 |
| 指定函数 | 要求模型调用指定的函数。 |
Python · 指定工具
response = client.chat.completions.create(
model="YOUR_MODEL_ID",
messages=[{"role": "user", "content": "查询旧金山的天气"}],
tools=tools,
tool_choice={
"type": "function",
"function": {"name": "get_weather"}
}
)注意:部分模型支持在一次响应中并行返回多个工具调用。使用前请确认所选模型是否支持该能力。
流式调用
工具调用也可以与流式响应一起使用。启用流式输出后,工具调用的名称和参数可能分多个数据块逐步返回。应用需要按工具调用的索引累积数据,在参数完整后再进行解析和执行。
Python
import json
tool_calls = {}
stream = client.chat.completions.create(
model="YOUR_MODEL_ID",
messages=[{"role": "user", "content": "查询旧金山的天气"}],
tools=tools,
stream=True,
temperature=0.1
)
for chunk in stream:
delta_calls = chunk.choices[0].delta.tool_calls
if delta_calls:
for item in delta_calls:
index = item.index
if index not in tool_calls:
tool_calls[index] = {"id": "", "name": "", "arguments": ""}
if item.id:
tool_calls[index]["id"] = item.id
if item.function and item.function.name:
tool_calls[index]["name"] = item.function.name
if item.function and item.function.arguments:
tool_calls[index]["arguments"] += item.function.arguments
if chunk.choices[0].finish_reason == "tool_calls":
for item in tool_calls.values():
arguments = json.loads(item["arguments"])
print(item["name"], arguments)
break问题排查
模型没有按预期调用工具
- 检查工具描述是否清晰、具体。
- 确认用户请求是否明确表达了需要工具完成的任务。
- 在适用场景下尝试设置 tool_choice="required"。
- 确认所选模型支持工具调用。
工具参数不正确或格式异常
- 为参数补充更具体的说明。
- 对于需要稳定参数输出的场景,尝试降低 Temperature。
- 在参数说明中提供格式或取值示例。
- 使用 enum 限制参数的可选值。
JSON 解析错误
Python · 参数解析示例
import json
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as error:
print(f"Invalid tool arguments: {error}")