Skip to content

Latest commit

 

History

History
268 lines (200 loc) · 7.16 KB

File metadata and controls

268 lines (200 loc) · 7.16 KB

🤖 AI Chatbot Template

A modular, reusable chatbot template built with Express.js and Google's Gemini AI. Perfect for quickly spinning up AI-powered applications with conversation history, web interface, and comprehensive configuration options.

✨ Features

  • 🎯 Modular Architecture - Clean, organized functions for easy customization
  • ⚙️ Configuration-Driven - Environment variables for all settings
  • 💾 Conversation History - Persistent chat history with automatic management
  • 🛡️ Error Handling - Comprehensive error handling with user-friendly messages
  • 🌐 Web Interface - Clean, responsive chat interface
  • 📊 API Endpoints - RESTful API for integration with other applications
  • 🔒 Security - Basic security headers and input validation
  • 📖 Documentation - Extensive comments and documentation

🚀 Quick Start

Prerequisites

  • Node.js (v14 or higher)
  • Google AI Studio API Key (Get one here)

Installation

  1. Clone or download this repository

    git clone <your-repo-url>
    cd ai-chatbot-template
  2. Install dependencies

    npm install
  3. Set up environment variables

    cp .env.example .env
    # Edit .env and add your GEMINI_API_KEY
  4. Start the server

    npm start
    # or for development
    npm run dev
  5. Open your browser

    http://localhost:3000
    

⚙️ Configuration

Environment Variables

Create a .env file based on .env.example:

# Required
GEMINI_API_KEY=your_api_key_here

# Optional
PORT=3000
GEMINI_MODEL=gemini-1.5-flash
SYSTEM_PROMPT=You are a helpful AI assistant.
TEMPERATURE=1.0
TOP_P=0.95
TOP_K=64
MAX_OUTPUT_TOKENS=8192
MAX_HISTORY_LENGTH=10

Configuration Options

Variable Description Default Options
GEMINI_API_KEY Required - Your Google AI API key - -
PORT Server port 3000 Any valid port
GEMINI_MODEL Gemini model to use gemini-1.5-flash gemini-1.5-flash, gemini-1.5-pro, gemini-1.0-pro
SYSTEM_PROMPT AI personality/behavior Default helpful assistant Any text
TEMPERATURE Response randomness 1.0 0.0 - 2.0
TOP_P Nucleus sampling 0.95 0.0 - 1.0
TOP_K Token selection limit 64 Integer
MAX_OUTPUT_TOKENS Max response length 8192 Integer
MAX_HISTORY_LENGTH Conversation pairs to keep 10 Integer

📡 API Endpoints

Main Interface

  • GET / - Web chat interface

Chat API

  • POST /ask - Send message to AI
    {
      "prompt": "Hello, how are you?"
    }

History Management

  • GET /history - Get conversation history
  • DELETE /history - Clear conversation history

Server Status

  • GET /status - Get server configuration and status

🎨 Customization Examples

Creative Writing Assistant

SYSTEM_PROMPT=You are a creative writing assistant. Help users brainstorm ideas, improve their writing, and provide constructive feedback.
TEMPERATURE=1.5

Technical Support Bot

SYSTEM_PROMPT=You are a technical support assistant. Provide clear, step-by-step solutions to technical problems.
TEMPERATURE=0.3

Casual Conversation Bot

SYSTEM_PROMPT=You are a friendly conversational AI. Keep responses casual and engaging.
TEMPERATURE=1.2

🔧 Development

Project Structure

├── server.js              # Main server file (modular architecture)
├── package.json           # Dependencies and scripts
├── .env.example           # Configuration template
├── conversation.json      # Chat history (auto-generated)
└── public/
    ├── index.html         # Web interface
    ├── style.css          # Styles
    └── script.js          # Frontend JavaScript

Key Functions

  • initializeAIClient() - Sets up the Gemini AI client
  • getAIResponse(prompt, history) - Gets AI response with history
  • loadHistoryFromFile() - Loads conversation history
  • saveHistoryToFile(history) - Saves conversation history
  • startServer() - Initializes and starts the server

Scripts

npm start        # Start production server
npm run dev      # Start with nodemon (auto-reload)

🔌 Integration

Use as a Module

const { getAIResponse, initializeAIClient } = require('./server.js');

// Initialize the AI client
initializeAIClient();

// Get a response
const { response, history } = await getAIResponse('Hello!', []);
console.log(response);

API Integration

// Send a message via API
const response = await fetch('http://localhost:3000/ask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt: 'Hello!' })
});
const data = await response.json();
console.log(data.answer);

🛡️ Error Handling

The template includes comprehensive error handling:

  • API Key Issues - Clear messages for invalid or missing keys
  • Quota Limits - Graceful handling of API quotas
  • Network Issues - Retry suggestions for connectivity problems
  • Input Validation - Proper validation of user inputs
  • Server Errors - Detailed logging with user-friendly responses

🚨 Security Considerations

  • Environment variables for sensitive data
  • Input validation and sanitization
  • Security headers (XSS, CSRF protection)
  • No secrets in code or version control
  • Graceful error handling without exposing internals

📁 File Management

  • Conversation History: Automatically saved to conversation.json
  • History Limits: Configurable max conversation pairs
  • Auto-cleanup: Old conversations automatically removed

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

📄 License

This project is open source. Feel free to use, modify, and distribute as needed.

🔗 Links

🆘 Troubleshooting

Common Issues

  1. "API key not valid"

    • Check your .env file has the correct GEMINI_API_KEY
    • Ensure your API key is active in Google AI Studio
  2. "Server won't start"

    • Check if port is already in use
    • Verify all dependencies are installed: npm install
  3. "No response from AI"

    • Check your API quota in Google AI Studio
    • Verify network connectivity
    • Check server logs for detailed error messages
  4. "History not saving"

    • Ensure write permissions in project directory
    • Check disk space
    • Verify conversation.json is not read-only

Debug Mode

Set environment variable for detailed logging:

DEBUG=1 npm start

👨‍💻 Author

Min Jun Kim


Made with ❤️ for the AI developer community

This template is designed to be your starting point for any chatbot project. Customize it, extend it, and make it your own!