In this tutorial, weβll walk through how to build a real-time chatbot using Next.js and OpenAI's API. Combining WebSockets for real-time communication and OpenAI for generating responses, you can create an intelligent and responsive chatbot. Letβs get started! π
π οΈ Step 1: Setting Up the Next.js Project
Start by setting up a Next.js app if you donβt already have one:
npx create-next-app@latest nextjs-chatbot
cd nextjs-chatbot
npm install
Next, install the packages we'll need: Socket.io for real-time communication and OpenAI's API client.
npm install socket.io socket.io-client openai
Now weβre ready to begin building the chatbot!
π Step 2: Setting Up the OpenAI API
To use OpenAI, you need an API key. Go to OpenAI's website and sign up for an API key.
In your Next.js project, create an .env.local
file to store your OpenAI API key:
NEXT_PUBLIC_OPENAI_API_KEY=your-openai-api-key
π Step 3: Create API Route for OpenAI Integration
Next, we need to set up a Next.js API route that interacts with OpenAI and generates responses for the chatbot.
Create a file at pages/api/chatbot.js
:
import { Configuration, OpenAIApi } from 'openai';
const configuration = new Configuration({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
if (req.method === 'POST') {
const { message } = req.body;
// Send user message to OpenAI for a response
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message }],
});
const reply = response.data.choices[0].message.content;
res.status(200).json({ reply });
} else {
res.status(405).send('Method not allowed');
}
}
This API route listens for POST requests with a message
from the user, sends it to OpenAI, and returns the AI-generated response.
π‘ Step 4: Setting Up WebSocket Server
Next, weβll set up Socket.io to allow real-time communication between the client and server.
Create a WebSocket server in pages/api/socket.js
:
import { Server } from "socket.io";
export default function handler(req, res) {
if (!res.socket.server.io) {
const io = new Server(res.socket.server);
res.socket.server.io = io;
io.on("connection", (socket) => {
console.log("User connected:", socket.id);
socket.on("message", async (message) => {
// Send message to OpenAI API
const response = await fetch("http://localhost:3000/api/chatbot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message }),
});
const { reply } = await response.json();
socket.emit("response", reply);
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
}
res.end();
}
This WebSocket server listens for incoming message
events, sends them to OpenAI via the /api/chatbot
route, and broadcasts the response back to the client.
π» Step 5: Client-Side WebSocket and Chat Interface
Now, letβs build the chat UI and handle communication with the WebSocket server. Create a components/ChatBot.js
file for the chat interface:
import { useEffect, useState } from 'react';
import io from 'socket.io-client';
let socket;
export default function ChatBot() {
const [message, setMessage] = useState("");
const [messages, setMessages] = useState([]);
useEffect(() => {
socket = io();
socket.on("response", (reply) => {
setMessages((prev) => [...prev, { sender: "bot", text: reply }]);
});
return () => {
socket.disconnect();
};
}, []);
const sendMessage = () => {
setMessages((prev) => [...prev, { sender: "user", text: message }]);
socket.emit("message", message);
setMessage("");
};
return (
<div>
<h1>Real-Time ChatBot π€</h1>
<div className="chatbox">
{messages.map((msg, index) => (
<div key={index} className={msg.sender === "user" ? "user-msg" : "bot-msg"}>
{msg.sender === "user" ? "You: " : "Bot: "} {msg.text}
</div>
))}
</div>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Ask me something..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}
This component does the following:
- Connects to the WebSocket server when mounted.
- Sends messages typed by the user.
- Displays the conversation, showing responses from OpenAI.
π Step 6: Display the ChatBot in the App
Finally, update your main page to render the chatbot. In pages/index.js
:
import ChatBot from '../components/ChatBot';
export default function Home() {
return (
<div>
<ChatBot />
</div>
);
}
This will display the chatbot interface when you visit the main page of your app.
π§ͺ Step 7: Testing the Chatbot
You can now test the chatbot by running your Next.js app:
npm run dev
Visit http://localhost:3000
, and youβll be able to chat with your real-time AI chatbot! Open multiple tabs to see how the real-time communication works as you send messages.
π Conclusion
Congratulations! π You've built a real-time chatbot using Next.js, WebSockets, and OpenAI. This setup can be extended to create more complex chatbots with features like user authentication, chat history, and more.
WebSockets ensure seamless real-time communication, while OpenAI powers the intelligent responses of your bot. Feel free to experiment further and enhance the chatbot with more advanced AI models!
π Additional Resources:
What kind of chatbot are you building? Let me know in the comments! π¬
Top comments (3)
Useful. Thanks for sharing!
Could we collaborate on it?
Yeah, Sure.