Building an AI Chatbot with React, Next.js, Tailwind CSS and OpenAI

Learn how to create a conversational AI chatbot using OpenAI’s powerful language models in a React app built with Next.js and Tailwind CSS

Rohit Kumar Thakur
4 min readNov 21, 2023
AI Chatbot: Next.js, Tailwind CSS and OpenAI API

Hello everyone, My name is Rohit. In this article, I will guide you through how to build a Chatbot using Next.js, Tailwind CSS and OpenAI API. If you face any issues then feel free to comment or DM me on my social media handles. X && Instagram

Source code and more: https://www.patreon.com/bugninza

Before diving into the code, there are a few things you need to set up. First and foremost, you’ll need to initialize a Next.js application. Next, decide whether you want to use page router configuration or app router configuration, depending on your preference. Bear in mind that routing won’t be covered in this project, as our focus is on building a chatbot app. If you’re a beginner, I recommend following the provided video tutorial.

Secondly, set up your OpenAI account and generate an API key. Ensure that your OpenAI API usage doesn’t expire (it has a $5 free tier with a time limit of 5–6 months). If you use the API with an expired timeframe, you’ll encounter an error with a status code of 429. To resolve this issue, you can either set up a billing account and pay OpenAI or create a new account with a different email and phone number. Remember, the phone number must be different to avoid the same error. The second method is particularly useful for testing your application.

Enough talk!!!! Let’s write some code.

First, make a .env.local file inside the root directory to store the API key

NEXT_PUBLIC_OPENAI_API_KEY=###################

Replace the hashtag with your openAI API key

Now, make a separate file ( if you prefer ) or continue to the main page.js to write the code for the chatbot.

Importing Dependencies:

“use client”
import React, { useState } from ‘react’;
import OpenAI from ‘openai’;

The “use client” directive tells Next.js to run this component on the client-side only. This is important for API calls to ensure they happen client-side.

Import React hooks like useState for managing state as well as the OpenAI library for making API requests to the OpenAI platform.

Initializing OpenAI

const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
dangerouslyAllowBrowser: true,
});

It initializes an OpenAI client with the API key and allows requests from the browser.

React Component

// State variables
const [userInput, setUserInput] = useState('');
const [chatHistory, setChatHistory] = useState([]);
const [isLoading, setIsLoading] = useState(false);

Inside the main App component, we gonna use these state variables. In this component, three state variables are declared using the useState hook:

  • userInput: Stores the user’s input.
  • chatHistory: Maintains the history of the conversation between the user and the assistant.
  • isLoading: Indicates whether the chatbot is currently processing a request, useful for displaying a loading indicator.

User Input Handling

const handleUserInput = async () => {
// Start the loading state
setIsLoading(true);

// Add the user's message to the chat history
setChatHistory((prevChat) => [
...prevChat,
{ role: 'user', content: userInput },
]);

// Make a request to OpenAI for the chat completion
const chatCompletion = await openai.chat.completions.create({
messages: [...chatHistory, { role: 'assistant', content: userInput }],
model: 'gpt-3.5-turbo',
});

// Add the assistant's response to the chat history
setChatHistory((prevChat) => [
...prevChat,
{ role: 'assistant', content: chatCompletion.choices[0].message.content },
]);

// Clear the user input field and end the loading state
setUserInput('');
setIsLoading(false);
};

Explanation of the handleUserInput function:

  • It starts by setting isLoading to true to indicate the start of a request.
  • The user’s message is added to the chatHistory array.
  • A request is made to the OpenAI API for chat completion. The messages include both user and assistant messages from the chat history.
  • The assistant’s response is added to the chatHistory.
  • The user input is cleared, and the loading state is set to false.

Return JSX

return (
// JSX code for the chatbot UI
);

At last, return the Code for the Chatbot UI as per your requirements or preferences.

Or

You can get help from here:

That’s it. If you gained some information today, please follow me and clap so that Medium starts recommending this article to more developers. Thanks for reading!

Attention all developers seeking to make social connections and establish themselves while earning passive income — look no further! I highly recommend ‘From Code to Connections’, a book that will guide you through the process. Don’t miss out, grab your copy now on Amazon worldwide or Amazon India! You can also go for Gumroad

--

--

Rohit Kumar Thakur
Rohit Kumar Thakur

Written by Rohit Kumar Thakur

I write about AI, Tech, Startup and Code

No responses yet