Spaces:
Build error
Build error
BankBot AI β System Architecture
1. High-Level Architecture
βββββββββββββββββββββββββββββββββββ
β CLIENT BROWSER β
β Next.js 14 (React, TypeScript) β
β β
β Pages: β
β / Dashboard β
β /chat AI Assistant (WS) β
β /analytics Spending Intel β
β /simulator What-If Engine β
β /transactions History β
β /status Observability β
ββββββββββββββββ¬ββββββββββββββββββββ
β HTTPS / WSS
ββββββββββββββββΌββββββββββββββββββββ
β NGINX REVERSE PROXY β
β β’ TLS termination β
β β’ Rate limiting (30r/m API) β
β β’ Auth rate limit (10r/m) β
β β’ WebSocket upgrade proxy β
β β’ Static asset caching β
ββββββββββββ¬βββββββββββββ¬βββββββββββ
β β
ββββββββββββββββββββββΌβββ ββββββββΌβββββββββββββββββββ
β FastAPI Backend β β Next.js Standalone β
β Python 3.11 β β Node.js 20 β
β Uvicorn (2 workers) β β Port 3000 β
β Port 8000 β ββββββββββββββββββββββββββββ
β β
β Routers: β
β /api/auth β
β /api/dashboard β
β /api/ai/* β
β /api/ai/chat/ws (WS) β
β /api/transactions β
β /api/notifications β
β /api/metrics β
ββββββββ¬βββββββββ¬βββββββββ
β β
ββββββββββββββΌβββ ββββΌβββββββββββββββ
β PostgreSQL 15 β β Redis 7 β
β (Primary DB) β β (Cache Layer) β
β β β β
β Tables: β β Keys: β
β users β β dashboard:* β
β accounts β β ai:coaching:* β
β transactions β β ai:behavior:* β
β goals β β ai:twin:* β
β investments β β ai:subs:* β
β subscriptions β β β
β notifications β β TTLs: β
β fraud_logs β β dashboard: 2min β
β ai_insights β β score: 10min β
β analytics_ β β briefing: 1hr β
β snapshots β ββββββββββββββββββββ
ββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββββββββββββββββ
β AI ORCHESTRATION LAYER β
β β
β Priority Chain: β
β 1. OpenAI (gpt-4o-mini) β fastest β
β β if unavailable β
β 2. Groq (llama-3.3-70b) β free tier β
β β if unavailable β
β 3. Ollama (llama3:latest) β local β
β β if unavailable β
β 4. Rule-based fallback β always on β
β β
β Modules: β
β β’ chat.py β contextual chat β
β β’ coaching.py β health score β
β β’ forecasting.py β balance prediction β
β β’ simulation.py β what-if engine β
β β’ fraud.py β anomaly detection β
β β’ behavior.py β spending patterns β
β β’ subscriptions.py β sub optimization β
βββββββββββββββββββββββββββββββββββββββββββ
2. Data Flow β Dashboard Load
Browser Next.js FastAPI DB/Cache
β β β β
βββ GET / β β β
β βββ fetch /api/ β β
β β dashboard/ β β
β β overview β β
β β βββ check cache βββΊ β
β β ββββ cache miss ββ β
β β βββ query accounts β
β β βββ query txns β
β βββ JSON response ββββββ query fraud β
ββββ render dashboard βββ βββ set cache(2min) β
β β β β
β [2nd request] β β β
β βββ fetch /api/ β β
β β dashboard/ β β
β β overview β β
β β βββ check cache βββΊ β
β β ββββ cache HIT βββ β
ββββ render (22ms) βββββββββ JSON (22ms) βββββ β
3. Data Flow β WebSocket Chat
Browser FastAPI AI Backend
β β β
βββ WS connect ββββββββββΊ β
ββββ WS accepted βββββββββ β
β β β
βββ { type: "chat", β β
β message: "..." } βββΊβ β
β βββ build context βββΊβ
β β (user profile, β
β β history, goals) β
β β βββ stream tokens
ββββ { type: "chat_start" } β
ββββ { type: "chat_chunk", content: "He" } β
ββββ { type: "chat_chunk", content: "re" } β
ββββ { type: "chat_chunk", content: " is" } β
β ... (streaming) β
ββββ { type: "chat_end" } β
β β β
βββ { type: "ping" } ββββΊβ (heartbeat 25s) β
ββββ { type: "pong" } ββββ β
4. AI Context Construction
Every chat message is enriched with full user financial context:
system_prompt = f"""
You are BankBot, an elite AI Financial Analyst.
CURRENT USER PORTFOLIO:
- Name: {user.name}
- Financial Personality: {user.financial_personality}
- Health Score: {score}/100
- Total Balance: ${total_balance:,.2f}
- Accounts: {account_details}
- Goals: {goals_details}
- Investments: {investments_details}
- Subscriptions: {subs_details}
- Behavioral Insights: {behavior_insights}
PRINCIPLES:
1. Never give generic advice β use real numbers
2. Respond like a Bloomberg Terminal analyst
3. Keep answers brief, actionable, financially meaningful
"""
5. Fraud Detection Algorithm
Transaction received
β
βΌ
βββββββββββββββββββββββββββββββββ
β Load last 30 transactions β
β for this user β
βββββββββββββββββ¬ββββββββββββββββ
β
βββββββββΌβββββββββ
β Amount spike? β > 3.5x avg β +40 pts
β β > 2.0x avg β +20 pts
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Timing anomaly?β 11PMβ4AM β +25 pts
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Rapid fire? β < 3 min gap β +20 pts
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Duplicate? β Same merchant+amount
β β within 10 min β +30 pts
βββββββββ¬βββββββββ
β
βββββββββΌβββββββββ
β Score β₯ 30? β β Log to fraud_logs
β Score β₯ 50? β β Status: "flagged"
β Score < 30? β β Status: "verified"
ββββββββββββββββββ
6. Caching Strategy
| Data | Cache Key | TTL | Reason |
|---|---|---|---|
| Dashboard overview | dashboard:overview:{uid} |
2 min | High-frequency, DB-heavy |
| AI health score | ai:coaching:score:{uid} |
10 min | AI call expensive |
| AI daily briefing | ai:coaching:briefing:{uid} |
1 hr | LLM cost control |
| Behavior insights | ai:behavior:insights:{uid} |
10 min | Computation heavy |
| Twin prediction | ai:twin:predict:{uid} |
5 min | Moderate cost |
| Subscriptions | ai:subs:optimize:{uid} |
10 min | Stable data |
Cache backend: Redis β in-memory dict fallback (automatic, no config needed).
7. Security Architecture
Request β Nginx (rate limit) β FastAPI middleware stack:
1. Rate limiter (120 req/min per IP)
2. Security headers (X-Frame-Options, CSP, etc.)
3. Request logger (structured JSON)
4. Process time header
5. CORS validation
6. Route handler
βββ JWT validation (if protected route)
βββ Business logic
βββ DB query / AI call / Cache lookup
JWT Flow:
Login β access_token (60min) + refresh_token (7 days)
β
βΌ
Request with Authorization: Bearer {access_token}
β
βΌ
Token expired? β POST /api/auth/refresh with refresh_token
β
βΌ
New access_token issued (refresh_token unchanged)
β
βΌ
Logout β client clears tokens (stateless)
8. Deployment Architecture
Internet
β
βΌ
Cloudflare (DNS + DDoS protection)
β
βΌ
Nginx (SSL termination, rate limiting)
β
ββββΊ Next.js Frontend (Vercel / Docker port 3000)
β
ββββΊ FastAPI Backend (Render / Docker port 8000)
β
ββββΊ PostgreSQL (Render managed / Docker)
ββββΊ Redis (Render managed / Docker)
ββββΊ AI Provider (OpenAI API / Groq API)