Skip to content

codingwalebhaiya/Qna-Chatbot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

🤖 AI ChatBot with LangChain & Google Gemini API A production-ready, full-stack AI chatbot application built with modern technologies. Features secure authentication, encrypted chat history, rate limiting, and a beautiful responsive UI.

✨ Features

🔒 Security & Authentication

JWT & API Key based authentication Password encryption with bcrypt End-to-end encrypted chat messages Input sanitization & validation Rate limiting per user/IP CORS protection

💬 Chat Features

Real-time conversation with Google Gemini AI Persistent chat history per session Markdown support in responses Copy messages to clipboard Conversation feedback (like/dislike) Multiple chat sessions Context-aware responses

🎨 UI/UX

Modern, responsive design with Tailwind CSS ShadCN UI components Dark/light mode ready Loading states & animations Mobile-friendly interface Toast notifications

🛠️ Developer Experience

Full TypeScript support Shared types between frontend/backend Environment-based configuration Comprehensive error handling API documentation Docker support

📋 Prerequisites

Node.js 18+ MongoDB 6.0+ Google Gemini API Key npm or yarn package manager

🚀 Quick Start

  1. Clone the Repository bash git clone https://github.com/codingwalebhaiya/Qna-Chatbot cd Qna-Chatbot

  2. Backend Setup

cd backend

npm install

Create .env file: env PORT=5000 MONGODB_URI=mongodb://localhost:27017/chatbot_db JWT_SECRET=your_super_secure_jwt_secret GOOGLE_GEMINI_API_KEY=your_gemini_api_key FRONTEND_URL=http://localhost:5173

  1. Frontend Setup

cd frontend npm install Create .env file: env VITE_API_URL=http://localhost:5000/api VITE_APP_NAME=AI ChatBot

  1. Start MongoDB

Using Docker

docker run -d -p 27017:27017 --name mongodb-chatbot mongo:latest

Or using installed MongoDB

mongod

  1. Run Development Servers

Terminal 1 - Backend

cd backend npm run dev

Terminal 2 - Frontend

cd frontend npm run dev

  1. Open Application Navigate to http://localhost:5173

📁 Project Structure text Qna-Chatbot/ ├── backend/ # Node.js + Express + TypeScript │ ├── src/ │ │ ├── models/ # MongoDB schemas │ │ ├── routes/ # API routes │ │ ├── services/ # Business logic │ │ ├── middleware/ # Auth & validation │ │ └── utils/ # Helper functions │ ├── .env # Environment variables │ └── package.json │ ├── frontend/ # React + TypeScript + Vite │ ├── src/ │ │ ├── components/ # React components │ │ ├── lib/ # API client & utilities │ │ └── App.tsx # Main app component │ ├── .env # Frontend environment │ └── package.json │ └── README.md

🔧 API Endpoints

Authentication Method Endpoint Description POST /api/auth/register Register new user POST /api/auth/login Login user GET /api/auth/profile Get user profile POST /api/auth/regenerate-api-key Regenerate API key

Chat Method Endpoint Description POST /api/chat Send message to chatbot GET /api/chat/history/:sessionId Get chat history

Health Method Endpoint Description GET /health Health check endpoint

🔐 Security Features

  1. Authentication JWT tokens with expiration API key support for programmatic access Secure password hashing with bcrypt Account lockout prevention

  2. Data Protection Encrypted chat messages in database Input sanitization against XSS attacks SQL/NoSQL injection prevention Secure HTTP headers with Helmet

  3. Rate Limiting 100 requests per 15 minutes per user Different limits for free/premium users Redis-based rate limiting (optional)

  4. Validation Zod schema validation Request payload sanitization File upload validation Content type checking

🎨 UI Components Built with ShadCN UI: Button - Customizable buttons with variants Input - Form input fields with validation Card - Content containers Avatar - User profile images Toast - Notification system ScrollArea - Custom scrollbars Custom Components: ChatInterface - Main chat interface MessageBubble - Individual chat messages AuthForm - Login/Registration forms UserProfile - Profile management ApiKeyManager - API key controls

📦 Dependencies Backend json { "express": "Web framework", "mongoose": "MongoDB ODM", "jsonwebtoken": "JWT authentication", "bcryptjs": "Password hashing", "langchain": "AI orchestration", "@langchain/google-genai": "Gemini integration", "zod": "Schema validation", "helmet": "Security headers", "cors": "Cross-origin support" } Frontend json { "react": "UI library", "axios": "HTTP client", "react-query": "Data fetching", "react-hook-form": "Form handling", "tailwindcss": "Styling", "shadcn/ui": "UI components", "lucide-react": "Icons", "date-fns": "Date formatting" }

🐳 Docker Deployment

  1. Docker Compose Setup yaml version: '3.8' services: mongodb: image: mongo:latest ports:
    • "27017:27017" volumes:
    • mongodb_data:/data/db

backend: build: ./backend ports: - "5000:5000" environment: - MONGODB_URI=mongodb://mongodb:27017/chatbot_db - GOOGLE_GEMINI_API_KEY=${GOOGLE_GEMINI_API_KEY} depends_on: - mongodb

frontend: build: ./frontend ports: - "5173:5173" environment: - VITE_API_URL=http://localhost:5000/api depends_on: - backend

volumes: mongodb_data:

  1. Build and Run

docker-compose up --build 🌐 Environment Variables Backend (.env) env

Required

PORT=5000 MONGODB_URI=mongodb://localhost:27017/chatbot_db JWT_SECRET=your_jwt_secret_here GOOGLE_GEMINI_API_KEY=your_gemini_api_key

Optional

NODE_ENV=production FRONTEND_URL=http://localhost:5173 REDIS_URL=redis://localhost:6379 RATE_LIMIT_MAX=100 Frontend (.env) env VITE_API_URL=http://localhost:5000/api VITE_APP_NAME=AI ChatBot VITE_APP_VERSION=1.0.0

🔄 Development Workflow

  1. Code Structure TypeScript for type safety

Modular architecture for scalability

Shared types between frontend/backend

ESLint & Prettier for code quality

  1. Git Workflow

Create feature branch

git checkout -b feature/new-chat-feature

Commit changes

git add . git commit -m "Add: New chat feature"

Push to remote

git push origin feature/new-chat-feature 3. Testing

Backend tests

cd backend npm test

Frontend tests

cd frontend npm test

🚢 Deployment Option 1: Railway (Recommended)

Deploy backend

railway up --service backend

Deploy frontend

railway up --service frontend Option 2: Render Backend: Web Service Frontend: Static Site Database: MongoDB Atlas

Option 3: Vercel + MongoDB Atlas Frontend: Vercel Backend: Vercel Serverless Functions Database: MongoDB Atlas

📊 Monitoring & Analytics Built-in Monitoring Request logging Error tracking Performance metrics Usage analytics Integration Options Sentry for error tracking

Google Analytics for user behavior LogRocket for session replay Prometheus for metrics

🔧 Troubleshooting Common Issues: MongoDB Connection Failed

Check if MongoDB is running

sudo systemctl status mongod

Or start with Docker

docker start mongodb-chatbot CORS Errors

javascript // Ensure FRONTEND_URL matches your frontend origin FRONTEND_URL=http://localhost:5173 JWT Token Expired

bash

Clear localStorage and login again

localStorage.clear() Rate Limit Exceeded

javascript // Check user's usage count // Premium users have higher limits

🤝 Contributing Fork the repository Create a feature branch Commit your changes Push to the branch Open a Pull Request Development Guidelines Follow TypeScript best practices Write meaningful commit messages Add tests for new features Update documentation Use descriptive variable names

📄 License This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments Google Gemini for AI capabilities LangChain for AI orchestration ShadCN UI for beautiful components Vite for fast development

📞 Support For support, email: [email protected] or open an issue in the GitHub repository.

🔗 Useful Links Google AI Studio - Get Gemini API Key LangChain Documentation - AI Orchestration MongoDB Atlas - Cloud Database Tailwind CSS - Styling Framework

Built with ❤️ by Satyam Pandey

GitHubWebsiteTwitter/X

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published