================================================================================ BANKBOT AI — COMPLETE PROJECT DOCUMENTATION Version 2.0 · June 2026 ================================================================================ TABLE OF CONTENTS ───────────────── 1. Project Overview 2. Quick Start — How to Run the Project 3. How It Works — System Walkthrough 4. Technologies Used 5. Features 6. Architecture 7. AI Engine 8. Security 9. Database & Data Models 10. API Reference 11. Deployment Options 12. Use Cases 13. How BankBot Differs from Real-World Banking Apps 14. Known Limitations 15. Project Structure ================================================================================ 1. PROJECT OVERVIEW ================================================================================ BankBot AI is a production-grade, AI-native financial operating system built as a portfolio and educational project. It simulates the core features of a modern digital bank — account management, transactions, fraud detection, financial forecasting, goal tracking, and an AI assistant — all backed by a real FastAPI backend, a Next.js 14 frontend, and a multi-provider LLM chain. The project is live at: https://mohsin-devs-bankbot.hf.space/ Demo login: Email: alex@bankbot.dev Password: BankBot2026! Pre-loaded demo data: • $59,637 total balance across 3 accounts • 160 transactions across 6 months • 1 fraud alert (Tech Store NYC · $847 · 78% risk score) • 4 financial goals (Emergency Fund · Vacation · MacBook · Down Payment) • 4 investments (S&P 500 · AAPL · BTC · US Treasuries) • 6 subscriptions (Netflix · Spotify · Adobe CC · Planet Fitness · iCloud · LinkedIn) • 6 notifications (3 unread) GitHub: https://github.com/mohsinkp02/Bankbot-AI ================================================================================ 2. QUICK START — HOW TO RUN THE PROJECT ================================================================================ PREREQUISITES ───────────── • Python 3.11+ • Node.js 18+ • Git ──────────────────────────────────────── OPTION A — Local Development (Recommended for dev) ──────────────────────────────────────── Step 1: Clone the repository git clone https://github.com/mohsinkp02/Bankbot-AI.git cd Bankbot-AI Step 2: Set up the backend cd backend python -m venv venv venv\Scripts\activate (Windows) source venv/bin/activate (macOS / Linux) pip install -r requirements.txt Step 3: Configure environment copy .env.example .env (Edit .env and add at minimum:) GROQ_API_KEY=gsk_... # Free at console.groq.com JWT_SECRET_KEY=any-random-string-here Step 4: Seed demo data python app/scripts/seed_demo.py Step 5: Start the backend (keep this terminal open) uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload Step 6: In a NEW terminal — set up the frontend cd frontend npm install --legacy-peer-deps npm run dev Step 7: Open in browser Frontend → http://localhost:3000 API Docs → http://localhost:8000/docs Metrics → http://localhost:8000/api/metrics Health → http://localhost:8000/health Login with: alex@bankbot.dev / BankBot2026! ──────────────────────────────────────── OPTION B — Docker Compose ──────────────────────────────────────── Step 1: Copy and configure environment copy .env.example .env (Add GROQ_API_KEY and JWT_SECRET_KEY) Step 2: Build and start all containers docker compose up -d Step 3: Seed demo data docker compose exec backend python app/scripts/seed_demo.py Step 4: Open http://localhost:3000 Stop with: docker compose down ──────────────────────────────────────── OPTION C — Hugging Face Spaces (No setup needed) ──────────────────────────────────────── Just open the live URL: https://mohsin-devs-bankbot.hf.space/ Log in with: alex@bankbot.dev / BankBot2026! ──────────────────────────────────────── ENVIRONMENT VARIABLES ──────────────────────────────────────── Variable Required Default Description ───────────────────────────────────────────────────────────────────────────── GROQ_API_KEY Recommended — Free LLM from console.groq.com OPENAI_API_KEY Optional — OpenAI GPT-4o-mini (priority 1) JWT_SECRET_KEY Yes (prod) dev-secret Signs JWT tokens DATABASE_URL Optional SQLite PostgreSQL URL (Neon / Supabase) REDIS_URL Optional in-memory Redis URL for caching BACKEND_CORS_ORIGINS Optional localhost:3000 Allowed frontend origins ACCESS_TOKEN_EXPIRE_MINUTES Optional 60 JWT access token lifetime ================================================================================ 3. HOW IT WORKS — SYSTEM WALKTHROUGH ================================================================================ REQUEST LIFECYCLE (Dashboard Load) ─────────────────────────────────── 1. User opens http://localhost:3000 2. Next.js App Router renders the dashboard page 3. React component calls dashboardApi.overview() 4. api.ts sends: GET /api/dashboard/overview Authorization: Bearer 5. Nginx routes /api/* → FastAPI on port 8000 6. FastAPI middleware stack: a. CORS validation b. Rate limiter (120 req/min per IP) c. Security headers injection d. Request logger e. JWT token validation 7. Dashboard router checks Redis cache → Cache HIT (within 2 min): returns JSON in ~10ms → Cache MISS: queries database - accounts + balances - last 20 transactions - category spending aggregation - fraud alerts count - cash flow (6 months) - calls AI briefing (Groq/fallback) - caches result for 2 minutes 8. JSON response returned to Next.js 9. React renders: stat cards, charts, transaction list, fraud shield AI CHAT FLOW ──────────── 1. User types a message in the AI Assistant 2. Frontend calls POST /api/ai/chat with { message, session_id, language } 3. Backend fetches user's complete financial context from DB: - account balances - last 50 transactions - active goals + progress - investments + portfolio - subscriptions - fraud alerts 4. Builds a detailed system prompt with all this real data 5. Calls AI provider chain: Priority 1: OpenAI (gpt-4o-mini) if OPENAI_API_KEY set Priority 2: Groq (llama-3.3-70b) if GROQ_API_KEY set ← HF demo Priority 3: Ollama (llama3:latest) if running locally Priority 4: Rule-based fallback always works 6. Response text returned to frontend 7. Frontend displays word-by-word animation (28ms interval) 8. Both user message and AI response saved to chat memory (DB) FILE ATTACHMENT IN CHAT ──────────────────────── 1. User clicks the paperclip icon or drags a file onto the chat window 2. File immediately uploads to POST /api/documents/upload 3. Backend extracts text: PDF → pypdf → PyMuPDF → Tesseract OCR (fallback) DOCX → python-docx CSV → csv module (max 200 rows) TXT → direct decode Image → Tesseract OCR 4. AI analyzes extracted text: summary + key insights + suspicious items 5. File chip appears in input showing upload status (spinning → checkmark) 6. User can type a question or just hit send (default: "summarize this") 7. Backend calls POST /api/documents/chat with the question 8. Answer uses ONLY the document content — no hallucination 9. DocBadge in user message shows filename + expandable summary + insights FRAUD DETECTION FLOW ──────────────────── Every transaction is scored when it is recorded: Score calculation: • Amount spike > 3.5x user's avg → +40 pts • Amount spike > 2.0x user's avg → +20 pts • Night timing 11PM – 4AM → +25 pts • Rapid-fire < 3 min since last → +20 pts • Duplicate same merchant+amt, within 10 min → +30 pts Results: • Score ≥ 50 → flagged → notification created → appears in Security • Score 30-49 → suspicious • Score < 30 → verified CACHING STRATEGY ──────────────── Endpoint Cache Key TTL Reason ───────────────────────────────────────────────────────────────────────────── Dashboard overview dashboard:overview:{uid} 2 min Heavy DB, high traffic AI health score ai:coaching:score:{uid} 10 min LLM call is slow AI daily briefing ai:coaching:briefing:{uid} 1 hour Expensive to generate Behavior insights ai:behavior:insights:{uid} 10 min Pattern analysis heavy Balance prediction ai:twin:predict:{uid} 5 min Moderate cost Subscription optimization ai:subs:optimize:{uid} 10 min Stable data Cache backend: Redis if configured → in-memory Python dict fallback No configuration change needed to use fallback. ================================================================================ 4. TECHNOLOGIES USED ================================================================================ FRONTEND ──────── Next.js 14.2 React framework — App Router, SSR, standalone output for Docker TypeScript 5 Type safety across all frontend code Tailwind CSS 3.4 Utility-first styling + CSS custom properties for dark/light themes Framer Motion 12 Page transitions, card hover animations, stagger effects Recharts 3 Area charts, pie charts, sparklines on the dashboard Zustand 5 Lightweight global state management (auth, theme, language, dashboard) Radix UI Accessible dialog, slider, and tooltip primitives Lucide React Icon system (consistent, tree-shakeable) BACKEND ─────── FastAPI 0.111 Async HTTP + WebSocket API framework (Python 3.11) Uvicorn 0.29 ASGI server with reload support SQLAlchemy 2.0 ORM + connection pooling (works with SQLite and PostgreSQL) Alembic 1.13 Database migration tool python-jose 3.3 JWT encode/decode (HS256 algorithm) passlib[bcrypt] 1.7 Password hashing with bcrypt (rounds=12) openai 1.30 OpenAI API client (GPT-4o-mini) groq 0.9 Groq API client (llama-3.3-70b-versatile) redis 5.0 Redis client with in-memory dict fallback pydantic 2.7 Request/response validation and env settings management pypdf 4.2 PDF text extraction (primary) PyMuPDF 1.24 PDF extraction + OCR fallback python-docx 1.1 DOCX text extraction numpy 1.26 Numerical operations for ML loan predictor httpx 0.27 HTTP client for internal requests and tests INFRASTRUCTURE ────────────── Docker Multi-stage build: Node 20 (Next.js build) + Python 3.11 slim (runtime) Nginx Reverse proxy: routes port 7860 to Next.js (3000) or FastAPI (8000) Supervisord Process manager running 3 processes in one container SQLite Default database — zero config, perfect for demo/dev PostgreSQL 15 Production database option Redis 7 Cache layer (optional — in-memory fallback if not set) Hugging Face Spaces Free Docker hosting — live URL in ~5 minutes GitHub Actions CI: lint and build checks on push to main WHY THESE CHOICES ───────────────── Next.js standalone mode: shrinks Docker image by ~70% vs copying node_modules. FastAPI + SQLAlchemy: clean async code, same models work on SQLite and PostgreSQL. Groq as default AI: free tier, 500+ tokens/second — fast enough for streaming demos. Zustand over Redux: zero boilerplate, 1-2 KB, TypeScript-first. Tailwind CSS variables: enables instant dark/light switching without re-renders. Single Docker container: simplifies HF deployment — one port (7860), one process manager. ================================================================================ 5. FEATURES ================================================================================ DASHBOARD • Single API call returns all data: balance, income, expenses, cash flow 6 months, category spending, recent transactions, health score, AI briefing • 4 animated stat cards with trend arrows • Area chart: Income vs Expenses vs Savings (6 months) • Pie chart: Spending breakdown by category • Recent transactions list with merchant, category, amount • Fraud shield banner showing alert count • Cold load: ~65ms | Cached load: ~10ms AI ASSISTANT • Full financial context injected into every message prompt • Knows real balance, goals, investments, fraud alerts, spending patterns • Attach files (PDF, DOCX, CSV, TXT, images) directly in the chat input • Drag-and-drop files onto the chat window • AI answers questions about attached documents, restricted to document content • Chat memory: conversation history persisted across sessions • Responds in English, Hindi, or Marathi based on user's language setting • 4-tier AI fallback: OpenAI → Groq → Ollama → Rule-based FRAUD DETECTION (Security page) • Real-time scoring on 4 dimensions: amount spike, night timing, velocity, duplicates • Risk levels: verified / suspicious / flagged • AI explanation for each fraud alert • Notification created automatically for flagged transactions • Notification bell with unread count in navbar FINANCIAL HEALTH SCORE • 100-point composite across 6 weighted dimensions: - Savings consistency (20 pts) - Debt ratio (20 pts) - Spending discipline (20 pts) - Emergency fund (20 pts) - Investments (10 pts) - Subscription hygiene (10 pts) WHAT-IF SIMULATOR • 6 real-time sliders: income, rent, food, transport, entertainment, savings target • Instant 36-month balance projection • Conservative / Expected / Optimistic scenario comparison • AI commentary on the projection ANALYTICS • Spending heatmap by day of week and hour • Category comparison month-over-month • Weekly coaching report with anomaly detection • Monthly narrative: total spend, income, savings story PAYMENTS • Create payment with automatic fraud scoring • Internal account-to-account transfer • Payment history with status (pending/completed/failed/flagged) • Risk score displayed per payment GOALS • Create and track financial goals with target dates • Progress bar and days remaining • AI-generated monthly contribution plan • Contribute to goals directly from the UI LOANS • ML-based loan eligibility predictor (salary, credit score, employment years, age) • Approval probability + risk level • EMI calculation for different tenures • Comparison table for different interest rates SETTINGS • Change display name and financial personality • Toggle notifications, AI coaching, fraud alerts • Theme toggle (dark/light) • Language switcher (EN/HI/MR) SYSTEM STATUS • Live metrics: request count, error rate, AI latency (p95), cache hit ratio • WebSocket connection stats • Backend health: AI provider, DB type, cache type, uptime • Per-route latency averages ================================================================================ 6. ARCHITECTURE ================================================================================ SINGLE-CONTAINER (Hugging Face) ──────────────────────────────── Internet ↓ HF Spaces (port 7860) ↓ Nginx (reverse proxy) ├── /api/* → FastAPI (port 8000) ├── /docs → FastAPI (port 8000) └── /* → Next.js (port 3000) ↓ SQLite + in-memory cache All three processes (Nginx + FastAPI + Next.js) are managed by supervisord inside one Docker container. This keeps the HF deployment simple — one container, one port. MULTI-CONTAINER (Docker Compose / Production) ────────────────────────────────────────────── Browser ├──→ localhost:3000 → nextjs container └──→ localhost:8000 → fastapi container ├── postgres container └── redis container MIDDLEWARE STACK ORDER ────────────────────── Request enters → Nginx rate limiter (30 req/min API, 10 req/min auth) → FastAPI CORS validation → FastAPI rate limiter (120 req/min per IP, in-process) → Security headers middleware → Request logger (structured JSON, includes request-id) → Process-time header middleware → Route handler → JWT validation (protected routes only) → Business logic → Cache check → DB query → AI call → Cache set → Response with X-Process-Time header ================================================================================ 7. AI ENGINE ================================================================================ PROVIDER CHAIN ────────────── 1. OpenAI (gpt-4o-mini) ← fastest, most capable, costs money ↓ if not configured or error 2. Groq (llama-3.3-70b) ← free tier, very fast (500+ tok/s) ↓ if not configured or error 3. Ollama (llama3:latest) ← fully local, no API needed ↓ if not running 4. Rule-based fallback ← always works, uses real DB data, no LLM The app never crashes because of missing AI keys. The rule-based fallback uses actual database queries to generate deterministic answers. CONTEXT INJECTION (what's in every chat prompt) ──────────────────────────────────────────────── System prompt includes: • User name + financial personality • Health score • Total balance + per-account breakdown • Monthly income and expenses • Savings rate • Top 5 spending categories this month • Active goals with progress percentages • Investment portfolio with gain/loss • Subscription list with monthly total • Fraud alert count • Language instruction (respond in EN/HI/MR) This means every AI answer is grounded in the user's actual numbers — not generic financial advice. STREAMING ───────── WebSocket (WS /api/ai/chat/ws): Tokens streamed from AI provider as they are generated. Client receives { type: "chat_chunk", content: "..." } per token. HTTP (POST /api/ai/chat): Full response returned at once. Frontend simulates streaming with word-by-word display (28ms interval). ================================================================================ 8. SECURITY ================================================================================ AUTHENTICATION FLOW ──────────────────── POST /api/auth/login → validates email + bcrypt hash (rounds=12) → returns access_token (JWT, 60 min) + refresh_token (JWT, 7 days) Protected requests: Authorization: Bearer → JWT signature verified + expiry checked on every request Access token expired: → POST /api/auth/refresh with refresh_token → new access_token returned (refresh_token unchanged) → api.ts handles this automatically (transparent to user) Logout: → client clears localStorage (stateless — no server-side session) PASSWORD STORAGE ──────────────── bcrypt with 12 rounds. Never stored in plain text. Never returned in any API response. SECURITY HEADERS (on every response) ────────────────────────────────────── X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Referrer-Policy: strict-origin-when-cross-origin Permissions-Policy: camera=(), microphone=(), geolocation=() RATE LIMITING ───────────── Nginx: 30 requests/min for /api/*, 10 requests/min for /api/auth/* FastAPI: 120 requests/min per IP (in-process, resets per minute window) Response: HTTP 429 with Retry-After header IMPORTANT NOTE FOR PRODUCTION USE ────────────────────────────────── BankBot is a demo — it has not been security-audited or penetration-tested. Do NOT use it to handle real user financial data or real money. ================================================================================ 9. DATABASE & DATA MODELS ================================================================================ DATABASE SELECTION ────────────────── Default: SQLite (auto-created at backend/bankbot.db, zero config) Production: PostgreSQL (set DATABASE_URL env var) The same SQLAlchemy ORM models work identically on both databases. If DATABASE_URL points to PostgreSQL and the connection fails, the app silently falls back to SQLite. CORE MODELS ──────────── User id UUID (primary key) email VARCHAR UNIQUE NOT NULL password_hash VARCHAR NOT NULL (bcrypt) profile_data JSON {name, phone, avatar, plan} financial_personality VARCHAR ai_personalization_settings JSON created_at, updated_at TIMESTAMP Account (belongs to User) id, user_id, type (checking/savings/investment), balance, currency, status Transaction (belongs to Account) id, account_id, amount, type (credit/debit), category, merchant timestamp, tags (JSON), spending_emotion_label FraudLog (belongs to Transaction, 0 or 1 per transaction) id, transaction_id, risk_score (0.0–1.0), suspicious_activity_details status (pending/resolved/false_positive) Goal (belongs to User) id, user_id, title, target_amount, current_amount, target_date ai_generated_plan JSON Investment (belongs to User) id, user_id, asset_name, type, amount_invested, current_value portfolio_allocation, ai_risk_analysis JSON Subscription (belongs to User) id, user_id, merchant, amount, billing_cycle, active ai_usage_detection JSON Notification (belongs to User) id, user_id, title, message, type, read_status, created_at ChatMessage (belongs to User) id, user_id, session_id, role (user/assistant), content, created_at UploadedDocument (belongs to User) id, user_id, filename, file_type, extracted_text (TEXT, max 50k chars) ai_summary, ai_insights (JSON) PERFORMANCE INDEXES ──────────────────── transactions(account_id) — most frequent join transactions(timestamp DESC) — timeline queries transactions(category) — spending analysis notifications(user_id, read_status) — unread count accounts(user_id) — dashboard load goals(user_id), investments(user_id) — profile loads ================================================================================ 10. API REFERENCE ================================================================================ Interactive Swagger UI: http://localhost:8000/docs All protected endpoints require: Authorization: Bearer CORE ENDPOINTS ────────────── GET /health Health check (no auth) GET /api/status Runtime: AI backend, DB type, version (no auth) GET /api/metrics Live observability dashboard (no auth) GET /docs Swagger UI AUTH ──── POST /api/auth/register Create account → JWT pair POST /api/auth/login Login (form-encoded) → JWT pair POST /api/auth/refresh Get new access token from refresh token GET /api/auth/me Current user profile PATCH /api/auth/settings Update name / preferences DASHBOARD ───────── GET /api/dashboard/overview Full dashboard data (cached 2 min) TRANSACTIONS ──────────── GET /api/transactions/ Paginated list (filter: category, type, page, limit) NOTIFICATIONS ───────────── GET /api/notifications/ List + unread count PATCH /api/notifications/{id}/read Mark read PATCH /api/notifications/read-all Mark all read DELETE /api/notifications/{id} Dismiss AI INTELLIGENCE ─────────────── GET /api/ai/coaching/score Health score (cached 10 min) GET /api/ai/coaching/briefing Daily AI briefing (cached 1 hr) GET /api/ai/behavior/insights Spending pattern analysis GET /api/ai/twin/predict 30-day balance forecast GET /api/ai/twin/future Long-term projection (?months=12) GET /api/ai/twin/scenarios Conservative/expected/optimistic GET /api/ai/fraud/analysis All fraud alerts GET /api/ai/fraud/explain/{id} AI explanation for one alert GET /api/ai/coach/weekly Weekly coaching report GET /api/ai/narrative/monthly Monthly financial narrative GET /api/ai/subscriptions/optimize Subscription cost analysis POST /api/ai/chat HTTP chat (non-streaming) WS /api/ai/chat/ws Streaming WebSocket chat POST /api/ai/simulate/purchase Impact of hypothetical purchase PAYMENTS ──────── POST /api/payments/create New payment (fraud-scored) POST /api/payments/transfer Internal account transfer GET /api/payments/history Payment list (filter: type, status) GET /api/payments/{id} Single payment detail POST /api/payments/verify Confirm or reject flagged payment DELETE /api/payments/{id} Cancel payment GOALS ───── GET /api/goals List goals + progress summary POST /api/goals/{id}/contribute Add contribution amount LOANS ───── POST /api/loans/eligibility ML loan eligibility prediction MEMORY (CHAT HISTORY) ───────────────────── GET /api/memory/history Chat history (all sessions) POST /api/memory/save Save a chat message DELETE /api/memory/clear Clear history (?session_id) GET /api/memory/preferences User preferences (theme, language) PATCH /api/memory/preferences Update preferences DOCUMENTS ───────── POST /api/documents/upload Upload + analyze (PDF/DOCX/TXT/CSV/image) POST /api/documents/chat/{id} Ask question about a document POST /api/documents/analyze/{id} Re-analyze existing document GET /api/documents/history Previously uploaded documents GET /api/documents/{id} Document + its chat history DELETE /api/documents/{id} Delete document ================================================================================ 11. DEPLOYMENT OPTIONS ================================================================================ OPTION A — Hugging Face Spaces (Current live deployment) ───────────────────────────────────────────────────────── The project uses a single Dockerfile with two build stages: Stage 1: node:20-slim → compiles Next.js standalone bundle Stage 2: python:3.11-slim → installs Python deps, copies Node output, installs Nginx + supervisord, sets up start.sh Pushing to the hf remote triggers automatic rebuild: git push hf hf-deploy2:main → HF detects new SHA, builds Docker image (~5 min) → Container starts, runs start.sh → start.sh: initializes DB, seeds demo data if empty, starts supervisord → supervisord: starts Nginx + FastAPI + Next.js Live URL: https://mohsin-devs-bankbot.hf.space/ OPTION B — Vercel (frontend) + Render (backend) ──────────────────────────────────────────────── Frontend to Vercel: cd frontend npx vercel --prod Set env: NEXT_PUBLIC_API_URL=https://your-backend.onrender.com Backend to Render: 1. Push to GitHub 2. Render.com → New Web Service → connect repo 3. Render reads backend/render.yaml (auto-detects config) 4. Set secrets: GROQ_API_KEY, JWT_SECRET_KEY 5. Render provisions PostgreSQL + Redis from render.yaml OPTION C — Full Docker Compose ──────────────────────────────── docker compose up -d docker compose exec backend python app/scripts/seed_demo.py Open: http://localhost:3000 PERSISTENT DATABASE ──────────────────── Default SQLite resets on HF Space restart. For persistence: Option Cost Setup ────────────────────────────────────────────────────── SQLite Free None (default, resets on restart) Neon Free tier Set DATABASE_URL in HF Secrets Supabase Free tier Set DATABASE_URL in HF Secrets Render PG Free tier Auto via render.yaml Neon connection string format: postgresql://user:pass@ep-xxx.neon.tech/bankbot?sslmode=require ================================================================================ 12. USE CASES ================================================================================ 1. PORTFOLIO / VIVA DEMONSTRATION Primary use case. Shows end-to-end full-stack development: - Database design (ER diagram, indexes, relationships) - REST + WebSocket API design - JWT authentication with refresh token rotation - LLM integration with fallback chains - Docker multi-stage containerization - CI/CD pipeline (GitHub Actions) - Production-quality UI with theme system For a viva, deep-dive topics available: - Walk through the fraud detection scoring algorithm - Explain the 4-tier AI fallback chain - Show the caching strategy and TTL choices - Demo the Docker multi-stage build and why standalone output matters - Walk through the JWT refresh flow in api.ts - Explain CSS custom properties for theming 2. LEARNING FULL-STACK AI DEVELOPMENT Each module is isolated and commented: - Study just auth (app/auth/router.py + stores/authStore.ts) - Study just WebSocket streaming (app/websocket/router.py) - Study just Zustand state management (lib/stores/) - Study just the AI context injection (app/ai/chat.py) 3. FINTECH STARTER TEMPLATE The backend routers, models, JWT flow, and AI orchestration can be adapted for real financial tools. Especially reusable: - 4-tier AI fallback pattern - Cache-aside with per-key TTLs - Fraud scoring algorithm structure 4. AI CHATBOT ARCHITECTURE REFERENCE The pattern of injecting live database context into LLM prompts (vs RAG or fine-tuning) is practical for domain chatbots. BankBot shows a clean implementation with streaming. 5. PRODUCT DEMO / PITCH MOCKUP Polished UI + realistic data + instant AI responses make it effective for showing stakeholders what a modern banking interface with AI could look like, without building a real bank. ================================================================================ 13. HOW BANKBOT DIFFERS FROM REAL-WORLD BANKING APPS ================================================================================ This is the most important section. BankBot is a realistic simulation, NOT a production banking system. WHAT BANKBOT DOES THAT REAL BANKS DO ────────────────────────────────────── Feature BankBot Real Bank ────────────────────────────────────────────────────────────────────────── JWT authentication Full implementation OAuth2 / proprietary SSO Transaction history Paginated, filterable Same concept Financial health score Rule-based 100-pt system Credit score (CIBIL, FICO) Fraud detection Rule-based scoring ML models + human review Goal tracking Progress + AI plan Savings goals / pots Multi-language support EN / HI / MR Varies by region API-first architecture REST + WebSocket Open Banking APIs Dark/light theme Full CSS variable system Most modern apps WHERE BANKBOT FUNDAMENTALLY DIFFERS ───────────────────────────────────── Area BankBot Real Banking System ────────────────────────────────────────────────────────────────────────────────── Money movement Simulated — no fund transfer Real money, PCI-DSS, RBI/FCA regulations Identity verification Email + password only KYC: ID docs, face match, address verification Data persistence SQLite resets on HF restart ACID PostgreSQL clusters, automated backups, DR AI advice Informational only, no license Licensed financial advisors, fiduciary duty, SEBI rules Security audit Basic JWT + bcrypt, no pentest SOC 2, ISO 27001, annual audits Scale 1 container, ~100 concurrent Kubernetes, load balancers, users max millions of users Transaction data Seeded synthetic demo data Real bank transaction feeds via Plaid / direct API Fraud ML 4 heuristic rules Deep learning on billions of transactions Payments Fake records, no actual routing SWIFT, NEFT, RTGS, UPI, IMPS real settlement Regulatory compliance None RBI, FCA, OCC, FDIC Investment data Static seeded values Real-time market data feeds (Bloomberg, NSE, BSE) Notifications In-app only SMS, email, push via Twilio / Firebase WHAT BANKBOT DOES THAT IS GENUINELY PRODUCTION-QUALITY ──────────────────────────────────────────────────────── These patterns are used in real production systems: ✅ 4-tier AI fallback chain — same pattern in production LLM apps ✅ Cache-aside with per-endpoint TTLs — standard Redis pattern ✅ JWT access + refresh token rotation — same as real OAuth2 ✅ WebSocket with heartbeat + exponential backoff reconnect ✅ Multi-stage Docker build with Next.js standalone output ✅ Structured JSON logging with request-id tracing ✅ Middleware stack order: CORS → rate limit → auth → handler ✅ Alembic migrations — same tool used in production Python backends ✅ pydantic-settings for environment variable validation ✅ SQLAlchemy 2.0 with async-compatible session patterns ================================================================================ 14. KNOWN LIMITATIONS ================================================================================ Limitation Current State Production Fix ────────────────────────────────────────────────────────────────────────────── Data resets SQLite on HF resets on restart DATABASE_URL → Neon/Supabase Single worker 1 Uvicorn worker on HF Multiple workers + Gunicorn No real-time market data Investment values are static Alpha Vantage / Polygon.io WS No email/SMS alerts Notifications are in-app only Twilio SMS, SendGrid email No 2FA Email + password only TOTP, SMS OTP AI rate limits Groq free: 30 req/min Paid tier, multiple API keys No audit log User actions not logged Append-only audit table No account linking Demo data only Plaid / Open Banking API Image OCR quality Tesseract can fail on low-res Google Vision / AWS Textract No real-time prices Investment P&L uses seed data NSE/BSE / Yahoo Finance API ================================================================================ 15. PROJECT STRUCTURE ================================================================================ BankBot New/ │ ├── Dockerfile Single-container build (HF Spaces) ├── docker-compose.yml Multi-service local/prod deployment ├── .env.example All environment variables documented ├── run.bat Windows quick-start script │ ├── hf/ │ ├── nginx.conf Nginx reverse proxy (port 7860 → 3000/8000) │ ├── supervisord.conf Process manager (Nginx + FastAPI + Next.js) │ └── start.sh Container startup: DB init → seed → supervisord │ ├── backend/ │ ├── requirements.txt All Python dependencies (pinned versions) │ ├── alembic.ini DB migration config │ ├── alembic/ Migration scripts │ └── app/ │ ├── main.py FastAPI app factory + middleware stack │ ├── ai/ │ │ ├── chat.py Context injection + AI provider chain │ │ ├── router.py /api/ai/* endpoints │ │ ├── coaching.py Health score + daily briefing │ │ ├── fraud.py Fraud scoring algorithm │ │ ├── forecasting.py Balance prediction │ │ ├── behavior.py Spending pattern analysis │ │ ├── simulation.py What-if engine │ │ ├── subscriptions.py Subscription optimization │ │ ├── ollama_integration.py Ollama + Groq + OpenAI wrappers │ │ └── loan_predictor.py ML loan eligibility │ ├── auth/router.py JWT auth (register/login/refresh/me) │ ├── dashboard/router.py Dashboard aggregation endpoint │ ├── transactions/router.py Transaction CRUD │ ├── payments/ Payment processing + fraud scoring │ ├── goals/router.py Goal tracking + contributions │ ├── loans/ Loan eligibility endpoint │ ├── documents/ │ │ ├── router.py Upload/chat/history endpoints │ │ └── service.py Text extraction + AI analysis │ ├── memory/router.py Chat history persistence │ ├── notifications/router.py Notification CRUD │ ├── websocket/router.py Streaming WebSocket chat │ ├── database/ │ │ ├── database.py SQLAlchemy engine + session + auto-fallback │ │ ├── models.py All SQLAlchemy models │ │ └── chat_migrate.py Chat schema migration helper │ ├── middleware/ │ │ ├── cache.py Redis → in-memory fallback cache │ │ └── logging.py Structured JSON logger + metrics collector │ └── scripts/ │ └── seed_demo.py Demo account seeder (idempotent) │ ├── frontend/ │ ├── next.config.mjs Standalone output, API rewrites, security headers │ ├── tailwind.config.ts CSS variable color tokens │ └── src/ │ ├── app/ Next.js App Router │ │ ├── page.tsx Dashboard │ │ ├── chat/page.tsx AI Assistant (doc upload integrated) │ │ ├── analytics/ Spending intelligence │ │ ├── simulator/ What-If engine │ │ ├── transactions/ Transaction history │ │ ├── payments/ Payment management │ │ ├── goals/ Goal tracking │ │ ├── loans/ Loan eligibility │ │ ├── security/ Fraud alerts │ │ ├── settings/ User preferences │ │ ├── status/ System observability │ │ ├── docs/ This documentation page │ │ ├── login/ Auth page │ │ ├── documents/ Redirects to /chat │ │ └── globals.css CSS variables (dark/light), utilities │ ├── components/ │ │ ├── layout/ │ │ │ ├── AppShell.tsx Auth guard + theme/lang sync │ │ │ ├── DashboardLayout.tsx Sidebar + Navbar + main │ │ │ ├── Sidebar.tsx Navigation + theme/lang controls │ │ │ └── Navbar.tsx Search + notifications + user │ │ ├── notifications/ │ │ │ └── NotificationPanel.tsx Bell + dropdown panel │ │ └── ui/ Shadcn primitives │ └── lib/ │ ├── api.ts Typed fetch client (all endpoints) │ ├── utils.ts cn() tailwind merge helper │ └── stores/ │ ├── authStore.ts JWT tokens + user session │ ├── themeStore.ts Dark/light + DOM sync │ ├── languageStore.ts EN/HI/MR translations │ └── dashboardStore.ts Dashboard data + 2-min cache │ └── docs/ ├── BANKBOT_DOCUMENTATION.txt ← This file ├── ARCHITECTURE.md ├── API_DOCUMENTATION.md ├── DEPLOYMENT_GUIDE.md └── ER_DIAGRAM.md ================================================================================ END OF DOCUMENTATION BankBot AI — Built with FastAPI + Next.js ================================================================================