Spaces:
Build error
Build error
File size: 12,629 Bytes
a282d4b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | # 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:
```python
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)
```
|