将 OpenAI 集成到应用中

已完成

Azure OpenAI 提供特定于语言的 SDK 和 REST API,开发人员可以用来向其应用程序添加 AI 功能。 Azure OpenAI 中的生成式 AI 功能通过模型提供。 Azure OpenAI 服务中可用的模型属于不同的系列,每个系列都有自己的重点。 若要使用这些模型之一,需要通过 Azure OpenAI 服务进行部署。

创建 Azure OpenAI 资源并部署模型后,即可配置应用。

可用的终结点

可以通过 REST API 或适用于 Python、C#、JavaScript 等的 SDK 访问 Azure OpenAI。 可用于与已部署模型交互的终结点的使用方式不同,并且某些终结点只能使用某些模型。 可用的终结点包括:

  • 完成 - 模型接受一个输入提示,并生成一个或多个预测的完成。 你将在 studio 中看到此操场,但在本模块中不会深入讨论。
  • ChatCompletion - 模型接受聊天对话形式的输入(其中角色使用他们发送的消息指定),然后生成下一个聊天完成。
  • 嵌入 - 模型接受输入并返回该输入的矢量表示形式。

例如,ChatCompletion 的输入是每条消息都有明确定义角色的会话:

{"role": "system", "content": "You are a helpful assistant, teaching people about AI."},
{"role": "user", "content": "Does Azure OpenAI support multiple languages?"},
{"role": "assistant", "content": "Yes, Azure OpenAI supports several languages, and can translate between them."},
{"role": "user", "content": "Do other Azure AI Services support translation too?"}

当你为 AI 模型提供一个真实的对话时,它可以生成具有更准确的语气、措辞和上下文的更好响应。 ChatCompletion 终结点通过发送与下一个用户消息的聊天历史记录,使模型能够进行更真实的对话。

ChatCompletion 还支持非聊天场景,例如摘要或实体提取。 可通过提供简短对话、指定系统信息和所需内容,并让用户输入信息来实现此操作。 例如,如果要生成工作描述,请向 ChatCompletion 提供类似于以下对话输入的内容。

{"role": "system", "content": "You are an assistant designed to write intriguing job descriptions."},
{"role": "user", "content": "Write a job description for the following job title: 'Business Intelligence Analyst'. It should include responsibilities, required qualifications, and highlight benefits like time off and flexible hours."}

注意

Completion 适用于较早的 gpt-3 生成模型,而 ChatCompletiongpt-4 模型唯一支持的选项,并且是使用 gpt-35-turbo 模型时的首选终结点。

使用 Azure OpenAI REST API

Azure OpenAI 提供了一个 REST API 用于交互和生成响应,开发人员可以使用它将 AI 功能添加到其应用程序。 本单元介绍 API 的示例用法、输入和输出。

每次调用 REST API 时,都需要 Azure OpenAI 资源的终结点和密钥,以及为部署的模型提供的名称。 在以下示例中,使用以下占位符:

占位符名称
YOUR_ENDPOINT_NAME 此基本终结点位于 Azure 门户的“密钥和终结点”部分。 它是资源的基本终结点,例如 https://sample.openai.azure.com/
YOUR_API_KEY 密钥位于 Azure 门户的“密钥和终结点”部分。 可以在资源中使用任一密钥。
YOUR_DEPLOYMENT_NAME 此部署名称是在 Azure AI Foundry 中部署模型时提供的名称。

聊天完成

在 Azure OpenAI 资源中部署模型后,可以使用 POST 请求向服务发送提示。

curl https://YOUR_ENDPOINT_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/chat/completions?api-version=2023-03-15-preview \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_API_KEY" \
  -d '{"messages":[{"role": "system", "content": "You are a helpful assistant, teaching people about AI."},
{"role": "user", "content": "Does Azure OpenAI support multiple languages?"},
{"role": "assistant", "content": "Yes, Azure OpenAI supports several languages, and can translate between them."},
{"role": "user", "content": "Do other Azure AI Services support translation too?"}]}'

来自 API 的响应将类似于以下 JSON:

{
    "id": "chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
    "object": "chat.completion",
    "created": 1679001781,
    "model": "gpt-35-turbo",
    "usage": {
        "prompt_tokens": 95,
        "completion_tokens": 84,
        "total_tokens": 179
    },
    "choices": [
        {
            "message":
                {
                    "role": "assistant",
                    "content": "Yes, other Azure AI Services also support translation. Azure AI Services offer translation between multiple languages for text, documents, or custom translation through Azure AI Services Translator."
                },
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

REST 终结点允许指定其他可选输入参数,如 temperaturemax_tokens 等。 如果要在请求中包含任何这些参数,请根据请求将它们添加到输入数据中。

嵌入

嵌入对机器学习模型轻松使用的特定格式很有帮助。 若要从输入文本生成嵌入,请向 embeddings 终结点发出 POST 请求。

curl https://YOUR_ENDPOINT_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version=2022-12-01 \
  -H "Content-Type: application/json" \
  -H "api-key: YOUR_API_KEY" \
  -d "{\"input\": \"The food was delicious and the waiter...\"}"

生成嵌入时,请确保在 Azure OpenAI 中使用用于嵌入的模型。 这些模型以 text-embeddingtext-similarity 开头,具体取决于你要查找的功能。

来自 API 的响应将类似于以下 JSON:

{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "embedding": [
        0.0172990688066482523,
        -0.0291879814639389515,
        ....
        0.0134544348834753042,
      ],
      "index": 0
    }
  ],
  "model": "text-embedding-ada:002"
}

将 Azure OpenAI 与 SDK 配合使用

除了 REST API 之外,用户还可以通过 C# 和 Python SDK 访问 Azure OpenAI 模型。 通过 REST 和这些 SDK 提供相同的功能。

对于本单元中介绍的 SDK,需要 Azure OpenAI 资源的终结点和密钥,以及为部署的模型提供的名称。 在以下代码片段中,使用以下占位符:

占位符名称
YOUR_ENDPOINT_NAME 此基本终结点位于 Azure 门户的“密钥和终结点”部分。 它是资源的基本终结点,例如 https://sample.openai.azure.com/
YOUR_API_KEY 密钥位于 Azure 门户的“密钥和终结点”部分。 可以在资源中使用任一密钥。
YOUR_DEPLOYMENT_NAME 此部署名称是部署模型时提供的名称。

安装库

首先,安装首选语言的客户端库。 C# SDK 是 REST API 的 .NET 适应,专为 Azure OpenAI 而构建,但它可用于连接到 Azure OpenAI 资源或非 Azure OpenAI 终结点。 Python SDK 由 OpenAI 生成和维护。

dotnet add package Azure.AI.OpenAI --version <insert preferred version>
pip install openai

配置应用以访问 Azure OpenAI 资源

每种语言的配置略有不同,但两种语言都需要设置相同的参数。 必要参数为 endpointkeydeployment name

将库添加到应用,并为客户端设置所需的参数。

// Add Azure OpenAI packages
using Azure.AI.OpenAI;
using OpenAI.Chat;

// Define parameters and initialize the client
string endpoint = "<YOUR_ENDPOINT_NAME>";
string key = "<YOUR_API_KEY>";
string deploymentName = "<YOUR_DEPLOYMENT_NAME>"; 

AzureOpenAIClient azureClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
ChatClient chatClient = azureClient.GetChatClient(deploymentName);
# Add OpenAI library
from openai import AzureOpenAI

deployment_name = '<YOUR_DEPLOYMENT_NAME>' 

# Initialize the Azure OpenAI client
client = AzureOpenAI(
        azure_endpoint = '<YOUR_ENDPOINT_NAME>', 
        api_key='<YOUR_API_KEY>',  
        api_version="20xx-xx-xx" #  Target version of the API, such as 2024-02-15-preview
        )

调用 Azure OpenAI 资源

配置与 Azure OpenAI 的连接后,将提示发送给模型。

// Get chat completion
ChatCompletion completion = chatClient.CompleteChat(
    [
        new SystemChatMessage(systemMessage),
        new UserChatMessage(userMessage),
    ]);

// Print the response
Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
response = client.chat.completions.create(
    model=deployment_name,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is Azure OpenAI?"}
    ]
)
generated_text = response.choices[0].message.content

# Print the response
print("Response: " + generated_text + "\n")

响应对象包含多个值,例如 total_tokensfinish_reason。 响应对象的完成类似于以下完成:

"Azure OpenAI is a cloud-based artificial intelligence (AI) service that offers a range of tools and services for developing and deploying AI applications. Azure OpenAI provides a variety of services for training and deploying machine learning models, including a managed service for training and deploying deep learning models, a managed service for deploying machine learning models, and a managed service for managing and deploying machine learning models."

在 C# 和 Python 中,调用可以包含可选参数,其中包括 temperaturemax_tokens