AI  

Creating an AI Chatbot in C# with Generative API and SignalR

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:

FeatureDescription
Context MemoryMaintain conversation context for smarter replies
Streaming ResponsesUse SignalR to send partial AI responses in real time
Multi-User SupportCreate private chat sessions per user connection
Database LoggingStore conversations in SQL Server for analytics
Custom PersonalitySet 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.