Introduction
Chatbots have become an integral part of our digital experience, helping businesses automate customer support, streamline services, and engage users in more personalized ways. With advancements in AI, especially with models like OpenAI's GPT, building a powerful conversational AI is easier than ever.
In this blog, we'll walk you through building a conversational AI chatbot using React for the frontend and Python for the backend. By the end of this guide, you'll have a fully functional chatbot that uses OpenAI's language model to interact with users. Let's dive in!
What You Need
Before we begin, here's what you need to get started:
- Basic knowledge of React and Python.
- If you are a beginner in react, i would recommend you go through this react tutorials - https://www.techartifacts.com/category/react
- Node.js and npm installed on your machine.
- Follow this tutorial to learn how to download and install Node.js and NPM - https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
- Python (preferably Python 3.7+).
- Follow this tutorial to learn how to download and install python - https://www.python.org/downloads/release/python-3131/
- OpenAI API key (You can get it by signing up at OpenAI).
- Follow this tutorial to learn how to generate an openAI API Key - https://openai.com/index/openai-api/
Assuming everything is now setup, let's dive in.
Step 1: Setting Up the Backend (Python)
We'll start by setting up the backend using Python, where we will handle the communication with OpenAI's API.
1. Create a Python project:
- Create a folder for your project and navigate to it in your terminal.
- Set up a virtual environment:
python -m venv venv
- Activate the virtual environment:
- If you are using Windows, then run the below command -
.\venv\Scripts\activate
- If you are using Linux or MacOS, then run the below command -
source venv/bin/activate
- If you are using Windows, then run the below command -
2. Install required libraries:
Install the libraries needed to interact with the OpenAI API and run a simple server:
pip install openai flask
3. Set up the OpenAI API:
- In your Python project folder, create a file called app.py.
- Import the necessary libraries and set up the OpenAI client:
import openai from flask import Flask, request, jsonify openai.api_key = 'YOUR_OPENAI_API_KEY' # Replace with your OpenAI API key app = Flask(__name__) @app.route('/chat', methods=['POST']) def chat(): user_input = request.json.get('message') response = openai.Completion.create( model="gpt-3.5-turbo", # You can also use the latest available model prompt=user_input, max_tokens=150 ) return jsonify({'response': response.choices[0].text.strip()}) if __name__ == '__main__': app.run(debug=True)
- Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key.
4. Run the server:
- In the terminal, run -
python app.py
- This will start a Flask server at http://localhost:5000, which listens for requests from the frontend.
Step 2: Building the Frontend (React)
Next, let's build the React app that will interact with the backend.
1. Create a new React app:
In a new folder, run:
npx create-react-app chatbot
cd chatbot
2. Install Axios:
We'll use Axios to make HTTP requests from React to the backend.
npm install axios
3. Create the Chatbot Component:
Open the src/App.js file and update it with the following code:
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [message, setMessage] = useState('');
const [chatHistory, setChatHistory] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
const newMessage = { user: message, bot: '' };
setChatHistory([...chatHistory, newMessage]);
try {
const response = await axios.post('http://localhost:5000/chat', { message });
const botMessage = response.data.response;
newMessage.bot = botMessage;
setChatHistory([...chatHistory, newMessage]);
} catch (error) {
console.error("Error communicating with the backend", error);
}
setMessage('');
};
return (
<div className="App">
<h1>AI Chatbot</h1>
<div className="chat-box">
{chatHistory.map((chat, index) => (
<div key={index}>
<p><strong>You:</strong> {chat.user}</p>
<p><strong>Bot:</strong> {chat.bot}</p>
</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Type your message..."
/>
<button type="submit">Send</button>
</form>
</div>
);
}
export default App;
This code sets up a basic chat interface. The user types a message, and once the form is submitted, Axios sends the message to the backend (Flask server). The backend responds with a reply from OpenAI’s model, which is then displayed in the chat window.
4. Add some styling (optional):
To make the chat look nicer, you can add simple CSS to src/App.css:
.App {
font-family: Arial, sans-serif;
text-align: center;
}
.chat-box {
margin: 20px;
padding: 10px;
border: 1px solid #ccc;
height: 300px;
overflow-y: scroll;
}
input {
padding: 10px;
width: 300px;
margin-right: 10px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
5. Run the React app:
In your terminal, run:
npm start
This will open the React app in your browser at http://localhost:3000.
Step 3: Testing the Chatbot
Now that both the frontend and backend are set up, it’s time to test the chatbot.
- Make sure your Flask server (python app.py) is running.
- Open the React app in your browser.
- Type a message in the input box and hit "Send".
- You should see a response from the bot, generated by OpenAI's model.
Conclusion
Congratulations! You've built a simple AI-powered chatbot using React and Python. This chatbot can easily be extended with more advanced features, such as handling user authentication, saving conversation history, or even deploying it to the cloud.
Building a chatbot like this opens up a lot of possibilities for automation, personalized customer support, and more. With the power of OpenAI’s models and the flexibility of React and Python, you can create complex, interactive applications that engage users in new and exciting ways.
Happy coding, and feel free to share your projects with the world!
If you found this guide helpful, don't forget to share it with others! And stay tuned for more tutorials on building cool projects with React and Python.