๐ค **Building a Real-Time Chatbot in Next.js with OpenAI** ๐ง
Hamza Khan
Posted on September 25, 2024
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! ๐ฌ
Posted on September 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.