Building a chatbot with GPT-3.5 and Next.js
Create a GPT-3 Chatbot Web App!
Introduction
Chatbots powered by artificial intelligence are becoming increasingly popular, providing businesses and websites with automated conversational agents that can interact with customers.
In this tutorial, we’ll use React framework Next.js to build the frontend and integrate the powerful natural language AI of OpenAI’s GPT-3 to create our own chatbot web app.
Even with no prior experience in AI or chatbots, by following this tutorial step-by-step you’ll gain the ability to build interactive AIs from scratch.
Overview
Here’s a quick rundown of what we’ll cover:
- Set up a Next.js app — Get our React environment & project started
- Sign up for an OpenAI API key — Gain access to GPT-3
- Create chatbot UI — Build a text chat interface using React
- Connect OpenAI API — Link chat app frontend to backend AI
- Deploy finished web app — Get our chatbot online!
Excited? The steps below will take you through building your own AI chatbot web app that can hold natural conversations on any topic you choose.
Step 1 — Set up a Next.js App
First, we’ll set up a Next.js project as the framework for our chatbot’s frontend. Next.js is perfect for this use case as it handles server-side rendering and static site generation right out of the box.
To start, make sure Node.js is installed on your development machine then run:
npm create next-appThis will scaffold a fresh Next.js project for you. Navigate into the new directory then run:
npm run dev
You should now see your hello world app running at http://localhost:3000!
With our React environment ready, let’s shift gears and get access to OpenAI’s GPT-3 model.
Step 2 — Sign Up for an OpenAI API Key
In order for our frontend to communicate with OpenAI’s backend servers, we’ll need an API key:
- Go to openai.com and sign up for a free account
- Once registered, click your profile picture > View API keys
- Copy the secret key — this identifies you to OpenAI
Treat your OpenAI secret key like a password and keep it secure. Now we’re ready to start integrating AI!
Step 3 — Create the Chatbot UI in React
With our Next.js foundation setup and API access granted, we can start constructing our chatbot’s user interface using React components.
Inside pages/index.js, delete the default contents and add:
// UI & layout
import { useState } from 'react'
export default function ChatPage() {
const [chatLog, setChatLog] = useState([])
return (
<div>
{/* Chat interface */}
</div>
)
}This initializes a chatLog hook to track conversational history and lays the groundwork for our chat UI.
Next, build out the graphical interface using standard React and flexbox:
return (
<div className="app">
<div className="sidebar">
{/* Chat avatar */}
</div>
<div className="chatbox">
<div className="chat-messages">
{/* Message history */}
</div>
<div className="chat-input">
{/* Text input */}
</div>
</div>
</div>
)This splits our app into a sidebar and chatbox - prime real estate for a chat avatar and message history.
Inside those containers, add UI elements like:
// Sidebar
<img
className="avatar"
src="bot.svg"
/>
// Messages
<div className="messages">
{
chatLog.map((msg, index) => (
<ChatMessage
key={index}
message={msg}
/>
))
}
</div>
// Input
<textarea
rows={1}
placeholder="Type your message..."
/>
<button>
<img src="send.svg" />
</button>Using standard React techniques like mapping over state to render a chat interface. For your custom chatbot avatar, drop in any .svg or image.
Lastly, style your chatbot UI by adding a styles object:
const styles = {
app: css`
display: flex;
height: 100vh;
`,
sidebar: css`
width: 220px;
background: #ddd;
`
}And so on for colors, sizing, flex behavior — tailoring it to your needs.
Our frontend design is nearly complete! We have a graphical chat interface rendering in React — the final piece is piping in the AI.
Step 4 — Connect the OpenAI API
Now for the fun part — integrating OpenAI’s natural language model into our chatbot.
First, install the openai npm package at the root of your Next.js app:
npm install openai
Then in your index page, import the openai library:
import { Configuration, OpenAIApi } from 'openai'Instantiate a configuration object with your secret key:
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);This safely handles authentication. Now we can query GPT-3!
Inside your text input, add a submit handler:
<textarea
placeholder="Chat with me..."
onKeyUp={handleSubmit}
/>Where handleSubmit passes the text to OpenAI:
async function handleSubmit(e) {
// Prevent default form behavior
e.preventDefault()
// Get user text input
const userMessage = e.target.value
// Chatbot response
const botResponse = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(userMessage),
temperature: 0.5,
})
// Display response
setChatLog(prevState => ([
...prevState,
{
user: userMessage,
bot: botResponse.data.choices[0].text
}
]))
}Breaking this down:
- Prevent the form refresh with
preventDefault - Grab user’s chat input text
- Send it to GPT-3 model
text-davinci-003 - Pass text as prompt to complete
- Store response + history in state
Lastly, we need to construct the actual prompt that primes GPT-3's next reply:
function generatePrompt(msg) {
let prompt = chatLog.map(
chat => `${chat.user}: ${chat.userText}\nAI: ${chat.botText}`
).join('\n') + `\nHuman: ${msg}\nAI:`
return prompt;
}This formats the user message history into an AI-ready prompt that elicits the next chained response.
And we’re done! With just ~100 lines of code you now have your own functional AI chatbot web app using Next.js and OpenAI 💪
Step 5 — Deploy the Web App
To share your conversational AI with the world, deploy the web app live with Vercel:
npm install -g vercel vercel
Follow the prompts to connect your GitHub/GitLab repo and push to production!
Now anyone can access your AI assistant online. No server configuration needed thanks to serverless platforms.
Key Takeaways
And that’s it! We:
- Built an AI chatbot web app in React
- Utilized Next.js for SSR with Vercel
- Integrated OpenAI’s GPT-3 for natural language
- Created a prompt-based conversational agent
You now have the blueprint to assemble intelligent chatbots customizable for business use cases like customer service, ecommerce stores, virtual assistants, and more.
The capabilities of AI chatbots are expanding rapidly. I hope you feel empowered to build your own after following this tutorial!
Let me know what chat experiences you create in the comments below!
