内容更新: 2026-06-09
概览
函数调用允许模型调用您定义的函数,实现与外部系统的交互。模型不会直接执行函数——它返回函数名称和参数,然后您的代码执行这些函数并将结果返回给模型。完整示例
import json
from openai import OpenAI
client = OpenAI(api_key="sk-xxx", base_url="https://api.crazyrouter.com/v1")
# 1. Define tools
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g.: New York"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search for products",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search keyword"},
"max_price": {"type": "number", "description": "Maximum price"}
},
"required": ["query"]
}
}
}
]
# 2. Mock function implementations
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 22, "unit": unit, "condition": "Sunny"}
def search_products(query, max_price=None):
return [{"name": f"{query} Product A", "price": 99}, {"name": f"{query} Product B", "price": 199}]
# 3. Conversation loop
messages = [{"role": "user", "content": "What's the weather like in New York today? Also search for umbrellas"}]
response = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
# 4. Handle tool calls
if message.tool_calls:
messages.append(message)
for tool_call in message.tool_calls:
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if func_name == "get_weather":
result = get_weather(**args)
elif func_name == "search_products":
result = search_products(**args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result, ensure_ascii=False)
})
# 5. Get final response
final = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools
)
print(final.choices[0].message.content)
强制指定函数调用
response = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
支持的模型
对于本页面中兼容OpenAI的函数调用示例,请首先使用以下经过验证的基础版本:gpt-5.5
在2026年3月23日,使用
gpt-5.5进行工具调用已在Crazyrouter生产环境中通过验证。对于其他厂商,请首先查看其专属页面,因为请求格式和支持详情可能有所不同。