Back

Step by Step Guide to Building an Azure OpenAI Service API Integration in C#

Aug 7, 20246 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your C# applications with the power of AI? Let's dive into integrating Azure OpenAI Service using the Azure.AI.OpenAI package. This guide will get you up and running in no time.

Prerequisites

Before we jump in, make sure you've got:

  • An Azure subscription (if you don't have one, now's the perfect time to sign up!)
  • An Azure OpenAI Service resource set up
  • Visual Studio or your favorite C# IDE
  • .NET 6.0 or later installed

Got all that? Great! Let's get coding.

Setting up the project

First things first, let's create a new C# console application. Once that's done, we need to add the Azure.AI.OpenAI package. Fire up your package manager console and run:

dotnet add package Azure.AI.OpenAI

Configuration

Now, head over to the Azure portal and grab your API key and endpoint. We'll need these to authenticate our requests.

Pro tip: Never hardcode these values! Instead, use environment variables or a configuration file. Your future self will thank you.

Initializing the OpenAIClient

Time to write some code! Start by importing the necessary namespaces:

using Azure; using Azure.AI.OpenAI;

Now, let's create an instance of OpenAIClient:

string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_KEY"); OpenAIClient client = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));

Making API calls

With our client set up, we're ready to make some API calls. Let's look at a few examples:

Completions

string deploymentName = "your-deployment-name"; string prompt = "Once upon a time"; Response<Completions> completionsResponse = await client.GetCompletionsAsync( deploymentName, new CompletionsOptions { Prompt = prompt } ); Console.WriteLine(completionsResponse.Value.Choices[0].Text);

Chat completions

string deploymentName = "your-deployment-name"; var chatCompletionsOptions = new ChatCompletionsOptions() { Messages = { new ChatMessage(ChatRole.System, "You are a helpful assistant."), new ChatMessage(ChatRole.User, "What's the capital of France?") } }; Response<ChatCompletions> response = await client.GetChatCompletionsAsync( deploymentName, chatCompletionsOptions ); Console.WriteLine(response.Value.Choices[0].Message.Content);

Error handling

Always wrap your API calls in try-catch blocks to handle any exceptions gracefully:

try { // Your API call here } catch (RequestFailedException ex) { Console.WriteLine($"API call failed: {ex.Message}"); }

Advanced usage

Streaming responses

For longer responses, you might want to stream the results:

await foreach (StreamingChatCompletionsUpdate update in client.GetChatCompletionsStreaming(deploymentName, chatCompletionsOptions)) { if (update.Role.HasValue) { Console.WriteLine($"Role: {update.Role}"); } if (!string.IsNullOrEmpty(update.Content)) { Console.Write(update.Content); } }

Managing tokens and rate limits

Keep an eye on your token usage and respect rate limits. The API responses include information about token usage, so make sure to log and monitor these.

Best practices

  • Always use secure methods to store and access your API keys.
  • Implement retry logic for transient failures.
  • Consider implementing a caching mechanism for frequently requested data.
  • Monitor your API usage to optimize performance and costs.

Conclusion

And there you have it! You're now equipped to integrate Azure OpenAI Service into your C# applications. Remember, the key to mastering this API is practice and experimentation. Don't be afraid to try out different prompts and parameters to see what works best for your use case.

Happy coding, and may your AI adventures be bug-free and endlessly exciting!

Further resources

Now go forth and create something awesome!