Function Calling
让 AI 模型在需要时调用您定义的函数,获取实时数据或执行具体操作。
工作原理
1. 在 tools 参数中定义您的函数(JSON Schema 格式)
2. 模型根据用户问题判断是否需要调用函数
3. 如需调用,返回函数名和参数
4. 您执行函数后,将结果传回模型获得最终回答
请求示例
Python Function Calling
from openai import OpenAI
client = OpenAI(
api_key="am-your-api-key",
base_url="https://allmodel.top/v1"
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如 北京、上海"
}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)
tool_call = response.choices[0].message.tool_calls[0]
print(f"调用函数: {tool_call.function.name}")
print(f"参数: {tool_call.function.arguments}")
# 模拟执行函数
weather_result = {"temperature": 22, "condition": "晴"}
print(f"天气结果: {weather_result}")
tool_calls 响应格式
tool_call 响应
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"北京\"}"
}
}
]
}
传入函数结果
继续对话
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "北京今天天气怎么样?"},
response.choices[0].message, # 上一步的 assistant 回复
{
"role": "tool",
"tool_call_id": "call_abc123",
"content": '{"temperature": 22, "condition": "晴"}'
}
]
)
print(response.choices[0].message.content)
# 模型最终回答: 北京今天天气晴朗,气温22摄氏度...
💡 注意:Function Calling 不支持流式(streaming=true)。模型会根据上下文自行判断何时需要调用函数。
allmodel.top