How to Build an AI Chatbot Using OpenAI and Streamlit

How to Build an AI Chatbot Using OpenAI and Streamlit

How to Build an AI Chatbot Using OpenAI and Streamlit

Interested in above project ,Click Below
WhatsApp
Telegram
LinkedIn

How to Build an AI Chatbot Using OpenAI and Streamlit

Want to build a production-level AI Chatbot Application that goes beyond a simple chat interface? This full-stack Python project uses FastAPI as the backend, Streamlit as the frontend, OpenAI GPT-3.5 Turbo as the AI brain, and MongoDB as the database — making it one of the most complete final year projects for BCA, MCA, and B.Tech CS/IT students in 2026.

This project includes 7 powerful AI modules — from AI chat and image generation to PDF Q&A and text summarization — all secured with JWT authentication and daily usage limits.

Project Overview

Project NameAI Chatbot Application
BackendFastAPI (Python)
FrontendStreamlit
AI EngineOpenAI GPT-3.5 Turbo + DALL-E 3
DatabaseMongoDB with Motor async driver
AuthenticationJWT Token + bcrypt
DifficultyIntermediate to Advanced
Best ForBCA, MCA, B.Tech CS/IT Final Year Students

7 Key Modules of This Project

ModuleDescription
AI ChatConversational AI using GPT-3.5 Turbo with full context memory
Image GeneratorGenerate images from text prompts using DALL-E 3
PDF Q&AUpload any PDF and ask questions — get AI-powered answers
Text SummarizerPaste any text and get short, medium, or long summary instantly
Chat HistoryBrowse, view, resume, or delete all past conversations
Profile and SettingsEdit username, change password, monitor daily usage stats
AuthenticationSecure login and registration with JWT tokens and bcrypt hashing

Download Full Source Code

The complete source code — backend routes, Streamlit pages, .env template, and requirements.txt — is available below.

See also  Chandrayaan-3's revolutionary AI technology guarantees successful lunar landing!

Technologies Used

LayerTechnologyPurpose
FrontendStreamlitInteractive web UI
BackendFastAPIHigh-performance async REST API
AI ChatOpenAI GPT-3.5 TurboChat, PDF Q&A, and text summarization
Image AIOpenAI DALL-E 3Text-to-image generation
DatabaseMongoDBStore users, conversations, usage data
DB DriverMotorAsync MongoDB driver for Python
Authpython-jose + bcryptJWT tokens and secure password hashing
PDF ParserPyPDF2Extract and chunk text from uploaded PDFs
HTTP ClientRequestsFrontend-to-backend communication
Configpython-dotenvLoad environment variables from .env

Project Folder Structure

Ai chatbot/
├── .env
├── requirements.txt
├── run.bat
│
├── backend/
│   ├── main.py
│   ├── config.py
│   ├── database/
│   │   └── mongodb.py
│   ├── models/
│   │   ├── user.py
│   │   └── chat.py
│   ├── routes/
│   │   ├── auth.py
│   │   ├── chat.py
│   │   ├── image.py
│   │   ├── pdf.py
│   │   └── summarizer.py
│   └── services/
│       ├── auth_service.py
│       ├── ai_service.py
│       └── pdf_service.py
│
└── frontend/
    ├── app.py
    ├── pages/
    │   ├── login.py
    │   ├── register.py
    │   ├── chat.py
    │   ├── image_gen.py
    │   ├── pdf_qa.py
    │   ├── summarizer.py
    │   ├── history.py
    │   └── settings.py
    └── utils/
        └── api_client.py

Prerequisites

  • Python 3.10 or higher installed on your system
  • MongoDB running on localhost:27017 (local install or Docker)
  • OpenAI API Key from platform.openai.com with billing enabled
  • Basic knowledge of Python, REST APIs, and terminal commands

How to Run This Project

Step 1 — Install All Dependencies

cd "Ai chatbot"
pip install -r requirements.txt

Step 2 — Configure Your .env File

Create a .env file in the root project folder and add the following:

OPENAI_API_KEY=sk-proj-your-actual-api-key-here
MONGODB_URL=mongodb://localhost:27017
DATABASE_NAME=ai_chatbot
JWT_SECRET_KEY=your-random-secret-key-here
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
MAX_MESSAGES_PER_DAY=50
MAX_MESSAGE_LENGTH=2000
MAX_PDF_SIZE_MB=10

Step 3 — Start MongoDB

# Local install
mongod

# Or using Docker
docker run -d -p 27017:27017 --name mongodb mongo:latest

Step 4 — Start the FastAPI Backend

cd "Ai chatbot"
uvicorn backend.main:app --host 127.0.0.1 --port 8000

Backend runs at: http://localhost:8000
API docs at: http://localhost:8000/docs

See also  Deep Learning Tutorial

Step 5 — Start the Streamlit Frontend

streamlit run frontend/app.py --server.port 8501

Frontend runs at: http://localhost:8501 — open this in your browser and you’re ready!

API Endpoints Reference

Authentication

MethodEndpointDescriptionAuth
POST/api/auth/registerRegister a new userNo
POST/api/auth/loginLogin and get JWT tokenNo
GET/api/auth/profileGet user profileYes
PUT/api/auth/profileUpdate username or nameYes
POST/api/auth/change-passwordChange passwordYes

AI Chat

MethodEndpointDescriptionAuth
POST/api/chat/sendSend message, get AI responseYes
GET/api/chat/conversationsList all conversationsYes
GET/api/chat/conversations/{id}Get full conversationYes
DELETE/api/chat/conversations/{id}Delete a conversationYes
GET/api/chat/usageGet today’s usage statsYes

Image, PDF and Summarizer

MethodEndpointDescriptionAuth
POST/api/image/generateGenerate image using DALL-E 3Yes
POST/api/pdf/uploadUpload a PDF fileYes
POST/api/pdf/askAsk question about the PDFYes
POST/api/summarize/Summarize a block of textYes

Security Features

  • JWT Authentication — all protected routes require a valid Bearer token
  • bcrypt Password Hashing — passwords are never stored as plain text
  • Pydantic Input Validation — all request data is validated for format and length
  • Daily Rate Limiting — each user is limited to 50 messages per day (configurable)
  • PDF File Size Cap — uploads are limited to 10MB by default
  • CORS Middleware — cross-origin requests handled securely

Configurable Limits via .env

LimitationDefaultConfig Key
Messages per day per user50MAX_MESSAGES_PER_DAY
Max characters per message2,000MAX_MESSAGE_LENGTH
Max PDF file size10 MBMAX_PDF_SIZE_MB
Max text for summarization10,000 charshardcoded in model
Image prompt max length1,000 charshardcoded in model
JWT token expiry60 minsACCESS_TOKEN_EXPIRE_MINUTES

MongoDB Collections

CollectionPurposeKey Fields
usersUser accounts and profilesusername, email, password_hash, full_name
chatsConversations and messagesuser_id, title, module, messages[], pdf_text
daily_usageRate limit trackinguser_id, date, count

How the Application Works

Login and Registration

  1. User fills the form on the Streamlit UI
  2. Frontend sends POST to /api/auth/register or /api/auth/login
  3. Backend validates credentials and creates or verifies user in MongoDB
  4. JWT token is returned and stored in Streamlit session state
  5. All future requests include the token as Authorization: Bearer token
See also  AI Tools for Students in 2026: Best Free Tools to Study Smarter

AI Chat

  1. User types a message in the Streamlit chat UI
  2. Message is sent to /api/chat/send with JWT token
  3. Backend loads the last 10 messages for conversation context
  4. Full context is sent to OpenAI GPT-3.5 Turbo
  5. AI response is saved to MongoDB and returned to the frontend

PDF Q&A

  1. User uploads a PDF — PyPDF2 extracts all text from the file
  2. Extracted text is stored in a MongoDB conversation document
  3. User asks a question about the PDF content
  4. Text is chunked and relevant sections found using keyword matching
  5. Relevant context plus question is sent to GPT-3.5 Turbo and answer is returned

Image Generation

  1. User enters a text prompt and selects size and quality settings
  2. Request is sent to /api/image/generate
  3. Backend calls DALL-E 3 API with the prompt and preferences
  4. Generated image URL is returned and displayed in the Streamlit UI

Why This is a Great Final Year Project

  • Uses real industry-level tools — FastAPI, OpenAI API, MongoDB, JWT
  • Covers both frontend and backend — ideal for full stack Python developers
  • 7 modules in one project — highly impressive for viva and presentations
  • Easy to extend — add voice input, language translation, or analytics
  • GPT-3.5 Turbo and DALL-E 3 are the most in-demand AI skills in 2026
  • One-click Windows startup with run.bat — easy to demo to examiners

Need help setting it up? Drop a comment below or visit updategadh.com for more free Python projects with source code.


🎓 Need Complete Final Year Project?

Get Source Code + Report + PPT + Viva Questions (Instant Access)

🛒 Visit UpdateGadh Store →
💬 Chat Now