Mag AI
by Magnence
Mag AI is a production-ready, enterprise-grade AI assistant platform that combines RAG-grounded knowledge retrieval, multi-LLM support, a rigorous security engine, and WhatsApp integration — all managed through a polished, responsive control panel dashboard.

Table of Contents
Overview
Mag AI is an enterprise AI assistant that:
- Answers customer questions via WhatsApp using RAG-grounded knowledge from your approved document library
- Protects against attacks with a multi-layer security engine (prompt injection detection, jailbreak defense, scope validation, PII filtering)
- Supports multi-LLM fallback across OpenAI, Anthropic, Gemini, and Grok Cloud
- Manages operations with tickets, appointments, feedback, and human handoff workflows
- Provides full auditability with security event tracking, audit logs, and analytics
The platform consists of:
- Backend — Python FastAPI application with PostgreSQL, Qdrant (vector DB), Redis, and Docker
- Frontend — Next.js 16 control panel dashboard with 18 pages
Key Features
AI & RAG
- Multi-LLM Provider Support: OpenAI, Anthropic, Gemini, Grok Cloud with automatic fallback chain
- RAG Engine: Document chunking, embedding, vector search via Qdrant, context assembly
- Confidence Scoring: Auto-respond (>80%), review (60–80%), block (<60%) thresholds
- Citation Tracking: Every AI response includes source document references with relevance scores
- Voice Messages: Whisper STT transcription with pydub audio conversion
- Image Understanding: VLM analysis + Tesseract OCR fallback
Security Engine
- Prompt Injection Detection: 20+ regex patterns + base64 + jailbreak signatures
- Scope Validation: Out-of-scope topic detection (sports, politics, legal advice, etc.)
- Response Validation: Groundedness check, fabrication detection, PII leak prevention
- Security Event Logging: All blocked attempts logged with severity, source, and patterns
Operations
- Document Approval Workflow: Draft → Pending Review → Approved → Indexed (with versioning)
- Ticket Management: Create, assign, prioritize, resolve, close
- Appointment Scheduling: Calendar view, reminders, agent assignment
- Human Handoff: Automatic escalation for complaints or explicit requests
- Feedback Collection: Helpful/not-helpful ratings with knowledge gap analysis
Control Panel (18 Pages)
| Page |
Description |
| Dashboard |
KPI overview, live activity feed, charts, quick actions |
| Conversations |
WhatsApp-style 3-pane chat with citations, quick replies, sentiment |
| Notifications |
Filterable feed with preferences and stats |
| My Profile |
User info, activity timeline, sessions, API access |
| Help & Onboarding |
Getting started checklist, keyboard shortcuts, FAQ |
| Knowledge Base |
Document library with filters, table/grid views, detail drawer |
| Approval Center |
Kanban board with approve/reject workflow |
| Tickets |
Support ticket table with detail drawer |
| Appointments |
List + calendar views |
| Analytics |
KPI cards, 7 chart types, auto-generated insights |
| AI Evaluation |
Model comparison radar, test cases, accuracy trends |
| Feedback Center |
Satisfaction metrics, knowledge gap analysis |
| Security Center |
Threat origin analysis, remediation guidance, event table |
| Audit Logs |
Searchable audit trail with action distribution |
| User Management |
User table, role distribution, invite management |
| System Health |
Service status, resource metrics, live polling |
| Settings |
7-tab config (General, AI Providers, Security, WhatsApp, Email, Integrations, Advanced) |
| AI Playground |
Interactive chat with live safety engine visualization |
Cross-Page Workflows
- Create Ticket from Conversation — Convert any conversation into a support ticket
- Save Test Case from Playground — Archive safety analysis results to AI Evaluation
- Command Palette (⌘K) — Global navigation + quick actions
- Role-Based Access Control — 4 roles (Super Admin, Admin, Agent, Viewer)
Architecture
┌─────────────────────────────────────────────────────────────┐
│ WhatsApp Users │
│ (Evolution API / Meta) │
└──────────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Nginx Reverse Proxy │
│ (Rate limiting + TLS) │
└──────────┬──────────────────────────────┬───────────────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────────────────┐
│ Next.js Frontend │ │ FastAPI Backend │
│ Control Panel │ │ (Port 8000) │
│ (Port 3000) │ │ │
│ │ │ ┌─────────────────────────────┐ │
│ 18 Pages │ │ │ AI Safety Engine │ │
│ Mock/Real API │ │ (Injection/Jailbreak/Scope) │ │
└─────────────────────┘ │ └─────────────┬───────────────┘ │
│ ▼ │
│ ┌─────────────────────────────┐ │
│ │ RAG Engine │ │
│ │ (Qdrant Vector Search) │ │
│ └─────────────┬───────────────┘ │
│ ▼ │
│ ┌─────────────────────────────┐ │
│ │ LLM Fallback Chain │ │
│ │ OpenAI→Gemini→Anthropic │ │
│ │ →Grok Cloud │ │
│ └─────────────────────────────┘ │
└──────┬──────────┬──────────┬─────┘
│ │ │
┌──────▼──┐ ┌────▼───┐ ┌───▼────┐
│PostgreSQL│ │ Qdrant │ │ Redis │
│(14 models│ │(vectors│ │(cache +│
│ + audit) │ │ + RAG) │ │ rate) │
└─────────┘ └────────┘ └────────┘
Tech Stack
Frontend
| Technology |
Version |
Purpose |
| Next.js |
16.1.3 |
React framework (App Router, Turbopack) |
| TypeScript |
5.x |
Type-safe development |
| Tailwind CSS |
4.x |
Utility-first styling |
| shadcn/ui |
New York |
Component library |
| TanStack Query |
5.x |
Server state management |
| Zustand |
5.x |
Client state management |
| Framer Motion |
11.x |
Animations |
| Recharts |
2.x |
Data visualization |
| Lucide React |
0.460+ |
Icon system |
Backend
| Technology |
Version |
Purpose |
| Python |
3.12 |
Runtime |
| FastAPI |
0.115.6 |
Web framework |
| SQLAlchemy |
2.0.36 |
ORM (async) |
| Alembic |
1.14.0 |
Database migrations |
| PostgreSQL |
16 |
Primary database |
| Qdrant |
1.12 |
Vector database (RAG) |
| Redis |
7 |
Caching + rate limiting |
| Pydantic |
2.10.4 |
Validation + settings |
| python-jose |
3.3 |
JWT authentication |
| slowapi |
0.1.9 |
Rate limiting |
AI / External Services
- OpenAI — GPT-4o, GPT-4o-mini, text-embedding-3-small, Whisper (STT)
- Anthropic — Claude 3.5 Sonnet, Claude 3 Opus
- Google Gemini — Gemini 1.5 Flash/Pro, Gemini 2.0 Flash
- Grok Cloud — Grok 3, Grok 3 Mini, Grok 2 Latest
- Evolution API — WhatsApp Web bridge (self-hosted)
- Meta WhatsApp Cloud API — Official WhatsApp Business API
- n8n — Workflow automation
- Prometheus + Grafana — Monitoring
Infrastructure
| Tool |
Purpose |
| Docker + Docker Compose |
Containerization (8 services) |
| Nginx |
Reverse proxy + rate limiting + TLS |
| Caddy |
Edge gateway (sandbox) |
| GitHub Actions |
CI/CD pipeline |
Project Structure
mag-ai/
├── src/ # Next.js frontend
│ ├── app/
│ │ ├── layout.tsx # Root layout + metadata
│ │ ├── page.tsx # Main router (auth → AppShell)
│ │ └── globals.css # Tailwind + gold theme palette
│ ├── components/
│ │ ├── layout/ # AppShell, Sidebar, Topbar, CommandPalette
│ │ ├── pages/ # 18 page components
│ │ ├── shared/ # Reusable UI (badges, formatters, states)
│ │ └── ui/ # shadcn/ui primitives (60+ components)
│ ├── hooks/ # TanStack Query hooks, use-toast, use-mobile
│ ├── lib/ # Types, mock-api, mock-data, utils, nav
│ └── store/ # Zustand stores (UI + Auth)
├── backend/ # Python FastAPI backend
│ ├── app/
│ │ ├── main.py # FastAPI app entry
│ │ ├── config/settings.py # Pydantic settings (50+ env vars)
│ │ ├── api/ # REST routes (auth, documents, webhooks, operations)
│ │ ├── ai/ # Safety engine, RAG, providers (OpenAI/Anthropic/Gemini/Grok)
│ │ ├── models/ # 14 SQLAlchemy models
│ │ ├── services/ # Business logic (tickets, appointments, email, etc.)
│ │ ├── middleware/ # Rate limiting, security headers, request ID
│ │ └── monitoring/ # Prometheus metrics
│ ├── alembic/ # Database migrations
│ ├── tests/ # pytest test suite (8 files)
│ ├── docs/ # ARCHITECTURE.md, API.md, DEPLOYMENT.md, SECURITY.md
│ ├── scripts/ # backup.sh, restore.sh, seed_eval_cases.py
│ ├── docker-compose.yml # 8-service stack
│ ├── Dockerfile # Multi-stage build
│ ├── nginx/nginx.conf # Reverse proxy config
│ └── requirements.txt # Python dependencies
├── .github/workflows/ # CI (ci.yml) + CD (deploy.yml)
├── public/logo.svg # Mag AI "M" branded logo
├── package.json # Frontend dependencies
└── README.md # This file
Prerequisites
For Frontend Only
- Node.js 18+ (or Bun runtime)
- npm, yarn, pnpm, or bun
For Full Stack
- Docker 24+
- Docker Compose v2+
- Python 3.12+ (for manual setup)
- PostgreSQL 16+ (or use Docker)
- Redis 7+ (or use Docker)
External API Keys (Optional — works with mock data without these)
- OpenAI API key (for GPT models + embeddings + Whisper)
- Anthropic API key (for Claude models)
- Google Gemini API key (for Gemini models)
- Grok Cloud API key (for Grok models)
- Evolution API instance (for WhatsApp integration)
Local Development Setup
Option 1: Frontend Only (Mock Data)
This is the fastest way to see the dashboard. The frontend runs with mock data simulating the backend.
# Clone the repository
git clone https://github.com/your-org/mag-ai.git
cd mag-ai
# Install dependencies (using npm)
npm install
# Or with npm
npm install
# Start the development server
npm run dev
# # or: yarn dev
Access the app: Open http://localhost:3000 in your browser.
Login credentials (mock — any of these work):
Note: In mock mode, all data is simulated. No backend, database, or external APIs are required.
Option 2: Full Stack with Docker
This runs the complete backend + database + vector DB + cache + monitoring stack.
# Clone the repository
git clone https://github.com/your-org/mag-ai.git
cd mag-ai
# Navigate to backend
cd backend
# Create environment file
cp .env.example .env # If .env.example exists, or create manually (see below)
# Edit .env with your API keys and secrets
nano .env
# Start all services (8 containers)
docker compose up -d
# Run database migrations
docker compose exec backend alembic upgrade head
# Seed evaluation test cases (optional)
docker compose exec backend python scripts/seed_eval_cases.py
Access the services:
Start the frontend:
# In a separate terminal, from the project root
npm install
npm run dev
Create an admin user:
# Via the API
curl -X POST http://localhost:8000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "YourSecurePassword123!",
"full_name": "Admin User",
"role": "super_admin"
}'
Option 3: Full Stack Manual Setup
For development without Docker:
1. Start PostgreSQL, Redis, and Qdrant
# Using Homebrew (macOS)
brew install postgresql@16 redis qdrant
brew services start postgresql@16
brew services start redis
qdrant # runs on port 6333
# Or using apt (Ubuntu/Debian)
sudo apt install postgresql-16 redis-server
sudo systemctl start postgresql redis-server
# Install Qdrant from: https://qdrant.tech/documentation/guides/installation/
cd backend
# Create virtual environment
python3.12 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Create .env file
cat > .env << 'EOF'
# Database
POSTGRES_USER=assistant
POSTGRES_PASSWORD=assistant_secret
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=assistant_db
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# Qdrant
QDRANT_HOST=localhost
QDRANT_PORT=6333
# JWT (CHANGE THIS!)
JWT_SECRET=your-super-secret-jwt-key-change-in-production
# AI Providers (add your keys)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=AIza...
GROK_API_KEY=xai-...
# WhatsApp (Evolution API)
WHATSAPP_PROVIDER=evolution
EVOLUTION_API_URL=http://localhost:8080
EVOLUTION_API_KEY=your-evolution-key
# Environment
ENVIRONMENT=development
DEBUG=true
CORS_ORIGINS=["http://localhost:3000"]
EOF
# Create database
createdb assistant_db
# Run migrations
alembic upgrade head
# Start the backend
python run.py
# Or: uvicorn app.main:app --reload --port 8000
# From project root
npm install
# The frontend automatically connects to http://localhost:8000
# If your backend is elsewhere, set NEXT_PUBLIC_API_URL
export NEXT_PUBLIC_API_URL=http://localhost:8000
npm run dev
Cloud Deployment
Deploy to Hostinger VPS
The project includes a GitHub Actions workflow for Hostinger deployment.
Prerequisites
- Hostinger VPS (4GB+ RAM recommended)
- Docker + Docker Compose installed on the VPS
- SSH access configured
Steps
-
Set up GitHub Secrets (in your repo → Settings → Secrets and Variables → Actions):
HOSTINGER_HOST=your-server-ip
HOSTINGER_USER=root
HOSTINGER_SSH_KEY=your-private-ssh-key
-
On the VPS, clone the repo:
ssh root@your-server-ip
mkdir -p /opt/assistant
cd /opt/assistant
git clone https://github.com/your-org/mag-ai.git backend
cd backend
-
Create production .env:
cp .env.example .env
nano .env # Set production values, strong passwords, real API keys
-
Start the stack:
docker compose up -d
docker compose exec backend alembic upgrade head
-
Set up SSL with Let’s Encrypt:
apt install certbot
certbot certonly --standalone -d api.yourdomain.com
# Edit nginx/nginx.conf to include SSL paths
docker compose restart nginx
-
Deploy updates (automatic via GitHub Actions on push to main):
# The deploy.yml workflow will:
# - SSH into your server
# - git pull
# - docker compose build backend
# - docker compose up -d backend
# - alembic upgrade head
# - health check
Deploy to AWS EC2
Prerequisites
- AWS account
- EC2 instance (t3.medium or larger — 4GB+ RAM)
- Security group open on ports 80, 443, 22
Steps
-
Launch EC2 instance (Ubuntu 22.04 LTS recommended)
-
Install Docker:
ssh -i your-key.pem ubuntu@your-ec2-ip
sudo apt update && sudo apt install -y docker.io docker-compose
sudo usermod -aG docker $USER
# Log out and back in
-
Clone and configure:
git clone https://github.com/your-org/mag-ai.git
cd mag-ai/backend
cp .env.example .env
nano .env # Configure production values
-
Start services:
docker compose up -d
docker compose exec backend alembic upgrade head
-
Set up the frontend (build and serve via Nginx or deploy to Vercel):
cd ../
npm install
npm run build
# Serve the .next/standalone output, or deploy to Vercel
-
Configure Route 53 (optional) to point your domain to the EC2 instance.
Deploy to DigitalOcean
Using DigitalOcean Droplet
-
Create a Droplet (Ubuntu 22.04, 4GB+ RAM, $24/mo plan)
-
Install Docker:
ssh root@your-droplet-ip
apt update && apt install -y docker.io docker-compose
-
Deploy:
git clone https://github.com/your-org/mag-ai.git
cd mag-ai/backend
cp .env.example .env
nano .env
docker compose up -d
docker compose exec backend alembic upgrade head
-
Set up firewall:
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable
- Connect your GitHub repository
- Set the backend directory as the app source
- Add environment variables in the DO dashboard
- Use the Dockerfile for the build
Deploy to Google Cloud / Azure
Google Cloud Run (Backend)
# Build and push the backend image
gcloud builds submit backend/ --tag gcr.io/your-project/mag-ai-backend
# Deploy to Cloud Run
gcloud run deploy mag-ai-backend \
--image gcr.io/your-project/mag-ai-backend \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars "ENVIRONMENT=production,POSTGRES_HOST=/cloudsql/your-project:us-central1:mag-ai-db"
Azure Container Instances
# Create resource group
az group create --name mag-ai-rg --location eastus
# Create container instance
az container create \
--resource-group mag-ai-rg \
--name mag-ai-backend \
--image your-registry/mag-ai-backend:latest \
--ports 8000 \
--environment-variables ENVIRONMENT=production POSTGRES_HOST=...
Environment Variables
Backend (.env)
Create a .env file in backend/ with the following variables:
# ===== Application =====
APP_NAME=Mag AI
APP_VERSION=1.0.0
ENVIRONMENT=production # development | staging | production
DEBUG=false
LOG_LEVEL=INFO
# ===== Database (PostgreSQL) =====
POSTGRES_USER=assistant
POSTGRES_PASSWORD=CHANGE_ME_STRONG_PASSWORD
POSTGRES_HOST=localhost # or postgres (Docker)
POSTGRES_PORT=5432
POSTGRES_DB=assistant_db
# DATABASE_URL is auto-built from above, or set explicitly:
# DATABASE_URL=postgresql+asyncpg://assistant:password@host:5432/assistant_db
# ===== Redis =====
REDIS_HOST=localhost # or redis (Docker)
REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME
# REDIS_URL is auto-built from above
# ===== Qdrant (Vector DB) =====
QDRANT_HOST=localhost # or qdrant (Docker)
QDRANT_PORT=6333
QDRANT_COLLECTION=company_documents
QDRANT_VECTOR_SIZE=1536
# ===== JWT / Authentication =====
JWT_SECRET=GENERATE_A_LONG_RANDOM_STRING_AT_LEAST_32_CHARS
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7
PASSWORD_MIN_LENGTH=8
# ===== AI Providers =====
MODEL_PROVIDER=openai
DEFAULT_MODEL=gpt-4o-mini
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxx
OPENAI_MODEL=gpt-4o-mini
ANTHROPIC_API_KEY=sk-ant-api03-xxxxxxxxxxxx
ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
GEMINI_API_KEY=AIzaxxxxxxxxxxxx
GEMINI_MODEL=gemini-1.5-flash
GROK_API_KEY=xai-xxxxxxxxxxxx
GROK_API_URL=https://api.x.ai/v1
GROK_MODEL=grok-2-latest
PROVIDER_FALLBACK_CHAIN=openai,gemini,anthropic,grok
# ===== Embeddings =====
EMBEDDING_PROVIDER=openai
EMBEDDING_MODEL=text-embedding-3-small
EMBEDDING_DIMENSION=1536
# ===== WhatsApp - Evolution API =====
WHATSAPP_PROVIDER=evolution # evolution | meta
EVOLUTION_API_URL=http://localhost:8080
EVOLUTION_API_KEY=your-evolution-api-key
EVOLUTION_INSTANCE=company-assistant
EVOLUTION_WEBHOOK_ROUTE=/webhooks/evolution
# ===== WhatsApp - Meta Official =====
# (Only needed if WHATSAPP_PROVIDER=meta)
META_WHATSAPP_TOKEN=your-meta-token
META_PHONE_NUMBER_ID=your-phone-number-id
META_VERIFY_TOKEN=your-verify-token
META_API_VERSION=v21.0
# ===== Email (SMTP) =====
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASSWORD=your-app-password
[email protected]
SMTP_FROM_NAME=Mag AI Assistant
SMTP_USE_TLS=true
# ===== CORS / Security =====
CORS_ORIGINS=["http://localhost:3000","https://yourdomain.com"]
RATE_LIMIT_PER_MINUTE=60
MAX_FILE_SIZE_MB=20
# ===== RAG Settings =====
CHUNK_SIZE=1000
CHUNK_OVERLAP=200
TOP_K=5
CONFIDENCE_THRESHOLD_HIGH=0.80
CONFIDENCE_THRESHOLD_MID=0.60
SIMILARITY_THRESHOLD=0.70
CONTEXT_MAX_TOKENS=4000
# ===== Company Info =====
COMPANY_NAME=Your Company Name
COMPANY_TIMEZONE=UTC
[email protected]
COMPANY_SUPPORT_PHONE=+1-555-0100
Frontend
The frontend reads from NEXT_PUBLIC_API_URL if you need to point it to a custom backend URL. Otherwise, it defaults to mock data mode.
# .env.local (optional)
NEXT_PUBLIC_API_URL=http://localhost:8000
API Reference
Base URL
http://localhost:8000/api/v1
Authentication
All protected endpoints require a Bearer token:
Authorization: Bearer <access_token>
Endpoints
| Method |
Path |
Description |
| Auth |
|
|
| POST |
/auth/register |
Register a new user |
| POST |
/auth/login |
Login and get tokens |
| POST |
/auth/refresh |
Refresh access token |
| GET |
/auth/me |
Get current user |
| POST |
/auth/change-password |
Change password |
| POST |
/auth/assign-role |
Assign role (admin+) |
| Documents |
|
|
| POST |
/documents/upload |
Upload a document |
| GET |
/documents |
List documents |
| POST |
/documents/{id}/submit-review |
Submit for review |
| POST |
/documents/{id}/approve |
Approve document |
| POST |
/documents/{id}/reject |
Reject document |
| POST |
/documents/{id}/reindex |
Re-index in Qdrant |
| DELETE |
/documents/{id} |
Delete document |
| POST |
/documents/{id}/new-version |
Upload new version |
| Webhooks |
|
|
| POST |
/webhooks/evolution |
Evolution API webhook |
| GET |
/webhooks/evolution |
Webhook verification |
| POST |
/webhooks/meta |
Meta WhatsApp webhook |
| GET |
/webhooks/meta |
Meta webhook verification |
| Operations |
|
|
| GET |
/conversations |
List conversations |
| GET |
/conversations/{id}/messages |
Get messages |
| GET |
/tickets |
List tickets |
| POST |
/tickets/{id}/status |
Update ticket status |
| GET |
/appointments |
List appointments |
| POST |
/feedback |
Submit feedback |
| GET |
/analytics/summary |
Dashboard analytics |
| GET |
/analytics/intents |
Intent distribution |
| GET |
/analytics/providers |
Provider stats |
| GET |
/security-events |
Security events |
| GET |
/audit-logs |
Audit trail |
| GET |
/agent-logs |
Agent processing logs |
| GET |
/evaluation/cases |
Evaluation test cases |
| GET |
/evaluation/results |
Evaluation results |
Interactive Docs
- Swagger UI:
http://localhost:8000/docs
- ReDoc:
http://localhost:8000/redoc
Frontend Pages
The control panel has 18 pages organized into 6 groups:
| Group |
Pages |
| Overview |
Dashboard, Conversations, Notifications, My Profile, Help & Onboarding |
| Knowledge |
Knowledge Base, Approvals |
| Operations |
Tickets, Appointments |
| Insights |
Analytics, AI Evaluation, Feedback |
| Security |
Security Center, Audit Logs |
| Admin |
User Management, System Health, Settings |
| AI Tools |
AI Playground |
Key Frontend Features
- Command Palette (⌘K / Ctrl+K) — Global search + quick actions
- Dark Mode — Full dark mode support with theme toggle
- Responsive — Works at 320px to 1920px+ widths
- Role-Based Access — 4 roles with page-level permissions
- Cross-Page Workflows — Create Ticket from Conversation, Save Test Case from Playground
- Live Activity Feed — Real-time event stream on Dashboard
- AI Playground — Interactive chat with safety engine visualization
Security
Security Engine Layers
- Intent Classification — Allowed vs blocked intents
- Prompt Injection Detection — 20+ regex patterns + base64 + jailbreak signatures
- Scope Validation — Out-of-scope topic detection
- Response Validation — Groundedness, fabrication, PII leak checks
- Confidence Gating — Auto-respond (>80%), review (60-80%), block (<60%)
Security Best Practices
- JWT tokens with short-lived access (30min) + refresh (7 days)
- bcrypt password hashing
- Rate limiting (60 req/min default, configurable)
- CORS whitelisting
- File upload validation (extension, MIME, signature, size)
- Security headers via Nginx
- Audit logging for all sensitive actions
Production Security Checklist
See backend/docs/SECURITY.md for the full security documentation.
Testing
Backend Tests
cd backend
# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/test_safety_engine.py -v
# Run only safety tests
pytest tests/ -k "safety or injection or scope" -v
Test files:
tests/test_intent.py — Intent classification
tests/test_injection.py — Prompt injection detection
tests/test_scope.py — Scope validation
tests/test_safety_engine.py — Full safety pipeline
tests/test_response_validation.py — Response validation
tests/test_webhooks.py — Webhook handling
tests/test_documents_security.py — Document upload security
tests/test_rag.py — RAG engine
Frontend Linting
# From project root
npm run lint
# or: npm run lint
Monitoring
Prometheus Metrics
The backend exposes Prometheus metrics at http://localhost:8000/metrics:
- Request count + latency histograms
- Active connections
- RAG query performance
- AI provider latency
- Security event counters
Grafana Dashboards
Pre-configured dashboards at http://localhost:3001 (admin/admin):
- API Overview (requests, latency, errors)
- AI Performance (provider latency, token usage, confidence)
- Security (blocked attempts, severity distribution)
- System (CPU, memory, disk)
Health Checks
- Liveness:
GET /health/live — Returns 200 if process is running
- Readiness:
GET /health/ready — Returns 200 if all dependencies are connected
Backup & Restore
Backup
cd backend
# Run the backup script (dumps PostgreSQL + Qdrant + uploads)
docker compose exec backend ./scripts/backup.sh
# Or manually:
# PostgreSQL backup
docker compose exec postgres pg_dump -U assistant assistant_db > backups/db_$(date +%Y%m%d).sql
# Qdrant backup
curl -X POST http://localhost:6333/collections/company_documents/snapshots
Restore
# Restore from backup
docker compose exec backend ./scripts/restore.sh backups/db_20240115.sql
# Or manually:
cat backups/db_20240115.sql | docker compose exec -T postgres psql -U assistant assistant_db
Automated Backups (Cron)
# Add to crontab (daily at 2 AM)
crontab -e
0 2 * * * cd /opt/assistant/backend && docker compose exec backend ./scripts/backup.sh >> /var/log/mag-ai-backup.log 2>&1
Troubleshooting
Common Issues
Frontend won’t start
# Clear Next.js cache
rm -rf .next
npm install
npm run dev
Backend can’t connect to PostgreSQL
# Check if PostgreSQL is running
docker compose ps postgres
# Check logs
docker compose logs postgres
# Verify connection
docker compose exec backend python -c "import asyncpg; import asyncio; asyncio.run(asyncpg.connect('postgresql://assistant:assistant_secret@postgres:5432/assistant_db'))"
Qdrant connection failed
# Check Qdrant status
curl http://localhost:6333/healthz
# Restart Qdrant
docker compose restart qdrant
WhatsApp webhook not receiving messages
- Verify Evolution API is running:
curl http://localhost:8080/health
- Check webhook URL is publicly accessible (use ngrok for local testing)
- Verify webhook secret matches in both Evolution API and backend
.env
- Check backend logs:
docker compose logs backend | grep webhook
AI responses are empty or erroring
- Verify API keys are set in
.env
- Check provider health:
curl http://localhost:8000/health/ready
- Check logs:
docker compose logs backend | grep -i "provider\|openai\|anthropic\|gemini\|grok"
- The fallback chain will try the next provider if one fails
OOM (Out of Memory) errors
- Minimum 4GB RAM for production
- Increase Docker memory limits in
docker-compose.yml
- Reduce
CONTEXT_MAX_TOKENS in .env
- Use a smaller embedding model (
text-embedding-3-small is recommended)
Logs
# Backend logs
docker compose logs -f backend
# All services
docker compose logs -f
# Specific service
docker compose logs -f postgres
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
Development Guidelines
- Frontend: Use TypeScript strict mode, follow existing shadcn/ui patterns
- Backend: Follow PEP 8, add type hints, write tests for new features
- Colors: Use the gold palette (
gold-50 through gold-950) — do NOT use indigo, violet, or purple
- Branding: Always use “Mag AI” and “Powered by Magnence” — no other branding
- Testing: Run
npm run lint (frontend) and pytest (backend) before submitting PRs
License
This project is licensed under the MIT License — see the LICENSE file for details.
Powered by Magnence
Mag AI — AI-Powered Enterprise Operations Platform
© 2026 Magnence. All rights reserved.
Production Hardening
The platform includes enterprise-grade security measures:
🔐 Password Security (bcrypt)
- All passwords are hashed with bcrypt (12 salt rounds) before storage
- Legacy plain-text passwords are auto-upgraded to bcrypt on next login
- Password validation: minimum 8 characters on registration
- Password changes via admin or profile use bcrypt hashing
// In src/lib/auth.ts
import bcrypt from "bcryptjs";
const hashedPassword = await bcrypt.hash(password, 12);
const isValid = await bcrypt.compare(password, storedHash);
🎫 JWT Authentication
- Login generates a proper JWT with claims:
sub (user ID), email, role, iat, exp
- Access tokens expire in 30 minutes
- Refresh tokens expire in 7 days
- JWT verification middleware on all protected API routes
- Token expiry returns HTTP 401 with “Token expired” message
🚦 Rate Limiting
- Login: 10 attempts per minute per IP
- Registration: 5 registrations per minute per IP
- General API: 60 requests per minute per IP
- Returns HTTP 429 with
Retry-After header when limit exceeded
- In-memory rate limiter (per-IP tracking)
All responses include:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload (HSTS)
Content-Security-Policy: default-src 'self'; ... (CSP)
X-Frame-Options: DENY (clickjacking prevention)
X-Content-Type-Options: nosniff (MIME sniffing prevention)
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()
Server and X-Powered-By headers removed
🗄️ PostgreSQL Support
- Development: SQLite (zero-config, file-based)
- Production: PostgreSQL — switch by:
- Change
provider = "sqlite" to provider = "postgresql" in prisma/schema.prisma
- Set
DATABASE_URL=postgresql://user:pass@host:5432/dbname in .env
- Run
npx prisma db push to create tables in PostgreSQL
- See
.env.production.example for full production configuration
🔔 Smart Notifications
- Notification badge auto-clears when you visit related sections:
- Visit Conversations → “mentions” notifications marked as read
- Visit Knowledge Base/Approvals → “documents” notifications marked as read
- Visit Tickets/Appointments → “tickets” notifications marked as read
- Visit Security/Audit Logs → “security” notifications marked as read
- Visit Analytics/AI Evaluation/Feedback → “system” notifications marked as read
- Opening the notification dropdown auto-marks all as read after 2 seconds
- Clicking individual notifications marks them as read
- All read status is synced to the database
评论