How to Build a Realtime AI-Powered Chatbot with Node.js and OpenAI GPT-4 in ReactJs

How to Build a Realtime AI-Powered Chatbot with Node.js and OpenAI GPT-4 in ReactJs
Backend: Node.js Server
Step 1: Set Up the Project
Create a new project directory and initialize it:
mkdir ai-chatbot
cd ai-chatbot
npm init -yStep 2: Install Dependencies
Install the required dependencies:
npm install express socket.io axios dotenvStep 3: Create server.js
Create a file named server.js in your project directory and add the following code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const axios = require('axios');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('message', async (message) => {
const reply = await getAIResponse(message);
socket.emit('message', reply);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
const getAIResponse = async (message) => {
const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
prompt: message,
max_tokens: 150
}, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
}
});
return response.data.choices[0].text.trim();
};
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});Step 4: Set Up Environment Variables
Create a .env file in your project directory to store your OpenAI API key:
OPENAI_API_KEY=your_openai_api_keyFrontend: React Application
Step 1: Set Up Your React Project
First, create a new React project using Create React App:
npx create-react-app ai-chatbot
cd ai-chatbotStep 2: Install Socket.io Client
Install the Socket.io client to enable real-time communication between the frontend and the backend:
npm install socket.io-clientStep 3: Create the Chat Component
Create a new file named Chat.js in the src directory and add the following code:
import React, { useState, useEffect, useRef } from 'react';
import io from 'socket.io-client';
import './Chat.css';
const socket = io.connect('http://localhost:3000');
const Chat = () => {
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState('');
const messagesEndRef = useRef(null);
useEffect(() => {
socket.on('message', (message) => {
setMessages((prevMessages) => [...prevMessages, message]);
});
return () => {
socket.off('message');
};
}, []);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const handleSendMessage = (e) => {
e.preventDefault();
if (message) {
const userMessage = `You: ${message}`;
setMessages((prevMessages) => [...prevMessages, userMessage]);
socket.emit('message', message);
setMessage('');
}
};
return (
<div id="chat-container">
<div id="messages">
{messages.map((msg, index) => (
<div key={index}>{msg}</div>
))}
<div ref={messagesEndRef}></div>
</div>
<form id="message-form" onSubmit={handleSendMessage}>
<input
id="message-input"
autoComplete="off"
placeholder="Type a message..."
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chat;Step 4: Style the Chat Component
Create a Chat.css file in the src directory and add the following styles:
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
#chat-container {
width: 400px;
background: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
border-radius: 5px;
}
#messages {
height: 300px;
overflow-y: scroll;
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 10px;
}
#message-form {
display: flex;
}
#message-input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 3px;
margin-right: 10px;
}
button {
padding: 10px 20px;
border: none;
background: #28a745;
color: #fff;
border-radius: 3px;
cursor: pointer;
}
button:hover {
background: #218838;
}Step 5: Update the App Component
Modify the App.js file to include the Chat component:
import React from 'react';
import Chat from './Chat';
import './App.css';
function App() {
return (
<div className="App">
<Chat />
</div>
);
}
export default App;Step 6: Run Both the Backend and Frontend
Make sure your backend server is running:
node server.jsStart your React application:
npm startConclusion
You have now built a real-time AI-powered chatbot with a Node.js backend and a React frontend. This chatbot leverages OpenAI’s GPT-4 to provide human-like responses, making it a powerful tool for enhancing user interaction in web applications.