Getting Started with OpenAI .NET SDK: Add ChatGPT to Your C# App

Learn how to integrate ChatGPT into your C# applications using the official OpenAI .NET SDK. This step-by-step guide shows you how to set up the SDK, create a chat client, and build an interactive AI chat application. Includes code examples and best practices.

Hey there! 👋

If you prefer watching over reading, check out the video tutorial here:

The official OpenAI .NET SDK is now stable (as of October 1st), and it's a game-changer for .NET developers wanting to integrate AI into their applications. Think of it as your Swiss army knife for working with OpenAI's models - whether you're using them directly or through Azure OpenAI services.

Why Use the OpenAI .NET SDK?

  • It's the official tool from OpenAI and Microsoft for .NET developers
  • Works with all the latest OpenAI models (including GPT-4 and friends)
  • Super flexible and easy to use
  • Compatible with pretty much any modern .NET project (WebAPI, Console apps, you name it!)

Let's Build Something!

First, let's create a new console application. Open your terminal and run:

dotnet new console -n OpenAISDKDemo
cd OpenAISDKDemo

Install the OpenAI .NET SDK from NuGet:

dotnet add package OpenAI

Setting Up the Chat Client

We'll be working with the Chat namespace, which handles text conversations between OpenAI and your app. First, add the using statement:

using OpenAI.Chat;

Handling the API Key (The Right Way)

While you could hardcode your API key, let's do it properly using configuration. Install these packages:

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.FileExtensions
dotnet add package Microsoft.Extensions.Configuration.Json

Create an appsettings.json:

{
  "OpenAI": {
    "ApiKey": "your_api_key_here"
  }
}

Set up the configuration in your code:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

IConfiguration config = builder.Build();

string apiKey = config["OpenAI:ApiKey"] ?? 
    throw new InvalidOperationException("API key not found in configuration.");

ChatClient client = new(model: "gpt-4", apiKey: apiKey);

Making Your First Chat Request

Here's a simple example:

ChatCompletion completion = client.CompleteChat("Hi my name is Jeff.");
Console.WriteLine($"GPT >> {completion.Content[0].Text}");

Managing Conversation History

If you want GPT to remember previous messages (like your name), you need to maintain a conversation history. Here's how:

var messages = new List<ChatMessage>
{
    new SystemChatMessage("You are a helpful assistant.")
};

while (true)
{
    Console.Write("You >> ");
    var userInput = Console.ReadLine();
    
    if (string.IsNullOrEmpty(userInput))
        break;

    messages.Add(new UserChatMessage(userInput));
    ChatCompletion response = await client.CompleteChatAsync(messages);
    Console.WriteLine($"AI >> {response.Content[0].Text}");
    messages.Add(new AssistantChatMessage(response.Content[0].Text));
}

This code creates an interactive chat experience where the model remembers previous messages in the conversation.

What's Next?

This is just scratching the surface of what you can do with the OpenAI .NET SDK. You can work with images, audio, and much more! Let me know in the comments if you'd like to see tutorials on those topics.

Remember, while this example uses a console application, you can integrate this into any type of .NET application - whether it's a web API, desktop app, or mobile app.

Happy coding! 🚀

---

*P.S. If you found this helpful, don't forget to share it with your fellow developers!*


Further readings

More from Getting Started

More from the Web