Spaces:
Running
Running
| ================================================================================ | |
| 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 <jwt_token> | |
| 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 <access_token> | |
| β 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 <token> | |
| 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 | |
| ================================================================================ | |