📖 Project Overview
This chatbot project integrates with OpenAI GPT API to create intelligent conversational interfaces. Features include message handling, context management, and response generation. Perfect for building chatbots with advanced language understanding and natural conversation capabilities.
✨ Features
Core Features
🔌 OpenAI API Integration
Seamless integration with OpenAI GPT-3 and GPT-4 APIs for intelligent conversations.
🤖 GPT-3 & GPT-4 Support
Support for multiple models including GPT-3.5 Turbo, GPT-4, and GPT-4 Turbo.
💬 Conversation Management
Full conversation history and context handling for natural conversations.
⚙️ Easy Customization
Highly customizable system prompts, temperature, and response parameters.
Advanced Features
🚀 Streaming Responses
Real-time token streaming for faster perceived response times using Server-Sent Events (SSE).
📊 Token Usage Tracking
Monitor token consumption, API usage, and costs in real-time with comprehensive statistics.
📈 Conversation Statistics
Track messages, requests, token usage, and session duration with detailed analytics.
💾 Export Conversations
Export conversations as JSON or TXT format with metadata and statistics included.
🔍 Conversation Search
Full-text search across conversation history with case-insensitive matching and highlighting.
📝 Markdown Rendering
Beautiful markdown and code syntax highlighting with multiple language support.
🌙 Dark Mode
Toggle between light and dark themes with persistent preference storage.
🎭 Custom Personas
8 pre-built personas: Coding, Creative, Teacher, Business, Friendly, Technical, Translator, and Default.
🔄 Advanced Error Handling
Retry logic with exponential backoff, graceful error messages, and network error handling.
🌐 Web Interface
Beautiful and modern Flask-based web application with responsive design.
⚙️ Settings Panel
Configure model, temperature, tokens, personas, and other settings easily.
💻 CLI Interface
Full-featured command-line interface for terminal usage with all features.
🛠️ Technologies
OpenAI API
Official OpenAI API for GPT models
APIPython 3.7+
Modern Python programming language
LanguageFlask 2.3.0+
Lightweight web framework
FrameworkGPT-3 & GPT-4
Advanced language models
AI ModelsHTML5/CSS3/JavaScript
Modern web technologies
FrontendMarked.js & Highlight.js
Markdown parsing and syntax highlighting
Libraries📦 Installation
Prerequisites
- Python 3.7 or higher
- OpenAI API key (Get one here)
Setup Steps
- Clone or download this project
- Install dependencies:
pip install -r requirements.txt - Set up your OpenAI API key:
Option 1: Using .env file (Recommended)
Copy the example file:
# Windows copy env_example.txt .env # Linux/Mac cp env_example.txt .envThen edit .env and replace your_openai_api_key_here with your actual API key.
Option 2: Environment variable
# Windows (PowerShell) $env:OPENAI_API_KEY="your_openai_api_key_here" # Linux/Mac export OPENAI_API_KEY=your_openai_api_key_hereGet your API key from: https://platform.openai.com/api-keys
- Run the chatbot:
Command Line Interface:
python chatbot.pyWeb Interface:
python app.pyThen open your browser and navigate to http://localhost:5000
📚 Usage
Command Line Interface
Run python chatbot.py and start chatting! Commands:
- Type your message and press Enter
- Type quit or exit to end the conversation
- Type clear to clear conversation history
- Type history to view conversation history
Web Interface
- Start the Flask server: python app.py
- Open http://localhost:5000 in your browser
- Start chatting with the AI assistant
- Use the Settings button to configure:
- Model selection (GPT-3.5 Turbo, GPT-4, etc.)
- Temperature (controls randomness)
- Max tokens (response length)
- Persona selection
💻 Code Examples
Basic Usage
from chatbot import GPTChatbot
# Initialize chatbot
chatbot = GPTChatbot(model="gpt-3.5-turbo")
# Set custom system prompt
chatbot.set_system_prompt("You are a helpful assistant.")
# Get response
response = chatbot.get_response("Hello, how are you?")
print(response)
# Save conversation
chatbot.save_conversation("conversation.json")
Using GPT-4
from chatbot import GPTChatbot
# Initialize with GPT-4
chatbot = GPTChatbot(model="gpt-4")
# Get response with custom parameters
response = chatbot.get_response(
"Explain quantum computing",
temperature=0.8,
max_tokens=1000
)
Streaming Response
for chunk in chatbot.get_streaming_response("Hello"):
print(chunk, end='', flush=True)
Get Statistics
stats = chatbot.get_conversation_stats()
print(f"Total tokens: {stats['token_usage']['total_tokens']}")
print(f"Total requests: {stats['total_requests']}")
Search Conversation
results = chatbot.search_conversation("python")
for msg in results:
print(f"{msg['role']}: {msg['content']}")
Export Conversation
# Export as JSON
chatbot.save_conversation("chat.json")
# Export as TXT
chatbot.export_conversation_txt("chat.txt")
Use Persona
from personas import get_persona
persona = get_persona("coding")
chatbot.set_system_prompt(persona['system_prompt'])
🔗 API Endpoints (Web Interface)
Basic Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | / | Main chat interface |
| POST | /api/chat | Send message and get response |
| POST | /api/chat/stream | Stream response (Server-Sent Events) |
| POST | /api/clear | Clear conversation history |
| GET | /api/history | Get conversation history |
| GET | /api/info | Get application information |
Advanced Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/stats | Get conversation statistics and token usage |
| POST | /api/reset-stats | Reset statistics |
| GET | /api/export/json | Export conversation as JSON |
| GET | /api/export/txt | Export conversation as TXT |
| POST | /api/search | Search conversation history |
| GET | /api/summary | Get conversation summary |
| GET | /api/personas | Get all available personas |
| POST | /api/personas/<key> | Set persona for session |
| GET | /api/templates | Get conversation templates |
⚙️ Configuration
Edit config.py to customize:
- Default model (GPT-3.5 Turbo, GPT-4, GPT-4 Turbo)
- Temperature settings (0.0 - 2.0)
- Max tokens configuration
- System prompts
- Conversation settings
Available Personas
Default Assistant
General-purpose helper
Coding Assistant
Programming expert
Creative Writer
Creative writing specialist
Educational Tutor
Teaching assistant
Business Advisor
Professional consultant
Friendly Chat
Casual conversation
Technical Expert
Deep technical analysis
Translation Assistant
Multilingual support
📁 Project Structure
openai-gpt-chatbot/
├── chatbot.py # Main chatbot class and CLI
├── app.py # Flask web application
├── config.py # Configuration settings
├── personas.py # Personas and templates
├── example_usage.py # Usage examples
├── setup.py # Package setup script
├── requirements.txt # Python dependencies
├── env_example.txt # Environment variables example
├── DOCUMENTATION.md # Complete documentation
├── README.md # Project overview
├── RELEASE_NOTES_v1.0.0.md # Release notes
├── LICENSE # MIT License
├── .gitignore # Git ignore file
├── __pycache__/ # Python cache directory (auto-generated)
├── templates/
│ └── index.html # Web interface HTML
└── static/
├── style.css # Stylesheet
└── script.js # Frontend JavaScript
📄 Detailed File Descriptions
🤖 chatbot.py
Size: ~17KB | Lines: ~470
Purpose: Main chatbot class with OpenAI API integration. Contains the GPTChatbot class with all core functionality including conversation management, streaming responses, token tracking, export, and search capabilities.
Key Features:
- GPTChatbot class implementation
- OpenAI API integration
- Conversation history management
- Streaming response support
- Token usage tracking
- Export functionality (JSON/TXT)
- Conversation search
- Error handling with retry logic
- Command-line interface (CLI)
🌐 app.py
Size: ~11KB | Lines: ~386
Purpose: Flask web application providing RESTful API endpoints and serving the web interface. Handles session management, API routing, and server-side functionality.
Key Features:
- Flask web server setup
- Session-based chatbot instances
- RESTful API endpoints
- Server-Sent Events (SSE) for streaming
- Conversation export (JSON/TXT)
- Statistics tracking
- Persona management
- Template rendering
⚙️ config.py
Size: ~2.8KB | Lines: ~94
Purpose: Configuration settings and constants. Centralized configuration management for models, API keys, response parameters, and application settings.
Key Features:
- Config class with default settings
- OpenAI API key management
- Model configuration (GPT-3.5, GPT-4)
- Temperature and token limits
- System prompt defaults
- Conversation settings
- Application metadata
- Configuration validation
🎭 personas.py
Size: ~5.1KB | Lines: ~147
Purpose: Pre-defined conversation personas and templates. Contains 8 different personas (coding, creative, teacher, business, etc.) and conversation templates for quick starts.
Key Features:
- 8 pre-built personas
- Persona helper functions
- Conversation templates
- System prompt definitions
- Persona descriptions
- Template management functions
📚 example_usage.py
Size: ~6.1KB | Lines: ~212
Purpose: Comprehensive usage examples demonstrating various ways to use the chatbot. Includes examples for basic usage, GPT-4, streaming, personas, export, and more.
Key Features:
- Basic usage examples
- GPT-4 usage examples
- Streaming response examples
- Persona usage examples
- Export examples
- Statistics examples
- Search examples
📦 setup.py
Size: ~1.1KB | Lines: ~41
Purpose: Python package setup script for distribution. Allows the project to be installed as a package using pip.
Key Features:
- Package metadata
- Dependency management
- Python version requirements
- Package classifiers
- Installation configuration
📋 requirements.txt
Size: ~202B | Lines: 11
Purpose: Python package dependencies list. Contains all required Python packages with version specifications.
Dependencies:
- openai >= 1.0.0
- python-dotenv >= 1.0.0
- flask >= 2.3.0
🔑 env_example.txt
Size: ~1.9KB | Lines: 58
Purpose: Template file for environment variables. Shows required and optional configuration variables with examples and instructions.
Key Features:
- OpenAI API key template
- Flask configuration options
- Server configuration
- OpenAI model settings
- Setup instructions
- Security notes
📖 README.md
Size: ~8.9KB | Lines: 360
Purpose: Project overview and quick start guide. Provides introduction, features, installation instructions, usage examples, and basic documentation.
Contents:
- Project description
- Features list
- Installation guide
- Usage examples
- API endpoints
- Configuration guide
- Troubleshooting
- Support information
📘 DOCUMENTATION.md
Size: ~18KB | Lines: 715
Purpose: Complete comprehensive documentation. Detailed documentation covering all aspects of the project including advanced features, API reference, code examples, and troubleshooting.
Contents:
- Project overview
- Quick start guide
- Detailed installation
- Feature documentation
- API endpoints reference
- Configuration details
- Code examples
- Project structure
- Error fixes
- Troubleshooting guide
📝 RELEASE_NOTES_v1.0.0.md
Size: ~5.5KB | Lines: 200
Purpose: Release notes for version 1.0.0. Documents features, changes, and updates in the initial release.
Contents:
- Release information
- Feature list
- What's included
- Quick start guide
- Statistics
- Technical details
- Changelog
⚖️ LICENSE
Size: ~1.2KB | Lines: 29
Purpose: MIT License file. Contains the full MIT License text and copyright information.
License Type: MIT License
Copyright: © 2026 RSK World
🚫 .gitignore
Size: ~566B | Lines: 55
Purpose: Git ignore rules. Specifies files and directories that should not be tracked by version control.
Excluded Items:
- .env files (API keys)
- __pycache__/ directories
- Python bytecode files
- Virtual environments
- IDE configuration files
- Conversation files
- OS-specific files
- Log files
📂 templates/
Type: Directory
Purpose: Flask templates directory. Contains HTML templates for the web interface.
Files:
- index.html - Main web interface HTML template with complete chat UI, settings panel, modals, and all interactive elements
🎨 static/
Type: Directory
Purpose: Static assets directory. Contains CSS stylesheets and JavaScript files for the web interface.
Files:
- style.css - Complete stylesheet with modern design, dark mode support, responsive layout, animations, and all UI styling
- script.js - Frontend JavaScript with chat functionality, API integration, markdown rendering, syntax highlighting, streaming support, and all interactive features
💾 __pycache__/
Type: Directory (Auto-generated)
Purpose: Python cache directory. Automatically created by Python to store compiled bytecode (.pyc files) for faster module loading.
Note: This directory is automatically generated and should not be edited. It's excluded from version control via .gitignore.
📂 .git/
Type: Directory
Purpose: Git version control directory. Contains all Git repository metadata, commit history, branches, and configuration.
Note: This is a hidden directory used by Git for version control. It contains the complete history of the repository.
📊 File Statistics
📌 File Organization
Core Python Files: chatbot.py, app.py, config.py, personas.py, example_usage.py
Configuration Files: setup.py, requirements.txt, env_example.txt, .gitignore
Documentation: README.md, DOCUMENTATION.md, RELEASE_NOTES_v1.0.0.md, LICENSE
Web Interface: templates/index.html, static/style.css, static/script.js
Auto-generated: __pycache__/, .git/
🚀 Advanced Features Details
1. Streaming Responses
Real-time token streaming for faster perceived response times using Server-Sent Events (SSE). Enable/disable via toggle in the UI.
2. Token Usage Tracking
Monitor API usage, costs, and token consumption with real-time statistics display. Track prompt tokens, completion tokens, and total tokens.
3. Conversation Statistics
Comprehensive analytics including total messages count, total API requests, token usage breakdown, and session duration with reset functionality.
4. Export Functionality
Export conversations in JSON or TXT format with one-click export. Includes conversation history, token usage statistics, and timestamped filenames.
5. Conversation Search
Full-text search across all messages with case-insensitive matching, results with context, and highlight matching content.
6. Markdown Rendering
Beautiful markdown and code display with full markdown support, code syntax highlighting, and multiple language support using Marked.js and Highlight.js.
7. Dark Mode
Toggle between light and dark themes with persistent theme preference (localStorage), smooth transitions, and optimized color schemes.
8. Advanced Error Handling
Robust error management with automatic retry with exponential backoff, configurable retry attempts (default: 3), graceful error messages, and network error handling.
🔧 Troubleshooting
API Key Issues
- Make sure your .env file contains OPENAI_API_KEY=your_key
- Or set the environment variable: export OPENAI_API_KEY=your_key
- Verify your API key is valid at OpenAI Platform
Import Errors
- Install all dependencies: pip install -r requirements.txt
- Make sure you're using Python 3.7+
Rate Limits
- OpenAI API has rate limits based on your plan
- If you hit rate limits, wait a moment and try again
- Consider upgrading your OpenAI plan for higher limits
Common Issues
- Module not found errors: Run pip install -r requirements.txt
- API key errors: Check your .env file or environment variables
- Port already in use: Change the port in app.py or stop the existing process
- Streaming not working: Check browser console for errors, ensure SSE is supported
📋 Requirements
openai>=1.0.0
python-dotenv>=1.0.0
flask>=2.3.0
🎯 Use Cases
💻 Development
AI coding assistant for developers
📚 Education
Learning and tutoring platform
💼 Business
Professional consultation and advice
✍️ Creative Writing
Storytelling and content creation
💬 General Chat
Casual conversations and assistance
🌍 Translation
Multilingual support and translation
💬 Support
For support, questions, or more projects:
- Website: https://rskworld.in
- Email: help@rskworld.in
- Phone: +91 93305 39277
📄 License
This project is provided as-is for educational and development purposes.
MIT License - See LICENSE file for details.
📂 Demo Folder Structure
The demo/ folder contains demonstration and documentation files for this project.
demo/
├── index.html # This documentation page
├── style.css # Stylesheet (optional, styles are inline)
└── script.js # JavaScript (optional, can be added for interactivity)
📄 Demo Files Description
📄 index.html
Purpose: Comprehensive project documentation and information page. This HTML file contains all details about the OpenAI GPT Chatbot project.
Contents:
- Complete project overview
- All features documentation
- Installation instructions
- Usage examples
- Code examples
- API endpoints reference
- Configuration details
- Detailed file and folder descriptions
- Project structure
- Troubleshooting guide
- Support information
Features:
- Self-contained HTML with inline CSS
- Responsive design
- Modern, beautiful UI
- Well-organized sections
- Easy navigation
🎨 style.css
Purpose: External stylesheet file (optional). Currently, all styles are embedded inline in index.html, but this file can be used for additional custom styles if needed.
Status: Empty file - can be used for custom styling
Usage: Add custom CSS styles here if you want to override or extend the inline styles in index.html
📜 script.js
Purpose: External JavaScript file (optional). Can be used to add interactive features to the documentation page.
Status: Empty file - can be used for additional functionality
Potential Uses:
- Table of contents navigation
- Smooth scrolling
- Search functionality
- Copy code snippets
- Theme toggle
- Print functionality
- Interactive elements
💡 About the Demo Folder
The demo/ folder is separate from the main openai-gpt-chatbot/ project folder. It contains:
- Documentation: This comprehensive HTML documentation page that explains the entire project
- Styling: Optional CSS file for custom styling
- Scripts: Optional JavaScript file for enhanced interactivity
Note: To view this documentation, simply open demo/index.html in any web browser. The page is self-contained and works offline.