將 OpenAI 整合到應用程式中

已完成

Azure OpenAI 提供特定語言的 SDK 和 REST API,以及開發人員可用來將 AI 功能新增至其應用程式的 REST API。 Azure OpenAI 中的 Ai 功能會透過 模型提供。 Azure OpenAI 服務中可用的模型分屬於不同的系列,擁有各自的專長。 若要使用其中一個模型,您必須透過 Azure OpenAI 服務進行部署。

建立 Azure OpenAI 資源並部署模型後,您就可以設定應用程式。

可用的端點

Azure OpenAI 可以透過 REST API 或適用於 Python、C#、JavaScript 等的 SDK 進行存取。 能夠與已部署模型互動的端點用途各不相同,而某些端點只能使用特定模型。 可用的端點包括:

  • Completion - 模型會接受輸入提示,並產生一或多個預測的結果。 您會在工作室中看到此遊樂場,但在此課程模組中不會對其進行深入討論。
  • ChatCompletion - 模型會採用聊天交談形式的輸入 (根據傳送的訊息來指定角色),並產生下一個聊天結果。
  • Embeddings - 模型會接受輸入,並傳回該輸入的向量標記法。

例如,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

內嵌對於機器學習模型容易取用的特定格式很有幫助。 若要從輸入文字產生內嵌,請向 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