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.
- 🎯 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
- Node.js (v14 or higher)
- Google AI Studio API Key (Get one here)
-
Clone or download this repository
git clone <your-repo-url> cd ai-chatbot-template
-
Install dependencies
npm install
-
Set up environment variables
cp .env.example .env # Edit .env and add your GEMINI_API_KEY -
Start the server
npm start # or for development npm run dev -
Open your browser
http://localhost:3000
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| 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 |
GET /- Web chat interface
POST /ask- Send message to AI{ "prompt": "Hello, how are you?" }
GET /history- Get conversation historyDELETE /history- Clear conversation history
GET /status- Get server configuration and status
SYSTEM_PROMPT=You are a creative writing assistant. Help users brainstorm ideas, improve their writing, and provide constructive feedback.
TEMPERATURE=1.5SYSTEM_PROMPT=You are a technical support assistant. Provide clear, step-by-step solutions to technical problems.
TEMPERATURE=0.3SYSTEM_PROMPT=You are a friendly conversational AI. Keep responses casual and engaging.
TEMPERATURE=1.2├── 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
initializeAIClient()- Sets up the Gemini AI clientgetAIResponse(prompt, history)- Gets AI response with historyloadHistoryFromFile()- Loads conversation historysaveHistoryToFile(history)- Saves conversation historystartServer()- Initializes and starts the server
npm start # Start production server
npm run dev # Start with nodemon (auto-reload)const { getAIResponse, initializeAIClient } = require('./server.js');
// Initialize the AI client
initializeAIClient();
// Get a response
const { response, history } = await getAIResponse('Hello!', []);
console.log(response);// 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);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
- 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
- Conversation History: Automatically saved to
conversation.json - History Limits: Configurable max conversation pairs
- Auto-cleanup: Old conversations automatically removed
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is open source. Feel free to use, modify, and distribute as needed.
-
"API key not valid"
- Check your
.envfile has the correctGEMINI_API_KEY - Ensure your API key is active in Google AI Studio
- Check your
-
"Server won't start"
- Check if port is already in use
- Verify all dependencies are installed:
npm install
-
"No response from AI"
- Check your API quota in Google AI Studio
- Verify network connectivity
- Check server logs for detailed error messages
-
"History not saving"
- Ensure write permissions in project directory
- Check disk space
- Verify
conversation.jsonis not read-only
Set environment variable for detailed logging:
DEBUG=1 npm startMin Jun Kim
- Email: koexmin@gmail.com
- GitHub: @codeminjun
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!