Build a real-time intelligent chat system using .NET, OpenAI, and SignalR
🧠 Introduction
Artificial Intelligence (AI) is no longer a futuristic concept — it’s becoming a standard component in modern applications. One of the most practical and exciting uses of AI is in chatbots that can interact naturally with users.
By integrating Generative AI APIs (like OpenAI GPT) and SignalR in C#, you can create a real-time intelligent chatbot capable of answering questions, generating content, and simulating conversation — all powered by AI.
In this article, we’ll walk through building an AI chatbot using .NET 8, SignalR, and the OpenAI API.
⚙️ Prerequisites
Before getting started, ensure you have:
✅ .NET 8 SDK
✅ Visual Studio 2022 or VS Code
✅ OpenAI API Key
✅ Basic understanding of WebSocket communication
🔧 Step 1. Create a New .NET 8 Web Project
Run the following command:
dotnet new web -n AIAssistantChat
cd AIAssistantChat
This will create a lightweight web app suitable for SignalR and API integration.
🧩 Step 2. Add Required Packages
Install the following NuGet packages:
dotnet add package Microsoft.AspNetCore.SignalR
dotnet add package OpenAI_API
dotnet add package Microsoft.AspNetCore.Cors
💬 Step 3. Setup the ChatHub (SignalR Hub)
Create a new folder Hubs and add a class ChatHub.cs:
using Microsoft.AspNetCore.SignalR;
using OpenAI_API;
using System.Threading.Tasks;
namespace AIAssistantChat.Hubs
{
public class ChatHub : Hub
{
private readonly OpenAIAPI _api;
public ChatHub()
{
_api = new OpenAIAPI("sk-your-openai-key"); // Replace with your API key
}
public async Task SendMessage(string user, string message)
{
// Broadcast user's message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
// Call the AI API for response
var result = await _api.Completions.GetCompletion(message);
// Send AI response
await Clients.All.SendAsync("ReceiveMessage", "AI Bot", result);
}
}
}
Explanation:
SendMessage()→ triggered when a user sends a messageAI response is generated via the OpenAI API
Both user and AI messages are broadcast to all connected clients in real time
🌐 Step 4. Configure SignalR in Program.cs
using AIAssistantChat.Hubs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
var app = builder.Build();
app.UseCors("AllowAll");
app.MapHub<ChatHub>("/chatHub");
app.Run();
This sets up the SignalR hub endpoint and enables CORS for web client connections.
💻 Step 5. Create a Frontend Chat UI (HTML + JavaScript)
Create a file named index.html in the project root and add:

Join the conversation! Your thoughts help the community grow.