Azure OpenAI client library for .NET

Publish date: 2024-06-15

The Azure OpenAI client library for .NET is an adaptation of OpenAI's REST APIs that provides an idiomatic interface and rich integration with the rest of the Azure SDK ecosystem. It can connect to Azure OpenAI resources or to the non-Azure OpenAI inference endpoint, making it a great choice for even non-Azure OpenAI development.

Use the client library for Azure OpenAI to:

Azure OpenAI is a managed service that allows developers to deploy, tune, and generate content from OpenAI models on Azure resources.

Source code | Package (NuGet) | API reference documentation | Product documentation | Samples

Getting started

Prerequisites

If you'd like to use an Azure OpenAI resource, you must have an Azure subscription and Azure OpenAI access. This will allow you to create an Azure OpenAI resource and get both a connection URL as well as API keys. For more information, see Quickstart: Get started generating text using Azure OpenAI Service.

If you'd like to use the Azure OpenAI .NET client library to connect to non-Azure OpenAI, you'll need an API key from a developer account at https://platform.openai.com/.

Install the package

Install the client library for .NET with NuGet:

dotnet add package Azure.AI.OpenAI --prerelease 

Authenticate the client

In order to interact with Azure OpenAI or OpenAI, you'll need to create an instance of the OpenAIClient class. To configure a client for use with Azure OpenAI, provide a valid endpoint URI to an Azure OpenAI resource along with a corresponding key credential, token credential, or Azure identity credential that's authorized to use the Azure OpenAI resource. To instead configure the client to connect to OpenAI's service, provide an API key from OpenAI's developer portal.

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"); 

Create OpenAIClient with an Azure Active Directory Credential

Client subscription key authentication is used in most of the examples in this getting started guide, but you can also authenticate with Azure Active Directory using the Azure Identity library. To use the DefaultAzureCredential provider shown below, or other credential providers provided with the Azure SDK, please install the Azure.Identity package:

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

Key concepts

The main concept to understand is Completions. Briefly explained, completions provides its functionality in the form of a text prompt, which by using a specific model, will then attempt to match the context and patterns, providing an output text. The following code snippet provides a rough overview (more details can be found in the GenerateChatbotResponsesWithToken sample code):

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); } 

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

Examples

You can familiarize yourself with different APIs using Samples.

Generate Chatbot Response

The GenerateChatbotResponse method authenticates using a DefaultAzureCredential, then generates text responses to input prompts.

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}"); 

Generate Multiple Chatbot Responses With Subscription Key

The GenerateMultipleChatbotResponsesWithSubscriptionKey method gives an example of generating text responses to input prompts using an Azure subscription key

// 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}"); } 

Summarize Text with Completion

The SummarizeText method generates a summarization of the given input prompt.

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}"); 

Stream Chat Messages with non-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(); } 

Troubleshooting

When you interact with Azure OpenAI using the .NET SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests.

For example, if you try to create a client using an endpoint that doesn't match your Azure OpenAI Resource endpoint, a 404 error is returned, indicating Resource Not Found.

Next steps

Contributing

See the OpenAI CONTRIBUTING.md for details on building, testing, and contributing to this library.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions

ncG1vNJzZmiZqqq%2Fpr%2FDpJuom6Njr627wWeaqKqVY8SqusOorqxmnprBcHDWnplonJ%2Bpu6bAjnqxrqqVY46Keq6pnKd5eWR%2Bb3yNaWSbnaSWe3Z7yKebnrBencGuuA%3D%3D