Use C# to Connect to OpenAI Chat GPT

In this Microsoft .NET C# and OpenAI post, we will show how to use C# to connect to the OpenAI API and generate chat completions.

The Microsoft .NET official OpenAI client library provides REST API access to the OpenAI and Azure OpenAI platforms. This post will only show how to connect to the OpenAI platform using an API and an active plan.

In our case, we are using Visual Studio 2022, the latest build with .NET 7.0.

Install Library

To install the OpenAI client library, we can use the following command or the package manager within the project.

dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.6

In the package manager, look for the following package

Code

using System.Text;
using Azure;
using Azure.AI.OpenAI;



string nonAzureOpenAIApiKey = "YOUR OPEN AI API Key";
var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
var chatCompletionsOptions = new ChatCompletionsOptions()
{
    Messages =
    {
        new ChatMessage(ChatRole.System, "tell me about ntweekly.com"),
       // new ChatMessage(ChatRole.User, "something"),
       // new ChatMessage(ChatRole.Assistant, "something"),
       // new ChatMessage(ChatRole.User, "something"),
    }
};

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

Model Configuration

The model uses the gpt-3.5-turbo in the above code, but it can easily change to another model by changing the name. To use GPT 4, change to gpt-4.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.