如何使用 Azure OpenAI

本文介绍如何使用OpenAI的Azure API来部署模型、创建补全和等待部署状态等操作,让你可以快速了解简单的操作,快速上手使用Azure API。

使用 Azure OpenAI

本篇文章介绍如何使用OpenAI的Azure API来部署模型、创建补全和等待部署状态等操作。阅读本文可以让你快速了解简单的操作,快速上手使用Azure API。

Azure 完成示例

在此示例中,我们将尝试遍历使用 Azure 端点完成工作所需的所有操作。
此示例侧重于完成,但也涉及使用 API 也可用的其他一些操作。 此示例旨在快速展示简单操作,并非教程。

import openai
from openai import cli

设置

为了使以下部分正常工作,我们首先必须设置一些东西。 让我们从 api_baseapi_version 开始。 要找到您的 api_base,请转到 https://portal.azure.com,找到您的资源,然后在“资源管理”->“键和端点”下查找“端点”值。

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

接下来我们必须设置 api_typeapi_key。 我们可以从门户网站获取密钥,也可以通过 Microsoft Active Directory 身份验证获取密钥。 取决于此,api_typeazureazure_ad

设置:门户

让我们首先看看从门户中获取密钥。 转到 https://portal.azure.com,找到您的资源,然后在“资源管理”->“Keys and Endpoints”下查找“Keys”值之一。

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

(可选)设置: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

部署

在本节中,我们将使用 text-davinci-002 模型创建一个部署,然后我们可以使用它来创建补全。

部署:手动创建

通过转到门户中“资源管理”->“模型部署”下的资源来创建新部署。 选择 text-davinci-002 作为模型。

(可选)部署:以编程方式创建

我们还可以使用代码创建部署:

model = "text-davinci-002"

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]
print(f'Successfully created deployment with id: {deployment_id}')

(可选)Deployments:等待部署成功

现在让我们检查新创建的部署的状态,等待它成功。

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} has status: {status}')
while status not in ["succeeded", "failed"]:
    resp = openai.Deployment.retrieve(id=deployment_id)
    status = resp["status"]
    print(f'Deployment {deployment_id} has status: {status}')

完工

现在让我们向部署发送示例完成。

prompt = "The food was delicious and the waiter"
completion = openai.Completion.create(deployment_id=deployment_id,
                                     prompt=prompt, stop=".", temperature=0)
                                
print(f"{prompt}{completion['choices'][0]['text']}.")

(可选)部署:删除

最后让我们删除部署

print(f'Deleting deployment: {deployment_id}')
openai.Deployment.delete(sid=deployment_id)

此文章由OpenAI开源维基百科原创发布,如若转载请注明出处:https://openai.wiki/openai-azure-completions-example.html

(0)
上一篇 2023-02-20 20:54
下一篇 2023-02-20 21:18

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

微信