A sophisticated AI chatbot application built with Next.js, featuring Koa AI Agent with comprehensive Koasync knowledge, secret training capabilities, and intelligent search through GitBook documentation.
- Intelligent Responses: Powered by OpenAI GPT-4o mini with built-in Koasync knowledge
- Context Awareness: Maintains conversation context and provides relevant answers
- Response Length Control: Automatically provides short/clear responses or detailed information based on user requests
- Jupiter Integration Knowledge: Special handling for planned features with consistent messaging
- Hidden Training Mode: Activate with secret code to teach the bot new information
- AI Analysis: Automatic analysis of training content with intent, sentiment, and topic extraction
- Database Storage: Training data stored in both
training_dataandgitbook_contentcollections - Natural Learning: Bot responds conversationally when learning new information
- Comprehensive Knowledge Base: Full GitBook documentation stored in MongoDB
- Enhanced Search: Deep content search across titles, sections, and training data
- Smart Scoring: Intelligent ranking of search results with keyword matching
- Training Data Integration: User-provided training becomes part of searchable knowledge
- Message Limits: 100 messages per client per day with server-side validation
- Persistent Tracking: Client identification and usage tracking in MongoDB
- Security Monitoring: IP address and user agent tracking
- Beautiful Design: Anime character illustrations with gradient backgrounds
- Responsive Layout: Works seamlessly on desktop and mobile devices
- Smooth Animations: Modern chat interface with loading states
- Training Indicators: Visual feedback for active training sessions
npm installCreate a .env.local file in the root directory:
# Required
NEXT_PUBLIC_OPENAI_API_KEY=your_openai_api_key_here
MONGODB_URI=your_mongodb_connection_string_here
# Secret Training Codes (Optional - will use defaults if not set)
SECRET_TRAINING_CODE=
EXIT_TRAINING_CODE=
# Public versions for frontend (Optional)
NEXT_PUBLIC_SECRET_TRAINING_CODE=
NEXT_PUBLIC_EXIT_TRAINING_CODE=# Start the development server
npm run dev
# In a separate terminal, initialize the database with GitBook content
curl -X POST http://localhost:3000/api/training/gitbook-initnpm run devOpen http://localhost:3000 in your browser.
| Variable | Description | Required | Default |
|---|---|---|---|
NEXT_PUBLIC_OPENAI_API_KEY |
OpenAI API key for GPT-4o mini | Yes | - |
MONGODB_URI |
MongoDB connection string | Yes | - |
SECRET_TRAINING_CODE |
Code to activate training mode | No | `` |
EXIT_TRAINING_CODE |
Code to exit training mode | No | `` |
NEXT_PUBLIC_SECRET_TRAINING_CODE |
Frontend version of secret code | No | Same as SECRET_TRAINING_CODE |
NEXT_PUBLIC_EXIT_TRAINING_CODE |
Frontend version of exit code | No | Same as EXIT_TRAINING_CODE |
- Go to MongoDB Atlas
- Create a free account and cluster
- Get your connection string
- Add it to your
.env.localfile asMONGODB_URI
- Install MongoDB locally
- Start MongoDB service
- Use connection string:
mongodb://localhost:27017/koa-ai-chat
mongodb+srv://username:password@cluster.mongodb.net/koa-ai-chat?retryWrites=true&w=majority
-
Start Training: Send the secret code as the first line of your message:
- Non-custodial: They don't hold your funds - Jupiter integration: Trades execute through Jupiter - Wallet-based: You sign transactions from your wallet -
Continue Training: All subsequent messages are automatically analyzed and stored
-
Exit Training: Send
exit training modeto stop the session
- AI Analysis: Each message is analyzed for intent, sentiment, topics, and complexity
- Database Storage: Data stored in both
training_data(session management) andgitbook_content(searchable knowledge) - Natural Responses: Bot responds conversationally, acknowledging what it's learning
- Future Integration: Training data becomes part of the bot's searchable knowledge base
{
title: "Non-Custodial Trading - User Training",
content: "User's training message",
section: "User Training Data",
metadata: {
userQuestion: "Original message",
aiAnalysis: { intent, sentiment, topics, complexity },
trainingType: "user_provided",
keywords: ["extracted", "topics"],
sessionId: "unique_session_id"
},
keywords: ["searchable", "terms", "for", "future", "queries"]
}- Title Search: Exact and partial matching
- Content Search: Deep content analysis with scoring
- Training Data: User-provided training content included in search results
- Keyword Matching: Intelligent keyword extraction and matching
- Context Relevance: Scoring based on search term relevance
- Exact Matches: Highest priority (+50 points)
- Content Matches: Detailed content analysis (+45 points)
- Training Data Bonus: User training content gets priority (+30 points)
- Keyword Matches: Extracted keywords from training data (+15 per match)
- Intent Matching: User intent alignment (+25 points)
- Partial Matching: Word-level partial matches (+10 per word)
- Prioritized Results: Training data appears first for user questions
- Official Content: GitBook documentation for general queries
- Combined Responses: Intelligent merging of training and official content
- Consistent Links: Always includes links to GitBook and X (Twitter)
- Official Documentation: Complete GitBook content stored in MongoDB
- Training Data: User-provided training integrated into searchable knowledge
- Metadata Enrichment: Enhanced with AI analysis and keywords
- Version Control: Content can be updated and reinitialized
/api/training/gitbook-init: Initialize database with GitBook content/api/training/gitbook-search: Search through all content (official + training)/api/training/secret-training: Handle secret training sessions/api/admin/training-data: Admin access to training sessions/api/admin/training-gitbook: Admin access to GitBook content
KOA_CHAT/
βββ src/
β βββ app/
β β βββ page.tsx # Main landing page
β β βββ layout.tsx # Root layout
β β βββ globals.css # Global styles
β β βββ api/ # API routes
β β βββ client/ # Client management
β β β βββ status/ # Client status API
β β β βββ increment/ # Message increment API
β β βββ training/ # Training system
β β β βββ gitbook-init/ # Initialize GitBook data
β β β βββ gitbook-search/ # Search GitBook content
β β β βββ secret-training/ # Secret training API
β β βββ admin/ # Admin endpoints
β β βββ clients/ # Client management
β β βββ training-data/ # Training session data
β β βββ training-gitbook/ # GitBook content management
β βββ components/
β β βββ ChatModal.tsx # Main chat interface
β βββ lib/
β β βββ mongodb.ts # MongoDB connection utilities
β βββ models/ # Database models
β β βββ Client.ts # Client data model
β β βββ GitBookContent.ts # GitBook content model
β β βββ TrainingData.ts # Training session model
β βββ types/ # TypeScript type definitions
βββ public/ # Static assets
βββ .env.local # Environment variables
βββ README.md # This file
βββ DEPLOYMENT_GUIDE.md # Deployment instructions
βββ MONGODB_INTEGRATION.md # MongoDB setup guide
βββ package.json # Dependencies and scripts
POST /api/client/status: Get client status and message countPOST /api/client/increment: Increment message count
POST /api/training/secret-training: Handle secret training sessionsPOST /api/training/gitbook-init: Initialize GitBook databasePOST /api/training/gitbook-search: Search through all content
GET /api/admin/training-data: View training sessionsDELETE /api/admin/training-data: Delete training sessionsGET /api/admin/training-gitbook: View GitBook content
Edit the message limit in src/components/ChatModal.tsx:
if (data.messageCount >= 100) { // Change this number
setMessageLimitReached(true);
}Update in .env.local:
SECRET_TRAINING_CODE=your_new_secret_code
EXIT_TRAINING_CODE=your_new_exit_codeEdit generateNaturalResponse function in src/app/api/training/secret-training/route.ts
- Environment Variables: All sensitive data stored in
.env.local - Server-side Validation: Message limits enforced server-side
- Client Tracking: IP addresses and user agents monitored
- Training Isolation: Training sessions isolated by user ID
- Admin Protection: Admin endpoints require proper authentication
- Ensure
.env.localexists with correct variable names - Restart development server after environment changes
- Check browser console for error messages
- Verify
MONGODB_URIformat and credentials - Check network connectivity to MongoDB
- Ensure database exists and is accessible
- Verify secret codes in
.env.local - Check browser console for API errors
- Ensure MongoDB is running and accessible
- Initialize GitBook data with
/api/training/gitbook-init - Check MongoDB for stored content
- Verify search query format
/api/test-search: Test search functionality directly- Browser Console: Check for API response errors
- MongoDB Compass: Direct database inspection
DEPLOYMENT_GUIDE.md: Complete deployment instructionsMONGODB_INTEGRATION.md: Detailed MongoDB setupGITBOOK_INTEGRATION_README.md: GitBook integration detailsSECRET_TRAINING_README.md: Secret training system guide
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
This project is open source and available under the MIT License.
For issues and questions:
- Check the troubleshooting section above
- Review the additional documentation files
- Check browser console for error messages
- Verify MongoDB connection and data
- Test API endpoints directly
Built with β€οΈ for the Koasync community