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
anthropic-claude-chatbot
RSK World
anthropic-claude-chatbot
Anthropic Claude Chatbot - Python + Flask + Claude API + JavaScript + AI Chatbot + Conversational AI
anthropic-claude-chatbot
  • __pycache__
  • .env578 B
  • .gitignore669 B
  • ADVANCED_FEATURES.md6.6 KB
  • CHECKLIST.md3 KB
  • GITHUB_RELEASE_GUIDE.md4.6 KB
  • LICENSE1.3 KB
  • PROJECT_INFO.md2.2 KB
  • QUICK_START.md2.8 KB
  • README.md8.5 KB
  • RELEASE_NOTES.md6.6 KB
  • SETUP_ENV.md1.9 KB
  • TROUBLESHOOTING.md5.1 KB
  • advanced-features.js24.9 KB
  • app.py9.7 KB
  • config.py2.4 KB
  • env.example550 B
  • index.html11.4 KB
  • requirements.txt440 B
  • run.bat782 B
  • run.sh713 B
  • script.js21.2 KB
  • setup.py2.5 KB
  • start-frontend.bat683 B
  • start.bat1.6 KB
  • styles.css20.2 KB
PROJECT_INFO.mdREADME.mdADVANCED_FEATURES.md.gitignoreapp.py
PROJECT_INFO.md
Raw Download

PROJECT_INFO.md

# Project Information

## Anthropic Claude Chatbot

### Project Details
- **ID:** 7
- **Title:** Anthropic Claude Chatbot
- **Category:** OpenAI Integration
- **Difficulty:** Intermediate
- **Year:** 2026

### Description
Chatbot integration with Anthropic Claude API for advanced conversational AI.

### Full Description
This project integrates Anthropic Claude API to create intelligent chatbots with advanced reasoning capabilities. Features include long context handling, complex reasoning, and safe AI interactions.

### Technologies
- Anthropic API
- Python
- Claude
- JavaScript

### Features
- Claude API integration
- Long context support
- Advanced reasoning
- Safe AI interactions
- Multi-modal support

### Developer Information
- **Website:** https://rskworld.in
- **Email:** help@rskworld.in, support@rskworld.in
- **Phone:** +91 93305 39277
- **Organization:** RSK World
- **Founder:** Molla Samser
- **Designer & Tester:** Rima Khatun

### Project Structure
```
anthropic-claude-chatbot/
├── index.html # Main HTML interface
├── styles.css # CSS styling
├── script.js # Frontend JavaScript
├── app.py # Flask backend server
├── config.py # Configuration file
├── setup.py # Setup helper script
├── requirements.txt # Python dependencies
├── env.example # Environment variables template
├── .gitignore # Git ignore rules
├── README.md # Project documentation
├── LICENSE # MIT License
├── run.bat # Windows start script
├── run.sh # Linux/Mac start script
└── PROJECT_INFO.md # This file
```

### Quick Start
1. Install Python dependencies: `pip install -r requirements.txt`
2. Copy `env.example` to `.env` and add your Anthropic API key
3. Run the server: `python app.py` (or use `run.bat` / `run.sh`)
4. Open `index.html` in your browser

### API Endpoints
- `GET /api/health` - Health check
- `POST /api/chat` - Chat endpoint
- `GET /api/models` - List available models

---

© 2026 RSK World. All rights reserved.

README.md
Raw Download

README.md

# Anthropic Claude Chatbot

**Project:** Anthropic Claude Chatbot
**Category:** OpenAI Integration
**Year:** 2026
**Difficulty:** Intermediate

## Overview

This project integrates Anthropic Claude API to create intelligent chatbots with advanced reasoning capabilities. Features include long context handling, complex reasoning, and safe AI interactions.

### Developer Details
- **Website:** [https://rskworld.in](https://rskworld.in)
- **Email:** help@rskworld.in, support@rskworld.in
- **Phone:** +91 93305 39277
- **Organization:** RSK World
- **Founder:** Molla Samser
- **Designer & Tester:** Rima Khatun

## Features

### Core Features
- ✅ **Claude API Integration** - Seamless integration with Anthropic's Claude API
- ✅ **Long Context Support** - Handle extended conversations and context
- ✅ **Advanced Reasoning** - Leverage Claude's powerful reasoning capabilities
- ✅ **Safe AI Interactions** - Built-in safety features and content filtering
- ✅ **Multi-modal Support** - Support for text, images, and documents
- ✅ **Modern UI** - Beautiful and responsive user interface
- ✅ **Real-time Chat** - Smooth conversation experience
- ✅ **Customizable Settings** - Adjust model, temperature, and tokens

### Advanced & Unique Features
- 🎤 **Voice Input/Output** - Speech recognition and text-to-speech capabilities
- 📎 **File Upload & Analysis** - Upload images and documents for Claude to analyze
- 🌙 **Dark Mode** - Eye-friendly dark theme toggle
- 💾 **Export Chat History** - Export conversations as PDF or TXT files
- 💬 **Multiple Chat Sessions** - Create and manage multiple conversation threads
- 🎨 **Code Syntax Highlighting** - Beautiful code rendering with syntax highlighting
- 📝 **Markdown Rendering** - Rich text formatting support
- ⚡ **Streaming Responses** - Real-time token streaming for faster response display
- 📋 **Copy Messages** - One-click copy for any message
- 👍 **Message Reactions** - Like/unlike assistant responses
- 📊 **API Usage Tracking** - Monitor token usage and API statistics
- 🎯 **Quick Templates** - Pre-built conversation templates for common tasks
- 🔍 **Chat Search** - Search through conversation history
- ⚙️ **Settings Export/Import** - Save and restore your preferences
- 🗣️ **Multi-language Voice Support** - Support for multiple languages in voice features

## Technologies Used

- **Anthropic API** - For Claude AI integration
- **Python** - Backend server (Flask)
- **JavaScript** - Frontend interactivity
- **HTML/CSS** - User interface
- **Claude** - Advanced AI model

## Project Structure

```
anthropic-claude-chatbot/
├── index.html # Main HTML file
├── styles.css # CSS styles
├── script.js # Frontend JavaScript
├── app.py # Flask backend server
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── .gitignore # Git ignore file
└── README.md # Project documentation
```

## Installation

### Prerequisites

- Python 3.8 or higher
- Node.js (optional, for any frontend tooling)
- Anthropic API key ([Get one here](https://console.anthropic.com/))

### Setup Steps

1. **Clone or download the project**

2. **Create a virtual environment (recommended)**
```bash
python -m venv venv

# On Windows
venv\Scripts\activate

# On macOS/Linux
source venv/bin/activate
```

3. **Install Python dependencies**
```bash
pip install -r requirements.txt
```

4. **Set up environment variables**
```bash
# Copy the example file
cp .env.example .env

# Edit .env and add your Anthropic API key
ANTHROPIC_API_KEY=your_actual_api_key_here
```

5. **Start the Flask server**
```bash
python app.py
```

6. **Open the application**
- Open `index.html` in your web browser, or
- Use a local server (e.g., `python -m http.server 8000`) and navigate to `http://localhost:8000`

## Usage

1. **Configure API Key**: Make sure your `.env` file contains a valid Anthropic API key.

2. **Start Backend**: Run `python app.py` to start the Flask server on port 5000.

3. **Open Frontend**: Open `index.html` in your browser or serve it through a local server.

4. **Start Chatting**: Type your message and press Enter or click the send button.

5. **Use Advanced Features**:
- **Voice Input**: Click the microphone icon to speak your message
- **Voice Output**: Click the speaker icon to have Claude's response read aloud
- **File Upload**: Click the paperclip icon to attach images or documents
- **Dark Mode**: Toggle dark theme from the header
- **Multiple Sessions**: Click the chat icon to manage multiple conversations
- **Export Chat**: Download your conversation history as PDF or TXT
- **Quick Templates**: Click the lightbulb icon for pre-built prompts
- **Search**: Use the search box to find specific messages

6. **Adjust Settings**: Click the settings icon to customize:
- Model selection (Claude 3.5 Sonnet, Opus, Sonnet, or Haiku)
- Max tokens (1-4096)
- Temperature (0-1)
- Stream response option
- Auto voice output
- Voice language selection
- Export/Import settings

## API Endpoints

### `GET /api/health`
Health check endpoint to verify API status.

**Response:**
```json
{
"status": "healthy",
"anthropic_configured": true
}
```

### `POST /api/chat`
Main chat endpoint for conversing with Claude.

**Request Body:**
```json
{
"message": "Hello, Claude!",
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"temperature": 0.7,
"conversation_history": [],
"stream": false
}
```

**Response:**
```json
{
"response": "Hello! How can I help you today?",
"model": "claude-3-5-sonnet-20241022",
"usage": {
"input_tokens": 10,
"output_tokens": 8
}
}
```

### `GET /api/models`
Get list of available Claude models.

## Configuration

### Environment Variables

- `ANTHROPIC_API_KEY` - Your Anthropic API key (required)
- `FLASK_ENV` - Flask environment (development/production)
- `PORT` - Server port (default: 5000)

### Frontend Configuration

Edit `script.js` to change the API base URL:
```javascript
const API_BASE_URL = 'http://localhost:5000/api';
```

## Available Models

- **Claude 3.5 Sonnet** - Latest and most capable model (recommended)
- **Claude 3 Opus** - Most powerful for complex tasks
- **Claude 3 Sonnet** - Balanced performance and speed
- **Claude 3 Haiku** - Fastest and most cost-effective

## Features in Detail

### Long Context Support
Claude can handle conversations with up to 200K tokens of context, making it perfect for extended discussions and document analysis.

### Advanced Reasoning
Claude excels at complex reasoning tasks, coding, mathematics, and multi-step problem solving.

### Safe AI Interactions
Anthropic's safety measures ensure responsible AI usage with built-in content filtering and safety protocols.

## Troubleshooting

### API Key Issues
- Ensure your `.env` file contains a valid `ANTHROPIC_API_KEY`
- Check that the API key is correctly formatted (starts with `sk-ant-`)
- Verify your API key has sufficient credits

### CORS Issues
- Make sure Flask-CORS is installed: `pip install flask-cors`
- Check that the frontend and backend URLs are correct

### Connection Errors
- Verify the Flask server is running on port 5000
- Check firewall settings
- Ensure no other application is using port 5000

## Security Notes

- Never commit your `.env` file to version control
- Keep your API key secure and private
- Use environment variables for sensitive data
- Consider implementing rate limiting for production use

## Contributing

This project is part of RSK World's free programming resources. For contributions or issues, please contact:

- **Email:** help@rskworld.in
- **Website:** [https://rskworld.in](https://rskworld.in)

## License

This project is provided as-is for educational purposes. Please refer to Anthropic's API terms of service for usage guidelines.

## Acknowledgments

- **Anthropic** - For providing the Claude API
- **RSK World** - Project organization and development
- **Molla Samser** - Project founder
- **Rima Khatun** - Designer & Tester

## Support

For support, visit [https://rskworld.in/contact.php](https://rskworld.in/contact.php) or email help@rskworld.in

---

**© 2026 RSK World. All rights reserved.**

ADVANCED_FEATURES.md
Raw Download

ADVANCED_FEATURES.md

# Advanced Features Documentation

## Overview
This document describes all the advanced and unique features added to the Anthropic Claude Chatbot project.

**Developer Details:**
- Website: https://rskworld.in
- Email: help@rskworld.in, support@rskworld.in
- Phone: +91 93305 39277
- Organization: RSK World
- Founder: Molla Samser
- Designer & Tester: Rima Khatun

---

## 🎤 Voice Input/Output

### Voice Input
- **Feature**: Speech-to-text input using browser's Web Speech API
- **Usage**: Click the microphone icon in the input toolbar
- **Supported Browsers**: Chrome, Edge, Safari
- **Languages**: Multiple language support (configurable in settings)

### Voice Output
- **Feature**: Text-to-speech for Claude's responses
- **Usage**: Click the speaker icon to read the last assistant message
- **Auto Mode**: Enable "Auto Voice Output" in settings for automatic reading
- **Customization**: Adjustable language, rate, pitch, and volume

---

## 📎 File Upload & Analysis

### Supported File Types
- **Images**: PNG, JPG, JPEG, GIF, WebP
- **Documents**: PDF, TXT, DOC, DOCX (up to 10MB)

### Features
- Drag-and-drop or click to upload
- File preview before sending
- Base64 encoding for API transmission
- Image analysis by Claude's vision capabilities

### Usage
1. Click the paperclip icon
2. Select a file
3. File preview will appear
4. Send message with file attached

---

## 🌙 Dark Mode

### Features
- Toggle between light and dark themes
- Persistent theme preference (saved in localStorage)
- Smooth transitions
- All UI elements styled for both themes

### Usage
Click the moon/sun icon in the header to toggle dark mode

---

## 💾 Export Chat History

### Export Formats

#### TXT Export
- Plain text format
- Includes timestamps
- Easy to read and share
- Small file size

#### PDF Export
- Professional formatted document
- Includes timestamps and user/assistant labels
- Multi-page support for long conversations
- Uses jsPDF library

### Usage
Click the download icon in the header, then choose format (1 for TXT, 2 for PDF)

---

## 💬 Multiple Chat Sessions

### Features
- Create unlimited chat sessions
- Switch between sessions seamlessly
- Each session maintains its own conversation history
- Delete sessions individually
- Session counter in header

### Usage
1. Click the chat icon in header to open sessions sidebar
2. Click "New Session" to create a new chat
3. Click on any session to switch
4. Click trash icon to delete a session

### Storage
Sessions are stored in browser's localStorage

---

## 🎨 Code Syntax Highlighting

### Features
- Automatic code block detection
- Syntax highlighting for 100+ programming languages
- Uses Highlight.js library
- Dark/light theme compatible
- Copy code blocks easily

### Supported Languages
- JavaScript, Python, Java, C++, C#, PHP, Ruby, Go, Rust, and many more

---

## 📝 Markdown Rendering

### Features
- Full Markdown support (GitHub Flavored Markdown)
- Headings, lists, links, images
- Code blocks with syntax highlighting
- Blockquotes, tables, strikethrough
- Automatic formatting

### Supported Elements
- Headers (H1-H6)
- Bold, italic, strikethrough
- Lists (ordered and unordered)
- Links and images
- Code blocks (inline and fenced)
- Blockquotes
- Tables
- Horizontal rules

---

## ⚡ Streaming Responses

### Features
- Real-time token streaming from API
- Faster perceived response time
- Visual streaming indicator
- Progressive message display
- Toggle in settings

### Usage
Enable "Stream Response" checkbox in settings

### Benefits
- See responses as they're generated
- Better user experience
- Reduced waiting time

---

## 📋 Copy Messages

### Features
- One-click copy for any message
- Visual feedback (checkmark appears)
- Copy button appears on hover
- Works for both user and assistant messages

---

## 👍 Message Reactions

### Features
- Like/unlike assistant responses
- Visual feedback
- Helps improve experience
- Feedback can be used for analytics

---

## 📊 API Usage Tracking

### Features
- Real-time token counting
- Input and output token tracking
- Display in header
- Hover for detailed breakdown
- Persistent across sessions

### Display
Shows total tokens used in the current session in the header

---

## 🎯 Quick Templates

### Pre-built Templates
1. **Code Review** - Request code review and suggestions
2. **Explain Concept** - Get simple explanations
3. **Debug Help** - Debug assistance
4. **Write Code** - Request code generation
5. **Summarize** - Summarize content
6. **Translate** - Translation requests
7. **Creative Writing** - Creative writing help
8. **Learn** - Educational explanations

### Usage
1. Click the lightbulb icon in input toolbar
2. Select a template
3. Template text is inserted into input
4. Customize and send

---

## 🔍 Chat Search

### Features
- Real-time search through conversation
- Highlights matching messages
- Auto-scroll to first match
- Case-insensitive search
- Search across all messages

### Usage
Type in the search box in the input footer

---

## ⚙️ Settings Export/Import

### Export Settings
- Save all preferences to JSON file
- Includes model, tokens, temperature, etc.
- Easy backup and restore

### Import Settings
- Load settings from JSON file
- Restore previous configuration
- Validate file format

### Settings Included
- Model selection
- Max tokens
- Temperature
- Stream response preference
- Auto voice output
- Voice language

---

## 🗣️ Multi-language Voice Support

### Supported Languages
- English (US & UK)
- Spanish
- French
- German
- More languages available via browser API

### Configuration
Select language in Settings > Voice Language

---

## Technical Implementation

### Libraries Used
- **Marked.js** - Markdown parsing
- **Highlight.js** - Code syntax highlighting
- **jsPDF** - PDF generation
- **Web Speech API** - Voice input/output
- **Anthropic API** - AI backend

### Browser Compatibility
- Chrome/Edge: Full support (including voice)
- Firefox: Most features (limited voice support)
- Safari: Full support
- Mobile browsers: Responsive design

### Performance
- Optimized for speed
- Lazy loading where applicable
- Efficient DOM updates
- Minimal dependencies

---

## Future Enhancements

Potential features for future versions:
- Conversation sharing via URL
- Cloud sync for sessions
- Custom voice model selection
- Advanced file type support
- Integration with external tools
- Plugin system

---

© 2026 RSK World. All rights reserved.

.gitignore
Raw Download
Find: Go to:
# Anthropic Claude Chatbot - Git Ignore
# Project: Anthropic Claude Chatbot
# Year: 2026
#
# Developer Details:
# - Website: https://rskworld.in
# - Email: help@rskworld.in, support@rskworld.in
# - Phone: +91 93305 39277
# - Organization: RSK World

# Environment variables
.env
.env.local
.env.*.local

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
ENV/
env/
.venv

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Logs
*.log
logs/
58 lines•669 B
text
app.py
Raw Download
Find: Go to:
"""
Anthropic Claude Chatbot - Flask Backend
Project: Anthropic Claude Chatbot
Category: OpenAI Integration
Year: 2026

Developer Details:
- Website: https://rskworld.in
- Email: help@rskworld.in, support@rskworld.in
- Phone: +91 93305 39277
- Organization: RSK World
- Founder: Molla Samser
- Designer & Tester: Rima Khatun
"""

from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
from anthropic import Anthropic
import os
from dotenv import load_dotenv
import logging
import base64
import json

# Load environment variables
load_dotenv()

# Initialize Flask app
app = Flask(__name__)
CORS(app)  # Enable CORS for frontend

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize Anthropic client
anthropic_client = None
try:
    api_key = os.getenv('ANTHROPIC_API_KEY')
    if api_key:
        anthropic_client = Anthropic(api_key=api_key)
        logger.info("Anthropic client initialized successfully")
    else:
        logger.warning("ANTHROPIC_API_KEY not found in environment variables")
except Exception as e:
    logger.error(f"Error initializing Anthropic client: {e}")


@app.route('/api/health', methods=['GET'])
def health_check():
    """
    Health check endpoint to verify API status
    """
    return jsonify({
        'status': 'healthy',
        'anthropic_configured': anthropic_client is not None
    }), 200


@app.route('/api/chat', methods=['POST'])
def chat():
    """
    Main chat endpoint that handles conversations with Claude
    """
    try:
        if not anthropic_client:
            return jsonify({
                'error': 'Anthropic API key not configured. Please set ANTHROPIC_API_KEY in your .env file.'
            }), 500

        # Get request data
        data = request.get_json()
        message = data.get('message', '')
        model = data.get('model', 'claude-3-5-sonnet-20241022')
        max_tokens = data.get('max_tokens', 1024)
        temperature = data.get('temperature', 0.7)
        conversation_history = data.get('conversation_history', [])
        stream = data.get('stream', False)

        # Validate input
        if not message and not data.get('file_data'):
            return jsonify({'error': 'Message or file is required'}), 400

        # Prepare messages for Claude API
        messages = []
        
        # Add conversation history
        for msg in conversation_history:
            msg_content = msg.get('content', '')
            # Handle both string and list content formats
            if isinstance(msg_content, list):
                messages.append({
                    'role': msg.get('role', 'user'),
                    'content': msg_content
                })
            else:
                messages.append({
                    'role': msg.get('role', 'user'),
                    'content': msg_content
                })
        
        # Prepare current message content
        current_content = []
        if message:
            current_content.append({
                'type': 'text',
                'text': message
            })
        
        # Handle file uploads (images)
        file_data = data.get('file_data')
        if file_data:
            try:
                # file_data should be base64 encoded
                file_type = data.get('file_type', 'image/png')
                current_content.append({
                    'type': 'image',
                    'source': {
                        'type': 'base64',
                        'media_type': file_type,
                        'data': file_data
                    }
                })
            except Exception as e:
                logger.error(f"Error processing file: {e}")
                return jsonify({'error': f'Error processing file: {str(e)}'}), 400
        
        # Add current message
        if len(current_content) > 1 or file_data:
            messages.append({
                'role': 'user',
                'content': current_content
            })
        elif current_content and len(current_content) > 0:
            messages.append({
                'role': 'user',
                'content': current_content[0]['text']
            })
        else:
            messages.append({
                'role': 'user',
                'content': message
            })

        # Create message with Claude API
        try:
            # Handle streaming
            if stream:
                def generate():
                    try:
                        with anthropic_client.messages.stream(
                            model=model,
                            max_tokens=max_tokens,
                            temperature=temperature,
                            messages=messages,
                            system="You are a helpful, harmless, and honest AI assistant. Provide clear and accurate responses."
                        ) as stream_obj:
                            for text_block in stream_obj.text_stream:
                                yield f"data: {json.dumps({'response': text_block})}\n\n"
                            # Get final usage stats
                            try:
                                final_message = stream_obj.get_final_message()
                                usage = {
                                    'input_tokens': final_message.usage.input_tokens,
                                    'output_tokens': final_message.usage.output_tokens
                                }
                                yield f"data: {json.dumps({'usage': usage, 'done': True})}\n\n"
                            except:
                                pass
                        yield "data: [DONE]\n\n"
                    except Exception as e:
                        yield f"data: {json.dumps({'error': str(e)})}\n\n"
                
                return Response(
                    stream_with_context(generate()),
                    mimetype='text/event-stream',
                    headers={
                        'Cache-Control': 'no-cache',
                        'Connection': 'keep-alive',
                        'X-Accel-Buffering': 'no',
                        'Access-Control-Allow-Origin': '*'
                    }
                )
            
            # Non-streaming response
            response = anthropic_client.messages.create(
                model=model,
                max_tokens=max_tokens,
                temperature=temperature,
                messages=messages,
                system="You are a helpful, harmless, and honest AI assistant. Provide clear and accurate responses."
            )

            # Extract response text
            response_text = ""
            if response.content:
                for block in response.content:
                    if hasattr(block, 'text'):
                        response_text += block.text

            logger.info(f"Successfully processed chat request with model {model}")

            return jsonify({
                'response': response_text,
                'model': model,
                'usage': {
                    'input_tokens': response.usage.input_tokens,
                    'output_tokens': response.usage.output_tokens
                }
            }), 200

        except Exception as api_error:
            logger.error(f"Anthropic API error: {api_error}")
            return jsonify({
                'error': f'Anthropic API error: {str(api_error)}'
            }), 500

    except Exception as e:
        logger.error(f"Error in chat endpoint: {e}")
        return jsonify({
            'error': f'Internal server error: {str(e)}'
        }), 500


@app.route('/api/models', methods=['GET'])
def get_models():
    """
    Get available Claude models
    """
    models = [
        {
            'id': 'claude-3-5-sonnet-20241022',
            'name': 'Claude 3.5 Sonnet',
            'description': 'Latest and most capable model with advanced reasoning'
        },
        {
            'id': 'claude-3-opus-20240229',
            'name': 'Claude 3 Opus',
            'description': 'Most powerful model for complex tasks'
        },
        {
            'id': 'claude-3-sonnet-20240229',
            'name': 'Claude 3 Sonnet',
            'description': 'Balanced performance and speed'
        },
        {
            'id': 'claude-3-haiku-20240307',
            'name': 'Claude 3 Haiku',
            'description': 'Fastest and most cost-effective model'
        }
    ]
    return jsonify({'models': models}), 200


if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))
    debug = os.getenv('FLASK_ENV') == 'development'
    
    logger.info("=" * 50)
    logger.info("Anthropic Claude Chatbot Server")
    logger.info("=" * 50)
    logger.info(f"Starting server on http://0.0.0.0:{port}")
    logger.info(f"API Health Check: http://localhost:{port}/api/health")
    logger.info(f"Debug mode: {debug}")
    logger.info("=" * 50)
    
    if not anthropic_client:
        logger.warning("⚠️  WARNING: ANTHROPIC_API_KEY not configured!")
        logger.warning("   Please set ANTHROPIC_API_KEY in .env file")
    else:
        logger.info("✅ Anthropic API client initialized successfully")
    
    try:
        app.run(host='0.0.0.0', port=port, debug=debug)
    except OSError as e:
        if "Address already in use" in str(e):
            logger.error(f"❌ Port {port} is already in use!")
            logger.error(f"   Please use a different port or stop the other application")
        else:
            logger.error(f"❌ Error starting server: {e}")

282 lines•9.7 KB
python
🚀 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