本笔记本展示如何在Azure OpenAI服务中使用函数调用功能。函数允许聊天补全的调用者定义能力,使模型能够利用这些能力将其功能扩展到外部工具和数据源。
你可以在OpenAI的博客上了解更多关于聊天功能的信息:https://openai.com/blog/function-calling-and-other-api-updates
注意: 聊天功能需要模型版本以gpt-4和gpt-35-turbo的-0613标签开头。旧版本的模型不支持这些功能。
本笔记本展示如何在Azure OpenAI服务中使用函数调用功能。函数允许聊天补全的调用者定义能力,使模型能够利用这些能力将其功能扩展到外部工具和数据源。
你可以在OpenAI的博客上了解更多关于聊天功能的信息:https://openai.com/blog/function-calling-and-other-api-updates
注意: 聊天功能需要模型版本以gpt-4和gpt-35-turbo的-0613标签开头。旧版本的模型不支持这些功能。
首先,我们安装必要的依赖项并导入将要使用的库。
! pip install "openai>=1.0.0,<2.0.0"
! pip install python-dotenvimport 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 OpenAI与Azure Active Directory身份验证的更多信息,请参阅文档。
! 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会从相应的环境变量中推断这些参数:
api_key 来自 AZURE_OPENAI_API_KEYazure_ad_token 来自 AZURE_OPENAI_AD_TOKENapi_version 来自 OPENAI_API_VERSIONazure_endpoint 来自 AZURE_OPENAI_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。如果模型确定应该调用该函数,选择项中将填充finish_reason为"tool_calls",并且要调用的函数及其参数详情将出现在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())