此 notebook 演示了如何将函数调用功能与 Azure OpenAI 服务一起使用。函数允许聊天完成的调用者定义模型可以使用的功能,以将其功能扩展到外部工具和数据源。
您可以在 OpenAI 的博客上阅读有关聊天功能的更多信息:https://openai.com/blog/function-calling-and-other-api-updates
注意:聊天函数需要以 -0613
标签开头的 gpt-4 和 gpt-35-turbo 模型版本。较旧版本的模型不支持它们。
此 notebook 演示了如何将函数调用功能与 Azure OpenAI 服务一起使用。函数允许聊天完成的调用者定义模型可以使用的功能,以将其功能扩展到外部工具和数据源。
您可以在 OpenAI 的博客上阅读有关聊天功能的更多信息:https://openai.com/blog/function-calling-and-other-api-updates
注意:聊天函数需要以 -0613
标签开头的 gpt-4 和 gpt-35-turbo 模型版本。较旧版本的模型不支持它们。
首先,我们安装必要的依赖项并导入我们将要使用的库。
! pip install "openai>=1.0.0,<2.0.0"
! pip install python-dotenv
import os
import openai
import dotenv
dotenv.load_dotenv()
Azure OpenAI 服务支持多种身份验证机制,包括 API 密钥和 Azure Active Directory 令牌凭据。
use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory
要设置 OpenAI SDK 以使用Azure API 密钥,我们需要将 api_key
设置为与您的端点关联的密钥(您可以在 Azure 门户中的“资源管理”下的“密钥和终结点”中找到此密钥)。您还可以在此处找到资源的端点。
if not use_azure_active_directory:
endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
api_key = os.environ["AZURE_OPENAI_API_KEY"]
client = openai.AzureOpenAI(
azure_endpoint=endpoint,
api_key=api_key,
api_version="2023-09-01-preview"
)
现在让我们看看如何通过 Azure Active Directory 进行身份验证。我们将首先安装 azure-identity
库。此库将提供我们进行身份验证所需的令牌凭据,并通过 get_bearer_token_provider
帮助程序函数帮助我们构建令牌凭据提供程序。建议使用 get_bearer_token_provider
而不是向 AzureOpenAI
提供静态令牌,因为此 API 将自动缓存和刷新令牌。
有关如何设置 Azure Active Directory 身份验证与 Azure OpenAI 的更多信息,请参阅文档。
! pip install "azure-identity>=1.15.0"
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
if use_azure_active_directory:
endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
api_key = os.environ["AZURE_OPENAI_API_KEY"]
client = openai.AzureOpenAI(
azure_endpoint=endpoint,
azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"),
api_version="2023-09-01-preview"
)
注意:如果未提供 AzureOpenAI,则会从其对应的环境变量中推断以下参数
AZURE_OPENAI_API_KEY
获取 api_key
AZURE_OPENAI_AD_TOKEN
获取 azure_ad_token
OPENAI_API_VERSION
获取 api_version
AZURE_OPENAI_ENDPOINT
获取 azure_endpoint
在本节中,我们将创建一个 GPT 模型的部署,我们可以使用该模型来调用函数。
让我们部署一个模型以用于聊天完成。转到 https://portal.azure.com,找到您的 Azure OpenAI 资源,然后导航到 Azure OpenAI Studio。单击“部署”选项卡,然后为您要用于聊天完成的模型创建部署。您为模型提供的部署名称将在下面的代码中使用。
deployment = "" # Fill in the deployment name from the portal here
完成设置和身份验证后,您现在可以将函数与 Azure OpenAI 服务一起使用。这将分为几个步骤
可以定义函数列表,每个函数都包含函数名称、可选描述以及函数接受的参数(描述为 JSON 模式)。
functions = [
{
"name": "get_current_weather",
"description": "Get the current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The temperature unit to use. Infer this from the users location.",
},
},
"required": ["location"],
},
}
]
现在我们可以将函数传递到聊天完成 API 中。如果模型确定它应该调用该函数,则将在选择中填充“tool_calls”的 finish_reason
,并且要调用的函数及其参数的详细信息将显示在 message
中。或者,您可以设置 tool_choice
关键字参数以强制模型调用特定函数(例如 {"type": "function", "function": {"name": get_current_weather}}
)。默认情况下,这设置为 auto
,允许模型选择是否调用该函数。
messages = [
{"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."},
{"role": "user", "content": "What's the weather like today in Seattle?"}
]
chat_completion = client.chat.completions.create(
model=deployment,
messages=messages,
tools=functions,
)
print(chat_completion)
函数调用的名称将是最初提供的名称之一,并且参数将包括与函数定义中包含的模式匹配的 JSON。
import json
def get_current_weather(request):
"""
This function is for illustrative purposes.
The location and unit should be used to determine weather
instead of returning a hardcoded response.
"""
location = request.get("location")
unit = request.get("unit")
return {"temperature": "22", "unit": "celsius", "description": "Sunny"}
function_call = chat_completion.choices[0].message.tool_calls[0].function
print(function_call.name)
print(function_call.arguments)
if function_call.name == "get_current_weather":
response = get_current_weather(json.loads(function_call.arguments))
函数的响应应序列化为新消息,并将角色设置为“function”。现在,模型将使用响应数据来制定其答案。
messages.append(
{
"role": "function",
"name": "get_current_weather",
"content": json.dumps(response)
}
)
function_completion = client.chat.completions.create(
model=deployment,
messages=messages,
tools=functions,
)
print(function_completion.choices[0].message.content.strip())