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 message
AI 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:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AI Chatbot - .NET + SignalR + OpenAI</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
</head>
<body style="font-family:Arial; padding:20px;">
<h2>π€ AI Chatbot</h2>
<div id="chat" style="border:1px solid #ccc; height:300px; overflow:auto; padding:10px;"></div>
<input type="text" id="messageInput" placeholder="Type your message..." style="width:80%;" />
<button onclick="sendMessage()">Send</button>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", (user, message) => {
const msg = document.createElement("div");
msg.innerHTML = `<b>${user}:</b> ${message}`;
document.getElementById("chat").appendChild(msg);
});
connection.start().catch(err => console.error(err.toString()));
function sendMessage() {
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", "User", message);
document.getElementById("messageInput").value = "";
}
</script>
</body>
</html>
Now, when you run the project and open this HTML page, youβll have a real-time AI chat interface.
π§ Example Interaction
User:
βWrite a C# function to calculate factorial of a number.β
AI Bot:
public int Factorial(int n)
{
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
User:
βNow explain it in simple words.β
AI Bot:
The function calls itself recursively until n
is 1, multiplying each value along the way β this is called recursion.
π Step 6. Run the Application
In terminal:
dotnet run
Then open the browser and navigate to:
π https://localhost:5001/index.html
You now have a live, real-time AI chatbot running locally.
π Security Tips
β
Use user secrets for API keys:
dotnet user-secrets set "OpenAIKey" "your-key"
β
Add throttling for rate limits
β
Validate user inputs to prevent misuse
β
Log AI responses for auditing
β‘ Advanced Enhancements
Here are ways to extend your chatbot further:
Feature | Description |
---|
Context Memory | Maintain conversation context for smarter replies |
Streaming Responses | Use SignalR to send partial AI responses in real time |
Multi-User Support | Create private chat sessions per user connection |
Database Logging | Store conversations in SQL Server for analytics |
Custom Personality | Set AI tone (friendly, formal, assistant-style) |
π External References
π OpenAI API Documentation
π Microsoft SignalR Documentation
π§± .NET 8 Minimal API Guide
π‘ CORS in ASP.NET Core
βοΈ Deploy SignalR App to Azure
π Conclusion
By combining Generative AI APIs and SignalR, you can build an intelligent, real-time chatbot that feels natural and responsive.
This architecture can be extended for support bots, learning assistants, or even AI customer service dashboards β all using familiar C# and .NET 8 technologies.
Generative AI isnβt replacing developers β itβs empowering them to build smarter, more interactive systems faster than ever.