Creating a Simple ChatGPT Clone with React and Flask


Build Your Own ChatGPT Clone: A Step-by-Step Guide with React and Flask

This entry is part 2 of 2 in the series ChatGPT clone

In this blog post, we’ll guide you through building a simple React application that mimics ChatGPT, using a Flask API as the backend. The app will feature a clean, responsive UI styled with Bootstrap, making it visually appealing and user-friendly.

Prerequisites

Before we dive in, ensure you have the following:

  1. Node.js and npm installed. You can download them here.
  2. Python 3.7+ with Flask and the OpenAI library installed.
  3. A running Flask API like the one we built in the previous tutorial, which integrates ChatGPT via OpenAI’s API.
  4. Basic knowledge of React and Flask.

Step 1: Setting Up the React Project

  1. Create a React App: Open your terminal and run:
   npx create-react-app chatgpt-clone
   cd chatgpt-clone
  1. Install Bootstrap: Install Bootstrap for styling:
   npm install bootstrap

Import Bootstrap in src/index.js:

   import 'bootstrap/dist/css/bootstrap.min.css';
  1. Install Axios: Axios will be used to make HTTP requests to the Flask backend:
   npm install axios

Step 2: Building the React App

2.1 Create a Chat Component

Inside the src folder, create a new file called Chat.js and add the following code:

import React, { useState } from 'react';
import axios from 'axios';

const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  const handleSend = async () => {
    if (!input.trim()) return;

    // Add the user message to the chat
    const userMessage = { role: 'user', content: input };
    setMessages([...messages, userMessage]);
    setInput('');

    try {
      // Send the message to the Flask API
      const response = await axios.post('http://127.0.0.1:5000/chat', {
        message: input
      });

      const botMessage = {
        role: 'assistant',
        content: response.data.message
      };

      // Add the bot's response to the chat
      setMessages([...messages, userMessage, botMessage]);
    } catch (error) {
      console.error('Error fetching response:', error);
      alert('Failed to get response from the server.');
    }
  };

  return (
    <div className="container mt-5">
      <h2 className="text-center mb-4">ChatGPT Clone</h2>
      <div className="card">
        <div className="card-body" style={{ height: '400px', overflowY: 'scroll' }}>
          {messages.map((msg, index) => (
            <div key={index} className={`mb-3 ${msg.role === 'user' ? 'text-end' : 'text-start'}`}>
              <span className={`badge ${msg.role === 'user' ? 'bg-primary' : 'bg-secondary'}`}>
                {msg.role === 'user' ? 'You' : 'ChatGPT'}:
              </span>
              <p className="d-inline-block ms-2">{msg.content}</p>
            </div>
          ))}
        </div>
        <div className="card-footer">
          <div className="input-group">
            <input
              type="text"
              className="form-control"
              placeholder="Type a message..."
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSend()}
            />
            <button className="btn btn-primary" onClick={handleSend}>
              Send
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Chat

2.2 Update App.js

Replace the content of src/App.js with:

import React from 'react';
import Chat from './Chat';

function App() {
  return (
    <div className="App">
      <Chat />
    </div>
  );
}

export default App;

Step 3: Running the React App

Start your React app with:

npm start

Navigate to http://localhost:3000 in your browser, and you’ll see your ChatGPT clone in action.

Step 4: Connecting Flask Backend

Ensure your Flask backend is running by navigating to the directory where your Flask app resides and running:

python app.py

The React app will send requests to the Flask API at http://127.0.0.1:5000/chat, which processes user inputs using OpenAI’s ChatGPT and returns responses.

Step 5: Styling with Bootstrap

To enhance the visual appeal of the app:

  1. Use Bootstrap’s grid system to make the chat interface responsive.
  2. Add additional styles for the chat bubbles to differentiate user and bot messages.

Example CSS for chat bubbles (optional):

.card-body .text-start {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 10px;
  margin-right: 50%;
}

.card-body .text-end {
  background-color: #007bff;
  color: white;
  padding: 10px;
  border-radius: 10px;
  margin-left: 50%;
}

Include this in src/index.css or within a <style> tag in Chat.js.

Conclusion

Congratulations! You’ve built a simple ChatGPT clone using React for the frontend and Flask for the backend. This project is a great foundation for building more advanced chatbot applications with additional features like authentication, message persistence, and improved UI design. Happy coding!

Series Navigation<< Building a Flask Application to Send Requests to ChatGPT

  • Share on X
  • Share on Pinterest