Using Azure OpenAI Service (GPT-4) in .NET
Tags: azure, dotnet, openai, chatgpt
Published: 2024-01-30 18:33:01

Hey, there! In this tutorial, we'll see how to call an Azure OpenAI Service GPT model from C#.

### **Required data from Azure:**

**Key and endpoint** - We can find this information in the _Keys and endpoint_ section in our Azure OpenAI Service resource.

![Azure Resource - Key and endpoint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69imthhsiryevbq7sjq7.jpg)

**Deployment name** - This would be the instance of the model to use. In this case, we can go to the Azure OpenAI Service studio, and in the _Deployments_ section specify a new one:

![Azure OpenAI Service - Deployments](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/elwffty89wd57s0r8yeo.jpg)

### **Azure OpenAI client library for .NET**

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. 

This library will allow us to use the GPT model from C#.

NuGet package: [Azure.AI.OpenAI](https://www.nuget.org/packages/Azure.AI.OpenAI)

```cli
dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.12
```

### **Code in C#**

With the NuGet package installed, this is a C# class that will allow us to generate new text content using a specified prompt: 

```csharp
using Azure.AI.OpenAI;
using Azure;

namespace GenerativeAI;

public class AzureOpenAIGPT
{
    const string key = "YOUR_KEY";
    const string endpoint = "https://YOUR_RESOURCE_NAME.openai.azure.com/";
    const string deploymentOrModelName = "YOUR_DEPLOYMENT_NAME";

    public async Task<string> GetContent(string prompt)
    {
        var client = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));

        var chatCompletionsOptions = new ChatCompletionsOptions
        {
            DeploymentName = deploymentOrModelName,
            Temperature = (float)0.5,
            MaxTokens = 800,
            NucleusSamplingFactor = (float)0.95,
            FrequencyPenalty = 0,
            PresencePenalty = 0,
        };

        chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(prompt));
        var response = await client.GetChatCompletionsAsync(chatCompletionsOptions);

        return response.Value.Choices[0].Message.Content;
    }
}
```

In this code, it is important to mention that there are three types of messages or roles that can be considered for the interaction:

- **_ChatRequestSystemMessage_**: represent instructions or other guidance about how the assistant should behave. 
- **_ChatRequestUserMessage_**: represent current or historical input from the end user. 
- **_ChatRequestAssistantMessage_**: represent historical responses from the assistant.

Example of a call from the console:

```csharp
var gpt = new AzureOpenAIGPT();
var gptPrompt = "Generate a definition of Azure OpenAI Service";

Console.WriteLine($"{await gpt.GetContent(gptPrompt)}");
```

![Results in console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/niw1ngzpcp136qgsvuyi.jpg)

## **Thanks for reading!**

If you have any questions or ideas in mind, it'll be a pleasure to be able to be in communication with you, and together exchange knowledge with each other.

**Additional Resources:**

- [Generative AI with Azure OpenAI (GPT-4 Overview)](https://dev.to/esdanielgomez/generative-ai-with-azure-openai-gpt-4-overview-5el5)
- [Azure OpenAI client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/ai.openai-readme?view=azure-dotnet-preview&WT.mc_id=DT-MVP-5004317)
- [Microsoft Azure AI Fundamentals: Generative AI](https://learn.microsoft.com/en-us/training/paths/introduction-generative-ai/?WT.mc_id=DT-MVP-5004317). 

Contact: 
[X](https://twitter.com/esDanielGomez) / [LinkedIn](https://www.linkedin.com/in/esdanielgomez) - [esdanielgomez.com](https://esdanielgomez.com/)