🔹 Introduction: Why Build a ChatBot Using OpenAPI ChatGPT API with Python?
Python is one of the most popular languages for AI applications because of its simplicity, vast ecosystem, and OpenAI API support. FastAPI is a high-performance, easy-to-use Python framework for building APIs, making it perfect for integrating OpenAI’s ChatGPT API.
A chatbot built with FastAPI and OpenAI’s API can:
✔️ Process real-time conversations with AI-generated responses.
✔️ Enhance customer support by automating responses.
✔️ Be used in e-commerce, healthcare, education, and more.
📌 What You Will Learn
✅ How to obtain and use OpenAI’s API key.
✅ How to set up FastAPI for chatbot requests.
✅ How to integrate OpenAI’s ChatGPT API in Python.
✅ How to connect a React JS frontend to the chatbot backend.
By the end of this guide, you will have a fully functional AI chatbot built with FastAPI, Python, React JS, and OpenAI’s ChatGPT API! 🚀
🔹 Prerequisites
Before starting, make sure you have the following installed:
✔️ Python 3.8+ (Download from Python.org)
✔️ FastAPI & Uvicorn (for backend development)
✔️ Node.js (v16 or higher) (Download from Node.js Official)
✔️ npm or yarn (for frontend development)
✔️ An OpenAI API Key – Get it from OpenAI API
🚀 Backend: Build a Chatbot API Using FastAPI and OpenAI
We will create a FastAPI-based REST API that receives user input, sends it to OpenAI’s ChatGPT API, and returns the AI-generated response.
🔹 Step 1: Install Required Dependencies
First, install the necessary Python libraries:
pip install fastapi uvicorn openai python-dotenv
🔹 fastapi
- The web framework for building APIs.
🔹 uvicorn
- The ASGI server to run FastAPI applications.
🔹 openai
- OpenAI’s Python SDK to communicate with ChatGPT API.
🔹 python-dotenv
- Loads API keys from environment variables.
🔹 Step 2: Get Your OpenAI API Key
- Sign up at OpenAI Platform.
- Generate an API key under API Keys.
- Store it securely in a
.env
file (we’ll use this file to load secrets).
Create a .env
file in the project directory:
echo "OPENAI_API_KEY=your-api-key-here" > .env
🔹 Step 3: Create a FastAPI Server
📌 Create a file main.py
and add the following code:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import openai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize FastAPI app
app = FastAPI()
# Get OpenAI API Key
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise ValueError("OpenAI API key not found. Please set it in the .env file.")
openai.api_key = OPENAI_API_KEY
# Request model
class ChatRequest(BaseModel):
prompt: str
# API route to send a message to OpenAI ChatGPT
@app.post("/api/chat")
async def chat(request: ChatRequest):
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini", # You can change to gpt-3.5-turbo or another model
messages=[{"role": "user", "content": request.prompt}]
)
return {"response": response["choices"][0]["message"]["content"]}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
🔹 Step 4: Run the FastAPI Server
Start the FastAPI application using Uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
📌 Your FastAPI server is now running at:
👉 http://localhost:8000/docs (Interactive API documentation)
👉 http://localhost:8000/api/chat (Chatbot endpoint)
🚀 Frontend: Build a React Chatbot UI
Now that our backend is set up, let's build the React frontend to send user input and display AI responses.
🔹 Step 5: Create a React App Using Vite.js
Run the following commands in your terminal:
# Create a new React project using Vite
npm create vite@latest chatgpt-react --template react
# Move into the project directory
cd chatgpt-react
# Install dependencies
npm install bootstrap axios
🔹 Step 6: Create the Chatbot Component
📌 Inside src/components/
, create a new file ChatBot.js
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
const ChatBot = () => {
const [input, setInput] = useState("");
const [messages, setMessages] = useState([]);
const chatEndRef = useRef(null);
const sendMessage = async () => {
if (!input.trim()) return;
const userMessage = { text: input, sender: "user" };
setMessages([...messages, userMessage]);
setInput("");
try {
const res = await axios.post("http://localhost:8000/api/chat", { prompt: input });
const botMessage = { text: res.data.response, sender: "bot" };
setMessages([...messages, userMessage, botMessage]);
} catch (error) {
console.error("Error fetching response", error);
setMessages([...messages, userMessage, { text: "Error retrieving response", sender: "bot" }]);
}
};
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
return (
<div className="container mt-5">
<div className="card shadow-lg">
<div className="card-header bg-primary text-white text-center">
<h4>ChatGPT Chatbot</h4>
</div>
<div className="card-body chat-box" style={{ height: "400px", overflowY: "auto" }}>
{messages.map((msg, index) => (
<div key={index} className={`d-flex ${msg.sender === "user" ? "justify-content-end" : "justify-content-start"} mb-2`}>
<div className={`p-3 rounded shadow ${msg.sender === "user" ? "bg-primary text-white" : "bg-light text-dark"}`} style={{ maxWidth: "75%" }}>
{msg.text}
</div>
</div>
))}
<div ref={chatEndRef} />
</div>
<div className="card-footer">
<input className="form-control" value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && sendMessage()} />
</div>
</div>
</div>
);
};
export default ChatBot;
🎉 Your AI Chatbot is now fully functional! 🚀
🚀 Step 6: Create the Chatbot Component (ChatBot.js
)
Now that our FastAPI backend is up and running, we will create a React component for the chatbot interface. This component will:
✅ Allow users to type messages and send them to the FastAPI backend.
✅ Display the user’s messages and responses from OpenAI’s ChatGPT API.
✅ Use Bootstrap for a simple and clean UI.
✅ Automatically scroll to the latest message in the chat window.
📌 Creating ChatBot.js
Component
📌 Inside src/components/
, create a new file ChatBot.js
and add the following code:
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
const ChatBot = () => {
const [input, setInput] = useState(""); // Stores user input
const [messages, setMessages] = useState([]); // Stores chat messages
const chatEndRef = useRef(null); // Used to auto-scroll chat to the latest message
// Function to send user message to ChatGPT API
const sendMessage = async () => {
if (!input.trim()) return;
const userMessage = { text: input, sender: "user" };
setMessages([...messages, userMessage]); // Add user message to state
setInput(""); // Clear input after sending message
try {
const res = await axios.post("http://localhost:8000/api/chat", { prompt: input });
const botMessage = { text: res.data.response, sender: "bot" };
setMessages([...messages, userMessage, botMessage]); // Add bot response
} catch (error) {
console.error("Error fetching response", error);
setMessages([...messages, userMessage, { text: "Error retrieving response", sender: "bot" }]);
}
};
// Scroll chat to bottom automatically when new messages arrive
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
return (
<div className="container mt-5">
<div className="card shadow-lg">
<div className="card-header bg-primary text-white text-center">
<h4>ChatGPT Chatbot</h4>
</div>
<div className="card-body chat-box" style={{ height: "400px", overflowY: "auto" }}>
{messages.map((msg, index) => (
<div key={index} className={`d-flex ${msg.sender === "user" ? "justify-content-end" : "justify-content-start"} mb-2`}>
<div className={`p-3 rounded shadow ${msg.sender === "user" ? "bg-primary text-white" : "bg-light text-dark"}`} style={{ maxWidth: "75%" }}>
{msg.text}
</div>
</div>
))}
<div ref={chatEndRef} />
</div>
<div className="card-footer">
<div className="input-group">
<input
type="text"
className="form-control"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendMessage()}
/>
<button className="btn btn-primary" onClick={sendMessage}>
Send
</button>
</div>
</div>
</div>
</div>
);
};
export default ChatBot;
Let's break down this code step by step:
1️⃣ Importing Required Libraries
import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
✔️ React Hooks
useState
: Manages user input and chat messages.useEffect
: Scrolls the chat to the bottom when a new message is added.useRef
: Tracks the last message to ensure smooth auto-scrolling.
✔️ Axios
- Used to make API requests to the backend (FastAPI server at
http://localhost:8000/api/chat
).
✔️ Bootstrap
- Provides prebuilt UI components for styling.
2️⃣ Defining State Variables
const [input, setInput] = useState(""); // Stores user input
const [messages, setMessages] = useState([]); // Stores chat messages
const chatEndRef = useRef(null); // Used to auto-scroll chat to the latest message
✔️ input
: Stores the text entered by the user.
✔️ messages
: Stores the entire chat history (both user and bot messages).
✔️ chatEndRef
: Used for automatic scrolling when new messages arrive.
3️⃣ Function to Handle Sending Messages
const sendMessage = async () => {
if (!input.trim()) return; // Prevent sending empty messages
const userMessage = { text: input, sender: "user" };
setMessages([...messages, userMessage]); // Add user message to chat
setInput(""); // Clear input after sending message
try {
const res = await axios.post("http://localhost:8000/api/chat", { prompt: input });
const botMessage = { text: res.data.response, sender: "bot" };
setMessages([...messages, userMessage, botMessage]); // Add bot response
} catch (error) {
console.error("Error fetching response", error);
setMessages([...messages, userMessage, { text: "Error retrieving response", sender: "bot" }]);
}
};
✔️ Prevents sending blank messages (if (!input.trim()) return;
).
✔️ Stores the user’s message in state before sending it to OpenAI.
✔️ Clears the input field (setInput("")
) for better UX.
✔️ Sends the request to FastAPI (http://localhost:8000/api/chat
).
✔️ Adds the bot’s response to the chat history.
✔️ Handles API errors gracefully.
4️⃣ Auto-Scrolling to Latest Message
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
✔️ Whenever a new message is added, this function scrolls the chat to the bottom.
✔️ Ensures a smooth transition to the latest message.
5️⃣ Chat UI with Bootstrap Styling
<div className="container mt-5">
<div className="card shadow-lg">
<div className="card-header bg-primary text-white text-center">
<h4>ChatGPT Chatbot</h4>
</div>
✔️ Uses Bootstrap classes like container mt-5
to center the chatbot.
✔️ Uses card shadow-lg
to give the UI a modern look.
✔️ Styled header (bg-primary text-white
) for branding.
6️⃣ Displaying Chat Messages
<div className="card-body chat-box" style={{ height: "400px", overflowY: "auto" }}>
{messages.map((msg, index) => (
<div key={index} className={`d-flex ${msg.sender === "user" ? "justify-content-end" : "justify-content-start"} mb-2`}>
<div className={`p-3 rounded shadow ${msg.sender === "user" ? "bg-primary text-white" : "bg-light text-dark"}`} style={{ maxWidth: "75%" }}>
{msg.text}
</div>
</div>
))}
<div ref={chatEndRef} />
</div>
✔️ Dynamically loops through messages and displays them.
✔️ Aligns user messages to the right and bot messages to the left.
✔️ Applies different colors for user (blue) and bot (gray) messages.
7️⃣ Input Field and Send Button
<div className="card-footer">
<div className="input-group">
<input
type="text"
className="form-control"
placeholder="Type your message..."
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendMessage()}
/>
<button className="btn btn-primary" onClick={sendMessage}>
Send
</button>
</div>
</div>
✔️ Allows sending messages by pressing "Enter" or clicking the Send button.
📌 Step 7: Modify App.js
to Include the Chatbot
📌 Inside src/
, open App.js
and replace the content with the following:
import React from "react";
import ChatBot from "./components/ChatBot";
function App() {
return (
<div className="d-flex justify-content-center align-items-center vh-100 bg-light">
<ChatBot />
</div>
);
}
export default App;
✔️ Imports the ChatBot
component from ./components/ChatBot.js
.
✔️ Centers the chatbot UI using Bootstrap's flex utilities (d-flex justify-content-center align-items-center
).
✔️ Applies a light background (bg-light
) to improve visibility.
✔️ Ensures the app takes the full viewport height (vh-100
).
🚀 Step 8: Run the React Application
Now, we can start the React app and test the chatbot UI.
📌 Run the following command:
npm run dev
📌 Open your browser and go to:
👉 http://localhost:5173
🚀 Step 9: Run the FastAPI Backend
📌 Before using the chatbot, make sure your FastAPI server is running!
In another terminal, navigate to the FastAPI project folder and start the server:
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
📌 FastAPI server will be available at:
👉 http://localhost:8000/docs (Swagger UI)
👉 http://localhost:8000/api/chat (Chatbot API endpoint)
Now that our chatbot is running locally, let’s test it and prepare for deployment.
🔹 Step 10: Test the Full Chatbot Application
✅ Open http://localhost:5173 in your browser.
✅ Type messages and get AI responses in real-time.
✅ Ensure FastAPI is running to avoid connection errors.
🎯 Summary: What We Achieved
✔️ Built a FastAPI backend that integrates with OpenAI’s ChatGPT API.
✔️ Created a REST API (/api/chat
) to process chatbot requests.
✔️ Developed a React frontend with Bootstrap for a clean UI.
✔️ Connected React JS to the FastAPI backend using Axios.
🎉 Your AI Chatbot is now fully functional and ready for real-world use! 🚀
🚀 Next Steps: Enhance Your Chatbot
Now that your chatbot is working, here are some ideas for improvement:
✅ Store Chat History - Save conversations in a database (MongoDB, PostgreSQL, SQLite).
✅ Add User Authentication - Implement login/signup using Firebase or JWT authentication.
✅ Improve UI - Add chat bubbles, avatars, or voice input.
✅ Support Multiple AI Models - Allow users to choose between GPT-3.5, GPT-4, or a fine-tuned model.
❓ Frequently Asked Questions (FAQs)
1. Why is my FastAPI server returning a 404 error?
✔️ Make sure the FastAPI server is running (uvicorn main:app --port 8000
).
✔️ Check that the correct endpoint (/api/chat
) is being called in ChatBot.js
.
2. How can I change the ChatGPT model?
✔️ In main.py
, modify:
model="gpt-4o-mini"
✔️ Change it to gpt-3.5-turbo
or gpt-4
based on your OpenAI plan.
3. How do I improve chatbot response speed?
✔️ Use faster models like gpt-3.5-turbo
.
✔️ Optimize API calls using asynchronous requests (async/await
).
Comments
Post a Comment
Leave Comment