Skip to content

Ionic-Errrrs-Code/niche_bot

Repository files navigation

Niche Bot Creator

A powerful, scalable AI chatbot creation platform built on Cloudflare's edge network. Create custom AI personalities, train them with your knowledge base, and deploy them anywhere.

πŸš€ Features

  • Personality Customization: Create unique AI personalities with custom names, ages, roles, and tones
  • Knowledge Base Training: Upload text files to train your bot with specific information
  • Vector Search: Uses Cloudflare Vectorize for intelligent, context-aware responses
  • Multi-Model Fallback: 158+ AI models with automatic fallback for maximum reliability
  • Real-time Chat: Interactive chat interface to test and refine your bot
  • Export Ready: Generate embeddable code for your website
  • Persistent Storage: D1 database for bot persistence and session management
  • Session Persistence: KV storage for chat history across browser sessions and embedded widgets
  • Widget Integration: Embeddable chatbot widget with persistent conversations

πŸ—οΈ Architecture

  • Frontend: Modern, responsive UI built with Tailwind CSS
  • Backend: Cloudflare Workers for serverless API endpoints
  • Database: Cloudflare D1 for structured data storage
  • Vector Database: Cloudflare Vectorize for semantic search
  • AI Processing: Cloudflare AI for embeddings and text processing

πŸ“ Project Structure

niche-bot-project/
β”œβ”€β”€ src/
β”‚   └── index.js         # Cloudflare Worker backend logic
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ index.html       # Main HTML interface
β”‚   └── app.js           # Frontend JavaScript logic
β”œβ”€β”€ wrangler.toml        # Cloudflare configuration
β”œβ”€β”€ package.json         # Dependencies and scripts
└── README.md           # This file

πŸ› οΈ Setup & Deployment

Prerequisites

  • Node.js 18+ installed
  • Cloudflare account with Workers enabled
  • Wrangler CLI installed globally

1. Install Dependencies

npm install

2. Install Wrangler CLI

npm install -g wrangler

3. Login to Cloudflare

wrangler login

4. Create D1 Database

wrangler d1 create niche-bot-db

Important: Copy the database_id from the output and update it in wrangler.toml.

5. Create Database Table

wrangler d1 execute niche-bot-db --command="CREATE TABLE bots (id TEXT PRIMARY KEY, personality TEXT, created_at TEXT);"

6. Create Vectorize Index

wrangler vectorize create niche-bot-kb-index --dimensions=384 --metric=cosine

7. Create KV Namespace

wrangler kv namespace create "SESSIONS"

Important: Copy the id from the output and update it in wrangler.toml.

8. Update Configuration

Edit wrangler.toml and replace the placeholder values with your actual:

  • D1 database ID
  • KV namespace ID
wrangler deploy

πŸ”§ Configuration

wrangler.toml

The main configuration file that defines:

  • Worker name and entry point
  • D1 database bindings
  • Vectorize index bindings
  • AI model bindings
  • Static asset serving

Environment Variables

The following services are automatically configured:

  • D1 Database: Stores bot personalities and metadata
  • Vectorize: Handles semantic search and knowledge retrieval
  • AI Models: Provides embedding and text processing capabilities
  • KV Storage: Stores chat sessions and conversation history

πŸ“š API Endpoints

POST /api/create-bot

Creates a new bot session with personality data.

Request Body:

{
  "personality": {
    "name": "Eva",
    "age": 28,
    "hair": "Silver",
    "role": "Knowledgeable historian",
    "tone": "Witty and slightly sarcastic",
    "bio": "An AI who has absorbed the entire library of Alexandria..."
  }
}

Response:

{
  "success": true,
  "botId": "uuid-here"
}

POST /api/train/:botId

Trains a bot with uploaded text files.

Request: Multipart form data with files field containing .txt files.

Response:

{
  "success": true,
  "message": "Knowledge base updated with X document chunks."
}

POST /api/chat/:botId

Handles chat interactions with the trained bot.

Request Body:

{
  "messages": [
    {"role": "user", "content": "Hello, what do you know about ancient Egypt?"}
  ]
}

Response:

{
  "success": true,
  "reply": "Based on my knowledge base, I can tell you that...",
  "modelUsed": "gpt-4"
}

POST /api/session/:botId

Saves chatbot session data including chat history.

Request Body:

{
  "chatHistory": [
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Hi there!"}
  ],
  "personality": {
    "name": "Eva",
    "role": "Assistant"
  }
}

GET /api/session/:botId

Loads chatbot session data.

Response:

{
  "success": true,
  "session": {
    "chatHistory": [...],
    "personality": {...},
    "lastUpdated": "2025-08-29T..."
  }
}

GET /api/widget/:botId

Gets bot data for embedded widgets.

Response:

{
  "success": true,
  "personality": {
    "name": "Eva",
    "role": "Assistant",
    "bio": "..."
  }
}

POST /api/widget-chat/:botId

Handles chat for embedded widgets with session persistence.

Request Body:

{
  "messages": [...],
  "sessionId": "session_123456"
}

GET /api/widget-session/:sessionId

Loads widget session data.

Response:

{
  "success": true,
  "session": {
    "chatHistory": [...],
    "personality": {...}
  }
}

🎯 Usage

Creating a Bot

  1. Fill out the personality form with your desired bot characteristics
  2. Click "Create & Save Personality" to save the bot
  3. The bot is now ready for training and chat

Training Your Bot

  1. Upload .txt files containing knowledge you want your bot to learn
  2. Click "Train with New Files" to process and store the information
  3. The bot will chunk the text and create vector embeddings for semantic search

Chatting with Your Bot

  1. Type messages in the chat interface
  2. The bot will search its knowledge base for relevant context
  3. Responses are generated using the selected AI model with personality consistency

Exporting Your Bot

  1. Click the "Export" button to generate embeddable code
  2. Copy the generated HTML/JavaScript code
  3. Paste it into your website to embed the chatbot
  4. The widget will automatically persist conversations across page visits

Example embed code:

<div data-bot-id="your-bot-id"></div>
<script src="https://your-domain.com/widget.js" defer></script>

Widget Features

  • Persistent Sessions: Chat history is saved and restored automatically
  • Responsive Design: Adapts to different screen sizes
  • Real-time Chat: Instant responses with typing indicators
  • Session Management: Each user gets their own conversation session

πŸ”’ Security & Best Practices

  • All API keys are stored securely in environment variables
  • File uploads are limited to .txt files
  • Vector embeddings are isolated per bot ID
  • Database queries use parameterized statements to prevent injection

πŸš€ Performance

  • Edge Computing: Deployed on Cloudflare's global network for low latency
  • Vector Search: Sub-second response times for knowledge retrieval
  • Model Fallback: Automatic failover ensures high availability
  • Caching: Built-in caching for improved response times

οΏ½οΏ½ Troubleshooting

Common Issues

  1. Database Connection Error: Verify your D1 database ID in wrangler.toml
  2. Vectorize Error: Ensure your Vectorize index is created and accessible
  3. AI Model Failures: Check that your API keys are valid and have sufficient credits

Debug Mode

Run in development mode for detailed logging:

wrangler dev

πŸ“ˆ Scaling

This architecture is designed to scale automatically:

  • Workers: Automatically scales based on demand
  • D1: Handles concurrent database connections efficiently
  • Vectorize: Optimized for high-throughput vector operations
  • AI Models: Multiple fallback options ensure reliability

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

πŸ“„ License

MIT License - see LICENSE file for details

πŸ†˜ Support

For issues and questions:

  • Check the troubleshooting section above
  • Review Cloudflare Workers documentation
  • Open an issue on GitHub

Built with ❀️ on Cloudflare's edge network