本示例将介绍如何使用Azure OpenAI服务进行嵌入。
设置
首先,我们安装必要的依赖项并导入将要使用的库。
! 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使用API密钥进行身份验证
要设置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 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
部署
在本节中,我们将创建一个模型部署,用于生成嵌入向量。
部署:在Azure OpenAI Studio中创建
让我们部署一个用于嵌入的模型。前往https://portal.azure.com,找到您的Azure OpenAI资源,然后导航到Azure OpenAI Studio。点击"Deployments"选项卡,为您想用于嵌入的模型创建一个部署。您为模型指定的部署名称将用于下面的代码中。
deployment = "" # Fill in the deployment name from the portal hereEmbeddings
现在让我们使用我们构建的客户端来创建嵌入。
embeddings = client.embeddings.create(
model=deployment,
input="The food was delicious and the waiter..."
)
print(embeddings)