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
- API Key: Obtain your API key from the OpenAI Developer Platform
- Model Selection: The example uses “gpt-4o” but you can use other models like “gpt-3.5-turbo”
- Billing: Ensure you have billing credits available in your OpenAI account
- 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
- API Key Security: Never hardcode API keys. Use environment variables or secure configuration
- Error Handling: Implement try-catch blocks for API calls
- Context Management: Limit message history to prevent token limit issues
- 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
- Source Code: GitHub Repository - dotnet-ai-examples/OpenAITest
- OpenAI Pricing: OpenAI API Pricing Page
- OpenAI Documentation: Official API documentation for additional features and options
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