共用方式為


適用于 .NET 的 Azure OpenAI 用戶端程式庫 - 1.0.0-Beta.5 版

適用于 .NET 的 Azure OpenAI 用戶端程式庫是 OpenAI REST API 的調整,可提供慣用的介面,並與 Azure SDK 生態系統的其餘部分進行豐富的整合。 它可以連線到 Azure OpenAI 資源 非 Azure OpenAI 推斷端點,使其成為即使是非 Azure OpenAI 開發的絕佳選擇。

使用適用于 Azure OpenAI 的用戶端程式庫來:

Azure OpenAI 是一項受控服務,可讓開發人員從 Azure 資源上的 OpenAI 模型部署、調整和產生內容。

| 原始程式碼套件 (NuGet) | API 參考檔 | 產品檔 | 樣品

開始使用

Prerequisites

如果您想要使用 Azure OpenAI 資源,您必須擁有 Azure 訂 用帳戶和 Azure OpenAI 存取權。 這可讓您建立 Azure OpenAI 資源,並同時取得連線 URL 和 API 金鑰。 如需詳細資訊,請參閱 快速入門:開始使用 Azure OpenAI 服務產生文字

如果您想要使用 Azure OpenAI .NET 用戶端程式庫來連線到非 Azure OpenAI,您需要來自開發人員帳戶的 https://platform.openai.com/ API 金鑰。

安裝套件

使用 NuGet安裝適用于 .NET 的用戶端程式庫:

dotnet add package Azure.AI.OpenAI --prerelease

驗證用戶端

若要與 Azure OpenAI 或 OpenAI 互動,您必須建立 OpenAIClient 類別的實例。 若要設定用戶端以搭配 Azure OpenAI 使用,請提供有效的端點 URI 給 Azure OpenAI 資源,以及授權使用 Azure OpenAI 資源的對應金鑰認證、權杖認證或 Azure 身分識別認證。 若要改為將用戶端設定為連線至 OpenAI 的服務,請從 OpenAI 的開發人員入口網站提供 API 金鑰。

OpenAIClient client = useAzureOpenAI
    ? new OpenAIClient(
        new Uri("https://your-azure-openai-resource.com/"),
        new AzureKeyCredential("your-azure-openai-resource-api-key"))
    : new OpenAIClient("your-api-key-from-platform.openai.com");

使用 Azure Active Directory 認證建立 OpenAIClient

用戶端訂用帳戶金鑰驗證用於本入門指南的大部分範例中,但您也可以使用 Azure 身分識別程式庫向 Azure Active Directory 進行驗證。 若要使用如下所示的 DefaultAzureCredential 提供者,或其他隨附于 Azure SDK 的認證提供者,請安裝 Azure.Identity 套件:

dotnet add package Azure.Identity
string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

重要概念

要瞭解的主要概念是 完成。 簡短說明,完成會以文字提示的形式提供其功能,該提示會使用特定 模型,然後嘗試比對內容和模式,並提供輸出文字。 下列程式碼片段提供粗略概觀, (您可以在範例程式碼) 中找到 GenerateChatbotResponsesWithToken 更多詳細資料:

OpenAIClient client = useAzureOpenAI
    ? new OpenAIClient(
        new Uri("https://your-azure-openai-resource.com/"),
        new AzureKeyCredential("your-azure-openai-resource-api-key"))
    : new OpenAIClient("your-api-key-from-platform.openai.com");

Response<Completions> response = await client.GetCompletionsAsync(
    "text-davinci-003", // assumes a matching model deployment or model name
    "Hello, world!");

foreach (Choice choice in response.Value.Choices)
{
    Console.WriteLine(choice.Text);
}

執行緒安全

我們保證所有用戶端實例方法都是安全線程,且彼此獨立 (指導方針) 。 這可確保重複使用用戶端實例的建議一律是安全的,即使是跨執行緒也一樣。

其他概念

用戶端選項 | 存取回應 | 長時間執行的作業 | 處理失敗 | 診斷 | 嘲笑 | 用戶端存留期

範例

您可以使用 範例熟悉不同的 API。

產生 Chatbot 回應

方法會 GenerateChatbotResponse 使用 DefaultAzureCredential 進行驗證,然後產生輸入提示的文字回應。

string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

string deploymentName = "text-davinci-003";
string prompt = "What is Azure OpenAI?";
Console.Write($"Input: {prompt}");

Response<Completions> completionsResponse = client.GetCompletions(deploymentName, prompt);
string completion = completionsResponse.Value.Choices[0].Text;
Console.WriteLine($"Chatbot: {completion}");

使用訂用帳戶金鑰產生多個 Chatbot 回應

方法 GenerateMultipleChatbotResponsesWithSubscriptionKey 提供使用 Azure 訂用帳戶金鑰產生輸入提示文字回應的範例

// Replace with your Azure OpenAI key
string key = "YOUR_AZURE_OPENAI_KEY";
string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));

List<string> examplePrompts = new(){
    "How are you today?",
    "What is Azure OpenAI?",
    "Why do children love dinosaurs?",
    "Generate a proof of Euler's identity",
    "Describe in single words only the good things that come into your mind about your mother.",
};

string deploymentName = "text-davinci-003";

foreach (string prompt in examplePrompts)
{
    Console.Write($"Input: {prompt}");
    CompletionsOptions completionsOptions = new CompletionsOptions();
    completionsOptions.Prompts.Add(prompt);

    Response<Completions> completionsResponse = client.GetCompletions(deploymentName, completionsOptions);
    string completion = completionsResponse.Value.Choices[0].Text;
    Console.WriteLine($"Chatbot: {completion}");
}

完成的摘要文字

方法 SummarizeText 會產生指定輸入提示的摘要。

string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

string textToSummarize = @"
    Two independent experiments reported their results this morning at CERN, Europe's high-energy physics laboratory near Geneva in Switzerland. Both show convincing evidence of a new boson particle weighing around 125 gigaelectronvolts, which so far fits predictions of the Higgs previously made by theoretical physicists.

    ""As a layman I would say: 'I think we have it'. Would you agree?"" Rolf-Dieter Heuer, CERN's director-general, asked the packed auditorium. The physicists assembled there burst into applause.
:";

string summarizationPrompt = @$"
    Summarize the following text.

    Text:
    """"""
    {textToSummarize}
    """"""

    Summary:
";

Console.Write($"Input: {summarizationPrompt}");
var completionsOptions = new CompletionsOptions()
{
    Prompts = { summarizationPrompt },
};

string deploymentName = "text-davinci-003";

Response<Completions> completionsResponse = client.GetCompletions(deploymentName, completionsOptions);
string completion = completionsResponse.Value.Choices[0].Text;
Console.WriteLine($"Summarization: {completion}");

使用非 Azure OpenAI 串流聊天訊息

string nonAzureOpenAIApiKey = "your-api-key-from-platform.openai.com";
var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
var chatCompletionsOptions = new ChatCompletionsOptions()
{
    Messages =
    {
        new ChatMessage(ChatRole.System, "You are a helpful assistant. You will talk like a pirate."),
        new ChatMessage(ChatRole.User, "Can you help me?"),
        new ChatMessage(ChatRole.Assistant, "Arrrr! Of course, me hearty! What can I do for ye?"),
        new ChatMessage(ChatRole.User, "What's the best way to train a parrot?"),
    }
};

Response<StreamingChatCompletions> response = await client.GetChatCompletionsStreamingAsync(
    deploymentOrModelName: "gpt-3.5-turbo",
    chatCompletionsOptions);
using StreamingChatCompletions streamingChatCompletions = response.Value;

await foreach (StreamingChatChoice choice in streamingChatCompletions.GetChoicesStreaming())
{
    await foreach (ChatMessage message in choice.GetMessageStreaming())
    {
        Console.Write(message.Content);
    }
    Console.WriteLine();
}

疑難排解

當您使用 .NET SDK 與 Azure OpenAI 互動時,服務傳回的錯誤會對應至 針對 REST API 要求傳回的相同 HTTP 狀態碼。

例如,如果您嘗試使用不符合 Azure OpenAI 資源端點的端點來建立用戶端, 404 則會傳回錯誤,表示 Resource Not Found

下一步

  • 提供其他程式碼範例的連結,在理想情況下,這些範例會與套件目錄中 /samples 的讀我檔案一起。
  • 如果適當,請將使用者指向可能有用的其他套件。
  • 如果您認為開發人員可能會在錯誤 (中輪轉套件,因為開發人員正在搜尋特定功能,並誤認為套件提供該功能) ,請指向他們可能尋找的套件。

參與

如需建置、測試及參與此程式庫的詳細資訊,請參閱 OpenAI CONTRIBUTING.md

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資訊,請造訪 cla.microsoft.com

當您提交提取要求時,CLA Bot 會自動判斷您是否需要提供 CLA,並適當地裝飾 PR (例如標籤、註解)。 請遵循 bot 提供的指示。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。

此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com

曝光數