以下这个代码示例是用 API 中转站来解读 OpenAI Function Call 的使用,具体过程是 Claude 3.5 帮助我写的代码~~
第二部分是详细的解读,希望对你有用。 关于 Function Call,请看这篇 https://help.apiyi.com/openai-api-function-call.html
请注意,这段代码中假设存在一个
fetch_weather
函数来获取实际的天气数据。你需要实现这个函数,或者将其替换为实际的天气 API 调用。另外,请确保你使用的是最新版本的 OpenAI Python 库。你可以通过运行以下命令来更新:pip install –upgrade openai
API 中转站的 Function Call 示例代码
如下所述:其中需要你自行更换 API Key,点击查看【API 中转站-API易的 Key】
from openai import OpenAI
import json
# 设置API密钥和基础URL
api_key = "sk-aBo2gWUzln更新成你自己的 Key"
api_base = "https://api.apiyi.com/v1"
client = OpenAI(api_key=api_key, base_url=api_base)
# 定义可用的函数
functions = [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location", "unit"]
}
}
]
# 用户查询
user_query = "What's the weather in Boston, MA?"
# 生成调用请求
messages = [
{"role": "system", "content": "You are an AI assistant that can call functions to assist users."},
{"role": "user", "content": user_query}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
functions=functions,
function_call="auto"
)
# 检查是否需要调用函数
if response.choices[0].message.function_call:
function_call = response.choices[0].message.function_call
function_name = function_call.name
function_params = json.loads(function_call.arguments)
# 根据函数名称执行相应的操作
if function_name == "get_current_weather":
# 这里应该实现 fetch_weather 函数
weather_data = fetch_weather(function_params["location"], function_params["unit"])
# 将结果发送回OpenAI
result_message = {
"role": "function",
"name": function_name,
"content": json.dumps(weather_data)
}
messages.append(response.choices[0].message)
messages.append(result_message)
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(final_response.choices[0].message.content)
else:
print(response.choices[0].message.content)
详细解读这段代码,让初学者也看得懂
OpenAI Function Call 代码逻辑解释
1. 导入和设置
from openai import OpenAI
import json
api_key = "sk-aBo2gWUzlneOAJqE9035Ac050d7749F8B5942b0fE58a752f"
api_base = "https://api.apiyi.com/v1"
client = OpenAI(api_key=api_key, base_url=api_base)
这部分代码导入了必要的库,设置了 API 密钥和基础 URL,并创建了一个 OpenAI 客户端对象。
2. 定义函数
functions = [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location", "unit"]
}
}
]
这里定义了一个可以被 AI 调用的函数。这个函数叫做 get_current_weather
,它需要一个位置和温度单位作为参数。
3. 设置用户查询
user_query = "What's the weather in Boston, MA?"
这是用户的输入,询问波士顿的天气。
4. 准备消息
messages = [
{"role": "system", "content": "You are an AI assistant that can call functions to assist users."},
{"role": "user", "content": user_query}
]
这里准备了发送给 AI 的消息,包括一条系统消息(定义 AI 的角色)和用户的查询。
5. 发送请求给 OpenAI
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
functions=functions,
function_call="auto"
)
这段代码向 OpenAI 发送请求,包括消息内容和可用的函数定义。
6. 处理 AI 的响应
if response.choices[0].message.function_call:
function_call = response.choices[0].message.function_call
function_name = function_call.name
function_params = json.loads(function_call.arguments)
if function_name == "get_current_weather":
weather_data = fetch_weather(function_params["location"], function_params["unit"])
result_message = {
"role": "function",
"name": function_name,
"content": json.dumps(weather_data)
}
messages.append(response.choices[0].message)
messages.append(result_message)
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(final_response.choices[0].message.content)
else:
print(response.choices[0].message.content)
这部分代码检查 AI 是否决定调用函数:
- 如果 AI 调用了函数,代码会执行相应的函数(在这里是
fetch_weather
),然后将结果发送回 AI 进行进一步处理。 - 如果 AI 没有调用函数,直接打印 AI 的回复。
注意事项
fetch_weather
函数需要单独实现,用于获取实际的天气数据。- 代码假设使用的是 “gpt-4o” 模型,可能需要根据实际可用的模型进行调整。
- API 密钥和 URL 需要替换为您自己的有效凭证。
这段代码展示了如何使用 OpenAI 的函数调用功能。它允许 AI 助手理解何时需要额外的信息来回答用户的问题,并能够调用预定义的函数来获取这些信息。
在这个例子中,当用户询问天气时,AI 能够识别出需要调用 get_current_weather
函数来获取具体的天气信息。然后,代码执行这个函数(在实际应用中,这里会是一个真实的天气 API 调用),并将结果返回给 AI 进行解释和回答。
这种方法使得 AI 能够更灵活地处理需要外部信息的查询,提供更准确和及时的回答。