← Back to Blog Our Take

OpenAI Chat Completions With .NET & C#

November 24, 2024
OpenAI Chat Completions With .NET & C#

Integrating AI into your .NET applications has never been easier. This guide walks you through implementing OpenAI’s chat completions API in C#, creating a functional chatbot in just a few lines of code.

Prerequisites

  • OpenAI account with API access
  • .NET development environment
  • OpenAI API key

Step 1: Create a New Console Application

dotnet new console -n OpenAIChatBot
cd OpenAIChatBot

Step 2: Install the OpenAI NuGet Package

dotnet add package OpenAI

Step 3: Import Required Namespaces

using OpenAI.Chat;

Step 4: Set Up OpenAI API Client

var openAIApiKey = ""; // Your OpenAI API key here
var client = new ChatClient("gpt-4o", openAIApiKey);

Step 5: Create Chat Message Container

var messages = new List<ChatMessage>
{
    // Optional: Add a system message to customize the AI's behavior
    new SystemChatMessage("You have a Southern accent and are friendly!")
};

Step 6: Implement the Chat Loop

while (true)
{
    var line = Console.ReadLine();
    if (line == "exit")
    {
        break;
    }

    messages.Add(new UserChatMessage(line));

    var response = await client.CompleteChatAsync(messages);
    var chatResponse = response.Value.Content.Last().Text;

    Console.WriteLine(chatResponse);

    messages.Add(new AssistantChatMessage(chatResponse));
}

Complete Code Example

Here’s the full implementation combining all the steps:

using OpenAI.Chat;

var openAIApiKey = ""; // Your OpenAI API key
var client = new ChatClient("gpt-4o", openAIApiKey);

var messages = new List<ChatMessage>
{
    // Optional: Add a system message to customize behavior
    new SystemChatMessage("You have a Southern accent and are friendly!")
};

while (true)
{
    var line = Console.ReadLine();
    if (line == "exit")
    {
        break;
    }

    messages.Add(new UserChatMessage(line));

    var response = await client.CompleteChatAsync(messages);
    var chatResponse = response.Value.Content.Last().Text;

    Console.WriteLine(chatResponse);

    messages.Add(new AssistantChatMessage(chatResponse));
}

Configuration Details

  1. API Key: Obtain your API key from the OpenAI Developer Platform
  2. Model Selection: The example uses “gpt-4o” but you can use other models like “gpt-3.5-turbo”
  3. Billing: Ensure you have billing credits available in your OpenAI account
  4. Rate Limits: Be aware of API rate limits based on your account tier

Key Components Explained

  • ChatClient: The main client for interacting with OpenAI’s API
  • ChatMessage: Base class for different message types
  • SystemChatMessage: Sets the AI’s behavior and personality
  • UserChatMessage: Contains user input
  • AssistantChatMessage: Stores AI responses
  • CompleteChatAsync: Sends messages to OpenAI and retrieves responses

Best Practices

  1. API Key Security: Never hardcode API keys. Use environment variables or secure configuration
  2. Error Handling: Implement try-catch blocks for API calls
  3. Context Management: Limit message history to prevent token limit issues
  4. Response Validation: Always validate API responses before using them

Next Steps

  • Explore streaming responses for real-time output
  • Implement conversation persistence with a database
  • Add function calling for more complex interactions
  • Build a web API wrapper for your chatbot

Additional Resources

This implementation provides a simple console-based chatbot that maintains conversation context by storing the entire message history and sending it with each request to the OpenAI API. With just these few lines of code, you’ve created a functional AI assistant in your .NET application.

Ready to Build Something Amazing?

Let's discuss how Aviron Labs can help bring your ideas to life with custom software solutions.

Get in Touch