Skip to content

Sanya06C/chatbot

Repository files navigation

Generic Chatbot - Gemini API

A modular, configuration-driven chatbot backend built with Flask and Google Gemini API. Designed for hackathon adaptability with pluggable prompts and data contexts.

🎯 Features

  • Modular Architecture: Separated concerns (config, service, brain, API)
  • Dynamic Prompt Injection: Change system prompts at runtime without redeployment
  • Conversation Memory: Maintains session-based conversation history
  • Flexible Configuration: YAML + Environment variables
  • RESTful API: Clean JSON endpoints for integration
  • Error Handling: Robust handling of API errors and rate limits

πŸ“ Project Structure

chatbot/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py          # Package initializer
β”‚   β”œβ”€β”€ config.py            # Configuration management
β”‚   β”œβ”€β”€ service.py           # Gemini API wrapper
β”‚   β”œβ”€β”€ brain.py             # Conversation & context logic
β”‚   └── main.py              # Flask application
β”œβ”€β”€ config.yaml              # Default prompts & settings
β”œβ”€β”€ .env.example             # Environment variables template
β”œβ”€β”€ requirements.txt         # Python dependencies
β”œβ”€β”€ run.py                   # Application entry point
└── README.md                # This file

πŸš€ Quick Start

1. Prerequisites

2. Installation

# Clone or navigate to project directory
cd chatbot

# Install dependencies
pip install -r requirements.txt

# Copy environment template
copy .env.example .env

# Edit .env and add your API key
notepad .env

3. Configuration

Edit .env file:

GEMINI_API_KEY=your_actual_api_key_here
FLASK_PORT=5000

Edit config.yaml to customize default prompts:

system_prompt: |
  You are a helpful AI assistant...

4. Run the Server

Note: All code is currently commented out. Uncomment the code in all files to run.

# Run the chatbot server
python run.py

Server will start at http://localhost:5000

πŸ“‘ API Endpoints

1. Health Check

GET /health

2. Chat

POST /chat
Content-Type: application/json

{
  "message": "Hello, how are you?",
  "session_id": "user123",
  "include_history": true
}

Response:

{
  "success": true,
  "response": "I'm doing well, thank you!",
  "session_id": "user123",
  "model": "gemini-pro",
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 12
  }
}

3. Update Configuration

POST /config
Content-Type: application/json

{
  "system_prompt": "You are a pirate assistant. Speak like a pirate!",
  "temperature": 0.9
}

4. Clear Session

DELETE /session/user123

5. List Sessions

GET /sessions

πŸ”§ Extending for Hackathons

Adding Custom Data Context

  1. In brain.py, modify build_prompt():
# Add context injection
if session.context_data:
    prompt_parts.append(f"CONTEXT DATA:\n{session.context_data}")
  1. Set context via API:
session.set_context('user_profile', {'name': 'John', 'preferences': 'tech'})

Changing Prompts Dynamically

# During hackathon, update prompt based on problem statement
curl -X POST http://localhost:5000/config \
  -H "Content-Type: application/json" \
  -d '{"system_prompt": "You are a legal advisor assistant..."}'

Supporting Different Data Formats

  1. Add data loader in brain.py:
def load_data_context(self, data_file: str):
    with open(data_file) as f:
        data = json.load(f)
    return data
  1. Use in prompt building

πŸ§ͺ Testing

# Test with curl
curl -X POST http://localhost:5000/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "What can you do?"}'

πŸ›‘οΈ Error Handling

The system handles:

  • Invalid API keys
  • Rate limiting (automatic retry logic can be added)
  • Malformed requests
  • Network errors

πŸ“ Configuration Reference

Environment Variables (.env)

Variable Description Default
GEMINI_API_KEY Google Gemini API key Required
FLASK_PORT Server port 5000
GEMINI_MODEL Model name gemini-pro
TEMPERATURE Model temperature 0.7

YAML Config (config.yaml)

  • system_prompt: Default AI persona and instructions
  • model: Model parameters (temperature, tokens, etc.)
  • conversation: History settings

πŸŽ“ Hackathon Workflow

  1. Setup (5 min): Install, configure API key
  2. Test (5 min): Verify basic chat works
  3. Problem Statement Released:
    • Update system_prompt via /config endpoint
    • Add domain data to context
    • Test with sample queries
  4. Demo: Show API calls and responses

πŸ“¦ Deployment

For production/demo:

pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app.main:app

🀝 Contributing

This is a hackathon template. Feel free to modify any module to fit your use case.

πŸ“„ License

MIT License - Use freely for hackathons and projects.


Built with ❀️ for hackathon speed and flexibility

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages