概述
Function Calling(函数调用)允许 AI 模型在需要时调用预定义的函数,从而获取实时信息、执行计算或调用外部 API。
定义函数
在请求中定义可用的函数,AI 模型会根据对话内容决定是否调用:
Python
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.lingyuncx.com/v1",
api_key="sk-xxxxxxxx"
)
# 定义可用函数
functions = [
{
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如'北京'、'上海'"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "北京今天天气怎么样?"}
],
functions=functions
)
print(response.choices[0].message)
处理函数调用
当 AI 模型决定调用函数时,返回会包含 function_call:
JSON
{
"role": "assistant",
"content": null,
"function_call": {
"name": "get_weather",
"arguments": "{\"location\": \"北京\", \"unit\": \"celsius\"}"
}
}
完整流程
Python
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.lingyuncx.com/v1",
api_key="sk-xxxxxxxx"
)
def get_weather(location: str, unit: str = "celsius") -> str:
"""获取天气信息(示例函数)"""
return f"{location}今天晴朗,温度 25°{unit[0].upper()}"
# 1. 第一次请求
functions = [{
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名称"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
functions=functions
)
# 2. 检查是否需要调用函数
message = response.choices[0].message
if message.function_call:
function_name = message.function_call.name
arguments = json.loads(message.function_call.arguments)
# 3. 执行函数
result = get_weather(**arguments)
# 4. 将结果返回给 AI
messages.append(message)
messages.append({
"role": "function",
"name": function_name,
"content": result
})
# 5. 第二次请求获取最终回复
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
functions=functions
)
print(response.choices[0].message.content)
# 输出:北京今天晴朗,温度 25°C
并行函数调用
设置 parallel_function_calls: true 允许 AI 并行调用多个函数:
Python
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "北京和上海今天天气怎么样?"}
],
functions=functions,
parallel_function_calls=True
)
应用场景
实时数据查询
天气、股票、新闻等实时信息
数据库查询
查询订单、用户信息等数据库操作
API 调用
调用第三方 API 获取数据或执行操作
代码执行
执行数学计算、数据处理等代码
💡 提示
函数描述越清晰,AI 模型调用越准确。建议在 description 中详细说明函数用途和参数含义。