help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
openai-gpt-chatbot
/
templates
RSK World
openai-gpt-chatbot
OpenAI GPT Chatbot - GPT-3 + GPT-4 + ChatGPT + Streaming + Token Tracking + Flask + Python
templates
  • index.html10.9 KB
RELEASE_NOTES.mdHOW_TO_CREATE_RELEASE.mdanalytics_dashboard.jsfitness_coach.cpython-313.pycapp.pyPROJECT_CHECK_SUMMARY.mdREADME.md
app.py
Raw Download
Find: Go to:
"""
Flask Web Application for OpenAI GPT Chatbot

Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026

Web interface for the OpenAI GPT Chatbot with conversation management.
"""

from flask import Flask, render_template, request, jsonify, session, Response, send_file
from chatbot import GPTChatbot
from config import Config
from personas import get_all_personas, get_persona, get_all_templates
import os
import uuid
import json as json_lib
from datetime import datetime
from io import BytesIO

# Author: RSK World (https://rskworld.in) - Year: 2026
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY", "rskworld-2026-secret-key-change-in-production")

# Store chatbot instances per session
# Author: RSK World (https://rskworld.in) - Year: 2026
chatbots = {}


def get_chatbot():
    """
    Get or create chatbot instance for current session
    
    Returns:
        GPTChatbot instance
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    if 'session_id' not in session:
        session['session_id'] = str(uuid.uuid4())
    
    session_id = session['session_id']
    
    if session_id not in chatbots:
        chatbots[session_id] = GPTChatbot(
            api_key=Config.OPENAI_API_KEY,
            model=Config.DEFAULT_MODEL
        )
        chatbots[session_id].set_system_prompt(Config.DEFAULT_SYSTEM_PROMPT)
    
    return chatbots[session_id]


@app.route('/')
def index():
    """
    Render main chat interface
    
    Returns:
        Rendered HTML template
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    app_info = Config.get_info()
    return render_template('index.html', app_info=app_info)


@app.route('/api/chat', methods=['POST'])
def chat():
    """
    Handle chat API requests
    
    Returns:
        JSON response with assistant message
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        data = request.get_json()
        user_message = data.get('message', '').strip()
        model = data.get('model', Config.DEFAULT_MODEL)
        temperature = float(data.get('temperature', Config.DEFAULT_TEMPERATURE))
        max_tokens = int(data.get('max_tokens', Config.DEFAULT_MAX_TOKENS))
        
        if not user_message:
            return jsonify({'error': 'Message is required'}), 400
        
        chatbot = get_chatbot()
        chatbot.model = model
        
        response = chatbot.get_response(
            user_message,
            temperature=temperature,
            max_tokens=max_tokens
        )
        
        return jsonify({
            'response': response,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/clear', methods=['POST'])
def clear_history():
    """
    Clear conversation history
    
    Returns:
        JSON response confirming history cleared
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        chatbot.clear_history()
        return jsonify({'message': 'Conversation history cleared'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/history', methods=['GET'])
def get_history():
    """
    Get conversation history
    
    Returns:
        JSON response with conversation history
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        history = chatbot.get_conversation_history()
        return jsonify({'history': history})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/info', methods=['GET'])
def get_info():
    """
    Get application information
    
    Returns:
        JSON response with app information
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    return jsonify(Config.get_info())


@app.route('/api/chat/stream', methods=['POST'])
def chat_stream():
    """
    Handle streaming chat API requests
    
    Returns:
        Server-Sent Events stream
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        data = request.get_json()
        user_message = data.get('message', '').strip()
        model = data.get('model', Config.DEFAULT_MODEL)
        temperature = float(data.get('temperature', Config.DEFAULT_TEMPERATURE))
        max_tokens = int(data.get('max_tokens', Config.DEFAULT_MAX_TOKENS))
        
        if not user_message:
            return jsonify({'error': 'Message is required'}), 400
        
        chatbot = get_chatbot()
        chatbot.model = model
        
        def generate():
            try:
                for chunk in chatbot.get_streaming_response(user_message, temperature, max_tokens):
                    yield f"data: {json_lib.dumps({'chunk': chunk})}\n\n"
                yield f"data: {json_lib.dumps({'done': True})}\n\n"
            except Exception as e:
                yield f"data: {json_lib.dumps({'error': str(e)})}\n\n"
        
        return Response(generate(), mimetype='text/event-stream')
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/stats', methods=['GET'])
def get_stats():
    """
    Get conversation statistics and token usage
    
    Returns:
        JSON response with statistics
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        stats = chatbot.get_conversation_stats()
        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/export/json', methods=['GET'])
def export_json():
    """
    Export conversation as JSON
    
    Returns:
        JSON file download
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        history = chatbot.get_conversation_history()
        stats = chatbot.get_conversation_stats()
        
        export_data = {
            "conversation": history,
            "statistics": stats,
            "export_date": datetime.now().isoformat(),
            "author": "RSK World (https://rskworld.in)"
        }
        
        json_str = json_lib.dumps(export_data, indent=2, ensure_ascii=False)
        filename = f"conversation_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        return Response(
            json_str,
            mimetype='application/json',
            headers={'Content-Disposition': f'attachment; filename={filename}'}
        )
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/export/txt', methods=['GET'])
def export_txt():
    """
    Export conversation as plain text
    
    Returns:
        TXT file download
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        filename = f"conversation_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        # Generate text content
        content = chatbot._generate_txt_content()
        
        # Create BytesIO with content
        output = BytesIO()
        output.write(content.encode('utf-8'))
        output.seek(0)
        
        return send_file(
            output,
            mimetype='text/plain',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/search', methods=['POST'])
def search_conversation():
    """
    Search conversation history
    
    Returns:
        JSON response with matching messages
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        data = request.get_json()
        query = data.get('query', '').strip()
        
        if not query:
            return jsonify({'error': 'Search query is required'}), 400
        
        chatbot = get_chatbot()
        results = chatbot.search_conversation(query)
        
        return jsonify({
            'query': query,
            'results': results,
            'count': len(results)
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/summary', methods=['GET'])
def get_summary():
    """
    Get conversation summary
    
    Returns:
        JSON response with conversation summary
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        summary = chatbot.get_conversation_summary()
        return jsonify({'summary': summary})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/reset-stats', methods=['POST'])
def reset_stats():
    """
    Reset conversation statistics
    
    Returns:
        JSON response confirming reset
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        chatbot = get_chatbot()
        chatbot.reset_stats()
        return jsonify({'message': 'Statistics reset successfully'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/personas', methods=['GET'])
def get_personas():
    """
    Get all available personas
    
    Returns:
        JSON response with personas
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    return jsonify(get_all_personas())


@app.route('/api/personas/<persona_key>', methods=['POST'])
def set_persona(persona_key):
    """
    Set persona for current session
    
    Args:
        persona_key: Key of the persona to set
        
    Returns:
        JSON response confirming persona set
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    try:
        persona = get_persona(persona_key)
        chatbot = get_chatbot()
        chatbot.set_system_prompt(persona['system_prompt'])
        return jsonify({
            'message': f"Persona '{persona['name']}' set successfully",
            'persona': persona
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/templates', methods=['GET'])
def get_templates():
    """
    Get all available conversation templates
    
    Returns:
        JSON response with templates
    """
    # Author: RSK World (https://rskworld.in) - Year: 2026
    return jsonify(get_all_templates())


if __name__ == '__main__':
    # Author: RSK World (https://rskworld.in) - Year: 2026
    if not Config.validate():
        print("Warning: OPENAI_API_KEY not set. Please set it in .env file.")
        print("For more information, visit: https://rskworld.in")
    
    app.run(debug=True, host='0.0.0.0', port=5000)

386 lines•10.9 KB
python
README.md
Raw Download

README.md

# OpenAI GPT Chatbot

Complete chatbot project using OpenAI GPT API for intelligent conversations and text generation.

**Author:** RSK World
**Website:** https://rskworld.in
**Email:** help@rskworld.in
**Phone:** +91 93305 39277
**Year:** 2026

> 📖 **For complete documentation, see [DOCUMENTATION.md](DOCUMENTATION.md)**

## Description

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
- ✅ GPT-3 and GPT-4 support
- ✅ Conversation management
- ✅ Context handling
- ✅ Easy to customize

### Advanced Features
- ✅ **Streaming Responses** - Real-time token streaming for faster responses
- ✅ **Token Usage Tracking** - Monitor token consumption and costs
- ✅ **Conversation Statistics** - Track messages, requests, and usage
- ✅ **Export Conversations** - Export as JSON or TXT format
- ✅ **Conversation Search** - Search through conversation history
- ✅ **Markdown Rendering** - Beautiful markdown and code syntax highlighting
- ✅ **Dark Mode** - Toggle between light and dark themes
- ✅ **Custom Personas** - 8 pre-built personas (Coding, Creative, Teacher, etc.)
- ✅ **Advanced Error Handling** - Retry logic with exponential backoff
- ✅ **Web Interface** - Beautiful and modern UI with Flask
- ✅ **Settings Panel** - Configure model, temperature, tokens, and personas

## Technologies

- OpenAI API
- Python
- GPT-3
- GPT-4
- ChatGPT
- Flask (for web interface)
- HTML/CSS/JavaScript

## Difficulty Level

**Beginner** - Perfect for developers new to AI chatbots and OpenAI API integration.

## Installation

### Prerequisites

- Python 3.7 or higher
- OpenAI API key ([Get one here](https://platform.openai.com/api-keys))

### Setup Steps

1. **Clone or download this project**

2. **Install dependencies:**
```bash
pip install -r requirements.txt
```

3. **Set up your OpenAI API key:**

**Option 1: Using .env file (Recommended)**

Copy the example file:
```bash
# Windows
copy env_example.txt .env

# Linux/Mac
cp env_example.txt .env
```

Then edit `.env` and replace `your_openai_api_key_here` with your actual API key.

**Option 2: Environment variable**
```bash
# Windows (PowerShell)
$env:OPENAI_API_KEY="your_openai_api_key_here"

# Linux/Mac
export OPENAI_API_KEY=your_openai_api_key_here
```

Get your API key from: https://platform.openai.com/api-keys

4. **Run the chatbot:**

**Command Line Interface:**
```bash
python chatbot.py
```

**Web Interface:**
```bash
python app.py
```
Then 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

1. Start the Flask server: `python app.py`
2. Open `http://localhost:5000` in your browser
3. Start chatting with the AI assistant
4. Use the Settings button to configure:
- Model selection (GPT-3.5 Turbo, GPT-4, etc.)
- Temperature (controls randomness)
- Max tokens (response length)

## Project Structure

```
openai-gpt-chatbot/
├── chatbot.py # Main chatbot class and CLI
├── app.py # Flask web application
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── .env.example # Environment variables example
├── README.md # This file
├── templates/
│ └── index.html # Web interface HTML
└── static/
├── style.css # Stylesheet
└── script.js # Frontend JavaScript
```

## Code Examples

### Basic Usage

```python
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

```python
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
)
```

## Configuration

Edit `config.py` to customize:
- Default model
- Temperature settings
- Max tokens
- System prompts
- Conversation settings

## API Endpoints (Web Interface)

### Basic Endpoints
- `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
- `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

## Advanced Features

### Streaming Responses

Enable real-time streaming for faster perceived response times:

```python
# In web interface, toggle "Stream Response" checkbox
# Or in code:
for chunk in chatbot.get_streaming_response("Hello", callback=print):
# Process each chunk
pass
```

### Token Usage Tracking

Monitor your API usage:

```python
stats = chatbot.get_conversation_stats()
print(f"Total tokens: {stats['token_usage']['total_tokens']}")
print(f"Total requests: {stats['total_requests']}")
```

### Export Conversations

Export your conversations in multiple formats:

```python
# Export as JSON
chatbot.save_conversation("chat.json")

# Export as TXT
chatbot.export_conversation_txt("chat.txt")
```

### Search Conversations

Search through conversation history:

```python
results = chatbot.search_conversation("python")
for msg in results:
print(f"{msg['role']}: {msg['content']}")
```

### Custom Personas

Use pre-built personas or create your own:

```python
from personas import get_persona

persona = get_persona("coding")
chatbot.set_system_prompt(persona['system_prompt'])
```

Available personas:
- `default` - General assistant
- `coding` - Programming expert
- `creative` - Creative writer
- `teacher` - Educational tutor
- `business` - Business advisor
- `friendly` - Casual chat
- `technical` - Technical expert
- `translator` - Translation assistant

## Customization

### Change System Prompt

```python
chatbot.set_system_prompt("You are a coding assistant specialized in Python.")
```

### Adjust Response Parameters

```python
response = chatbot.get_response(
user_message,
temperature=0.9, # More creative (0.0-2.0)
max_tokens=1000 # Longer responses
)
```

### Save and Load Conversations

```python
# Save conversation
chatbot.save_conversation("my_chat.json")

# Load conversation
chatbot.load_conversation("my_chat.json")
```

## 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](https://platform.openai.com)

### 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

## 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.

## Credits

**Created by RSK World**
Visit [https://rskworld.in](https://rskworld.in) for more free programming resources and source code.

---

## Documentation

For complete documentation including:
- Quick start guide
- Advanced features
- API reference
- Code examples
- Troubleshooting
- And more...

**See [DOCUMENTATION.md](DOCUMENTATION.md)**

---

© 2026 RSK World | All Rights Reserved

🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer