Azure 嵌入示例
注意:OpenAI 库有新版本可用。请参阅 https://github.com/openai/openai-python/discussions/742
本示例将介绍如何使用 Azure OpenAI 服务进行嵌入。
设置
首先,我们安装必要的依赖项。
! pip install "openai>=0.28.1,<1.0.0"
为了使后续部分正常工作,我们首先需要进行一些设置。让我们从 api_base
和 api_version
开始。要查找您的 api_base
,请访问 https://portal.azure.com,找到您的资源,然后在“资源管理”->“密钥和终结点”下查找“终结点”值。
import os
import openai
openai.api_version = '2023-05-15'
openai.api_base = '' # 请在此处添加您的终结点
接下来,我们需要设置 api_type
和 api_key
。我们可以从门户获取密钥,也可以通过 Microsoft Active Directory 身份验证获取。根据此,api_type
为 azure
或 azure_ad
。
设置:门户
让我们先看看如何从门户获取密钥。访问 https://portal.azure.com,找到您的资源,然后在“资源管理”->“密钥和终结点”下查找“密钥”值之一。
openai.api_type = 'azure'
openai.api_key = os.environ["OPENAI_API_KEY"]
注意:在此示例中,我们通过在代码中设置变量来配置库以使用 Azure API。对于开发,请考虑改用设置环境变量:
OPENAI_API_BASE
OPENAI_API_KEY
OPENAI_API_TYPE
OPENAI_API_VERSION
(可选)设置:Microsoft Active Directory 身份验证
现在让我们看看如何通过 Microsoft Active Directory 身份验证获取密钥。如果您想使用 Active Directory 身份验证而不是门户中的密钥,请取消注释以下代码。
# from azure.identity import DefaultAzureCredential
# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")
# openai.api_type = 'azure_ad'
# openai.api_key = token.token
令牌在一段时间内有效,之后会过期。为了确保每次请求都发送有效的令牌,您可以通过挂钩到 requests.auth 来刷新即将过期的令牌:
import typing
import time
import requests
if typing.TYPE_CHECKING:
from azure.core.credentials import TokenCredential
class TokenRefresh(requests.auth.AuthBase):
def __init__(self, credential: "TokenCredential", scopes: typing.List[str]) -> None:
self.credential = credential
self.scopes = scopes
self.cached_token: typing.Optional[str] = None
def __call__(self, req):
if not self.cached_token or self.cached_token.expires_on - time.time() < 300:
self.cached_token = self.credential.get_token(*self.scopes)
req.headers["Authorization"] = f"Bearer {self.cached_token.token}"
return req
session = requests.Session()
session.auth = TokenRefresh(default_credential, ["https://cognitiveservices.azure.com/.default"])
openai.requestssession = session
部署
在本节中,我们将创建一个可用于创建嵌入的部署。
部署:手动创建
让我们使用 text-similarity-curie-001
模型创建一个部署。通过在门户中导航到您的资源,然后在“资源管理”->“模型部署”下,创建一个新部署。
deployment_id = '' # 在此处填写门户中的部署 ID
部署:列出
现在,因为创建新部署需要很长时间,所以让我们在订阅中查找一个已经完成且成功的部署。
print('在部署运行时,选择一个已完成且支持嵌入的部署。')
deployment_id = None
result = openai.Deployment.list()
for deployment in result.data:
if deployment["status"] != "succeeded":
continue
model = openai.Model.retrieve(deployment["model"])
if model["capabilities"]["embeddings"] != True:
continue
deployment_id = deployment["id"]
break
if not deployment_id:
print('未找到状态为“succeeded”的部署。')
else:
print(f'找到一个状态为“succeeded”且支持嵌入的部署,ID 为:{deployment_id}。')
嵌入
现在让我们向部署发送一个示例嵌入。
embeddings = openai.Embedding.create(deployment_id=deployment_id,
input="The food was delicious and the waiter...")
print(embeddings)