Skip to content

kishore00777/Botx

Repository files navigation

πŸ€– Botx

The Open Source, Self-Hosted AI Chatbot Builder.

Build, manage, and embed AI chatbots powered by Google Gemini. No subscription fees, no data lock-in.

⭐ If you find this project useful, please consider giving it a star!

Table of Contents

Dashboard Preview

✨ Features

  • πŸš€ Self-Hosted Foundation: Next.js 16+, MongoDB, and NextAuth. You own the code and the data.
  • 🧠 Gemini AI Powered: Integrated with Google's state-of-the-art Gemini models (2.0 Flash, 1.5 Pro, 1.5 Flash).
  • 🎨 Visual Bot Builder: Customize system prompts, temperature, and themes (colors, welcome messages, icons).
  • πŸ“š Knowledge Base (RAG): Upload PDF & Word documents. Automatic vector indexing with MongoDB Atlas Vector Search.
  • πŸ“ Rich Text Support: Full Markdown support for bold, italics, lists, and code blocks in chat.
  • πŸ“Š Real-Time Analytics: Track bot usage, message count, and performance metrics.
  • πŸ’¬ Multi-Turn Conversations: Full conversation history with LangChain integration.
  • πŸ”Œ Embed Anywhere: One-line <script> tag to add your bot to any website with domain validation.
  • 🌍 Public Share Pages: Standalone, fully-themed chat pages for every bot.
  • πŸ›‘οΈ Advanced Security: Domain whitelisting, IP-based rate limiting, and admin authentication.
  • πŸš€ Serverless Ready: Optimized for Vercel with Mongoose connection pooling.

πŸš€ One-Click Deploy

Step 1: Fork the Repository

First, fork this repository to your GitHub account:

Fork on GitHub

A fork creates your own copy of the repository. You need to do this to deploy to Vercel.

Step 2: Deploy to Vercel

After forking, deploy directly to Vercel with a single click:

Deploy with Vercel

Replace YOUR_GITHUB_USERNAME with your actual GitHub username.

Step 3: Configure Environment Variables

During deployment, Vercel will prompt you to add these environment variables:

Variable Required Description Example
ADMIN_EMAIL βœ… Admin login email admin@example.com
ADMIN_PASSWORD βœ… Admin login password MySecurePass123!
AUTH_SECRET βœ… JWT encryption key (generate: openssl rand -base64 32) abc123...
MONGODB_URI βœ… MongoDB connection string mongodb+srv://user:pass@cluster.mongodb.net/botx
GEMINI_API_KEY βœ… Google Gemini API key AIzaSy...

Getting Your API Keys:

πŸ›  Technical Architecture

Component Technology Version
Framework Next.js (App Router) 16.1.4
Database MongoDB (Mongoose) 8.21.0
Auth NextAuth.js 5.0.0-beta.30
AI/LLM Google Gemini API Latest
Vector Search MongoDB Atlas Vector Search Native
UI Library React 19.2.3
Styling Tailwind CSS 4
AI Framework LangChain 1.2.10

Key Features:

  • Mongoose connection pooling for serverless (Vercel)
  • Automated vector index creation on first bot deployment
  • Enterprise-grade RAG with MongoDB Atlas Vector Search
  • No subscription required for AI models (BYOK - Bring Your Own Key)

πŸ“š API Documentation

Bot Endpoints

# List all bots
GET /api/bots
Authorization: Admin session required

# Create a new bot
POST /api/bots
Body: { name, systemPrompt, temperature, aiModel, theme }

# Get bot details
GET /api/bots/[id]

# Update bot
PUT /api/bots/[id]

# Delete bot
DELETE /api/bots/[id]

Chat Endpoint (Public)

# Send message to bot
POST /api/chat
Body: {
  botId: "publicId or _id",
  message: "User message",
  history: [{ role: "user", content: "..." }]
}
Response: { reply: "Bot response" }

Knowledge Base Endpoints

# Upload document
POST /api/bots/[id]/knowledge
Body: FormData with file

# Delete document
DELETE /api/bots/[id]/knowledge/[docId]

πŸ’» Usage Examples

Embed Bot on Website

Add this single line to your website's HTML:

<script src="https://yourdomain.com/embed.js?botId=YOUR_BOT_PUBLIC_ID"></script>

The bot widget will appear at the bottom-right corner.

Create Bot via API

const response = await fetch("/api/bots", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    name: "Customer Support Bot",
    systemPrompt: "You are a helpful customer support agent.",
    temperature: 0.7,
    aiModel: "gemini-2.0-flash",
    theme: {
      primaryColor: "#8b5cf6",
      chatTitle: "Support Bot",
      welcomeMessage: "Hello! How can I help?",
    },
  }),
});
const { bot } = await response.json();
console.log("Bot created:", bot.publicId);

Send Message to Bot

const response = await fetch("/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    botId: "YOUR_BOT_PUBLIC_ID",
    message: "What are your business hours?",
    history: [],
  }),
});
const { reply } = await response.json();
console.log("Bot says:", reply);

🧩 Project Structure

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/                 # API Routes
β”‚   β”‚   β”œβ”€β”€ bots/           # Bot management endpoints
β”‚   β”‚   β”œβ”€β”€ chat/           # Public chat endpoint
β”‚   β”‚   β”œβ”€β”€ auth/           # Authentication routes
β”‚   β”‚   └── admin/          # Admin utilities
β”‚   β”œβ”€β”€ dashboard/          # Admin Dashboard Pages
β”‚   β”œβ”€β”€ share/              # Public Bot Chat Pages
β”‚   β”œβ”€β”€ login/              # Admin Login
β”‚   └── globals.css         # Global styles
β”œβ”€β”€ models/                 # Mongoose Schemas
β”‚   β”œβ”€β”€ bot.model.ts        # Bot configuration
β”‚   β”œβ”€β”€ knowledge-base.model.ts
β”‚   └── knowledge-chunk.model.ts
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ db.ts              # MongoDB connection with pooling
β”‚   β”œβ”€β”€ gemini.ts          # Gemini API integration
β”‚   β”œβ”€β”€ atlas.ts           # Vector search utilities
β”‚   └── rate-limit.ts      # Rate limiting logic
β”œβ”€β”€ components/            # React components
β”‚   β”œβ”€β”€ message-renderer.tsx
β”‚   └── dashboard/         # Dashboard UI components
β”œβ”€β”€ auth.ts               # NextAuth configuration
└── middleware.ts         # Route protection

public/
β”œβ”€β”€ embed.js             # Widget embedding script
└── favicon.ico

πŸ” Security

βœ… Admin Authentication: Environment-based credentials with JWT sessions βœ… API Keys: Gemini API key stored server-side, never exposed to client βœ… Domain Whitelisting: Control which domains can embed your bot βœ… Rate Limiting: IP-based rate limiting on chat endpoint (prevents abuse) βœ… Bot Status Control: Enable/disable bots without deletion βœ… Serverless Safe: Connection pooling prevents database exhaustion on Vercel

For Production: Use strong passwords, enable MongoDB IP whitelisting, and enable HTTPS.

πŸ› Troubleshooting

"MONGODB_URI is not defined"

  • Ensure .env.local exists in root directory
  • Check the variable name is exactly MONGODB_URI
  • Restart dev server after adding env variables

"GEMINI_API_KEY is not defined"

  • Get a free API key from Google AI Studio
  • Add it to .env.local and restart the server
  • Check you're using Gemini API, not Google Cloud API

Bot chat returns 404

  • Verify bot is marked as isActive: true
  • Check bot publicId or _id matches the request
  • If using domain whitelisting, verify your domain is in the list

Vector search not working

  • Index is created automatically on first bot creation
  • For manual index setup: POST /api/admin/setup-index
  • Verify MongoDB Atlas has vector search enabled (M10+ cluster)

Rate limit errors (429)

  • The API limits requests by IP address
  • Wait a few minutes before retrying
  • Use a reverse proxy or cache in production

License

MIT Β© kishorem


Have questions? Open an issue on GitHub!

About

Resources

License

Stars

Watchers

Forks