"use client"; import { useState } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { BookOpen, ChevronRight, Terminal, Cpu, Zap, Shield, BarChart2, Globe, Server, Database, Code2, GitBranch, Layers, AlertTriangle, CheckCircle2, ArrowRight, Building2, Sparkles, Lock, Activity, FileText, MonitorSmartphone, Wifi, RefreshCw, Target, } from "lucide-react"; import { useThemeStore } from "@/lib/stores/themeStore"; // ─── Section types ──────────────────────────────────────────────────────────── interface Section { id: string; icon: React.ElementType; label: string; color: string; } const SECTIONS: Section[] = [ { id: "overview", icon: BookOpen, label: "Overview", color: "text-emerald-500" }, { id: "quickstart", icon: Terminal, label: "Quick Start", color: "text-blue-500" }, { id: "how-it-works", icon: Cpu, label: "How It Works", color: "text-purple-500" }, { id: "tech-stack", icon: Layers, label: "Tech Stack", color: "text-amber-500" }, { id: "features", icon: Zap, label: "Features", color: "text-cyan-500" }, { id: "architecture", icon: Server, label: "Architecture", color: "text-orange-500" }, { id: "ai-engine", icon: Sparkles, label: "AI Engine", color: "text-pink-500" }, { id: "security", icon: Shield, label: "Security", color: "text-red-500" }, { id: "database", icon: Database, label: "Database & Models", color: "text-teal-500" }, { id: "api", icon: Code2, label: "API Reference", color: "text-violet-500" }, { id: "deployment", icon: Globe, label: "Deployment", color: "text-lime-500" }, { id: "use-cases", icon: Target, label: "Use Cases", color: "text-sky-500" }, { id: "vs-real-world", icon: Building2, label: "vs Real Banking Apps", color: "text-rose-500" }, { id: "limitations", icon: AlertTriangle, label: "Limitations", color: "text-yellow-500" }, ]; // ─── Helpers ────────────────────────────────────────────────────────────────── function H1({ children }: { children: React.ReactNode }) { return

{children}

; } function H2({ children, id }: { children: React.ReactNode; id?: string }) { return

{children}

; } function H3({ children }: { children: React.ReactNode }) { return

{children}

; } function P({ children }: { children: React.ReactNode }) { return

{children}

; } function Code({ children }: { children: React.ReactNode }) { return ( {children} ); } function CodeBlock({ children, lang = "bash" }: { children: string; lang?: string }) { const { theme } = useThemeStore(); const isLight = theme === "light"; return (
{["#ff5f57","#febc2e","#28c840"].map((c) => (
))} {lang}
{children}
); } function Table({ headers, rows }: { headers: string[]; rows: string[][] }) { return (
{headers.map((h) => ( ))} {rows.map((row, i) => ( {row.map((cell, j) => ( ))} ))}
{h}
{cell}
); } function Badge({ children, color }: { children: React.ReactNode; color: string }) { return ( {children} ); } function InfoBox({ icon: Icon, title, children, color }: { icon: React.ElementType; title: string; children: React.ReactNode; color: string }) { return (
{title}
{children}
); } // ─── Content sections ───────────────────────────────────────────────────────── function SectionOverview() { return (

BankBot AI — Documentation

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 with a real AI layer on top — real-time chat, fraud detection, forecasting, and document analysis — all running in a single Docker container on Hugging Face Spaces.

The project demonstrates how to architect a full-stack AI application with a FastAPI backend, a Next.js 14 frontend, multi-provider LLM fallback chains, JWT authentication, WebSocket streaming, and a glassmorphism UI — deployable anywhere from a local machine to cloud platforms.

{[ { icon: MonitorSmartphone, label: "Next.js 14 Frontend", sub: "TypeScript · Tailwind · Framer Motion", color: "text-blue-500", bg: "bg-blue-500/10 border-blue-500/20" }, { icon: Server, label: "FastAPI Backend", sub: "Python 3.11 · SQLAlchemy · JWT", color: "text-emerald-500", bg: "bg-emerald-500/10 border-emerald-500/20" }, { icon: Sparkles, label: "4-Tier AI Chain", sub: "OpenAI → Groq → Ollama → Rules", color: "text-purple-500", bg: "bg-purple-500/10 border-purple-500/20" }, ].map((item) => (

{item.label}

{item.sub}

))}

Demo Account

{`Email: alex@bankbot.dev Password: BankBot2026! Pre-loaded data: • $59,637 across 3 accounts (checking · savings · investment) • 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)`}
); } function SectionQuickStart() { return (

Quick Start

Three ways to run BankBot AI — pick whichever fits your situation.

Option 1 — Hugging Face (No setup)

The easiest option. Just open the link and log in with the demo credentials.

https://mohsin-devs-bankbot.hf.space/
AI backend: Groq (llama-3.3-70b) · DB: SQLite · Cache: in-memory

Option 2 — Local Development

Requires Python 3.11+ and Node.js 18+. Run these once:

{`# 1. Clone the repo git clone https://github.com/mohsinkp02/Bankbot-AI.git cd Bankbot-AI # 2. Backend setup cd backend python -m venv venv venv\\Scripts\\activate # Windows # source venv/bin/activate # macOS / Linux pip install -r requirements.txt # 3. Configure environment (copy example and edit) copy .env.example .env # Open .env and add at minimum: # GROQ_API_KEY=gsk_... ← free at console.groq.com # JWT_SECRET_KEY=any-long-random-string # 4. Seed demo data python app/scripts/seed_demo.py # 5. Start backend (keep this terminal open) uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload`} {`# 6. In a NEW terminal — frontend setup cd frontend npm install --legacy-peer-deps npm run dev`} {`Then open: Frontend → http://localhost:3000 API Docs → http://localhost:8000/docs Metrics → http://localhost:8000/api/metrics Health → http://localhost:8000/health`}

Option 3 — Docker Compose

Runs everything (Nginx + FastAPI + Next.js + SQLite) in containers.

{`# 1. Copy and configure environment copy .env.example .env # Add GROQ_API_KEY and JWT_SECRET_KEY # 2. Build and start docker compose up -d # 3. Seed demo data docker compose exec backend python app/scripts/seed_demo.py # 4. Open http://localhost:3000 # Stop docker compose down`}

Environment Variables Reference

); } function SectionHowItWorks() { return (

How It Works

BankBot AI is a full-stack monorepo with a clear separation of concerns. The frontend never talks directly to the database — everything goes through the FastAPI backend which handles auth, business logic, AI orchestration, and caching.

Request Lifecycle

{String.raw`User action (e.g. load dashboard) │ ▼ Next.js page component → calls dashboardApi.overview() → fetch("/api/dashboard/overview", { Authorization: Bearer }) │ ▼ ← Nginx routes /api/* to FastAPI FastAPI route handler → validates JWT token → checks Redis cache (key: "dashboard:overview:USER_ID") │ ┌─────┴──────┐ │ Cache HIT │ → returns JSON in ~10ms │ Cache MISS │ → queries SQLite/PostgreSQL └─────┬──────┘ accounts + transactions + goals + fraud_logs │ ▼ runs AI briefing (Groq → offline fallback) sets cache (TTL 2 min) returns JSON response │ ▼ React component receives data → renders dashboard with charts, cards, fraud shield`}

AI Chat Flow

The AI Assistant builds a full financial context prompt from the user's live data before every message — so it always knows your real balance, goals, and spending patterns.

{`User types "How much did I spend on food this month?" │ ▼ POST /api/ai/chat (with message + session_id + language) │ ▼ Backend fetches user's financial context: • accounts + balances • last 50 transactions • active goals + progress • investments • subscriptions • fraud alerts │ ▼ Builds system prompt: "You are BankBot. User Alex has $59,637 total. This month: Food $487.30 across 12 transactions. Top merchant: Chipotle ($143). ..." │ ▼ AI Provider chain: 1. OpenAI gpt-4o-mini (if OPENAI_API_KEY set) 2. Groq llama-3.3-70b (if GROQ_API_KEY set) ← HF demo uses this 3. Ollama llama3 (if running locally) 4. Rule-based fallback (always available) │ ▼ Response streamed back → saved to chat memory → displayed`}

Fraud Detection Flow

{`Every transaction is scored when it enters the system: Amount spike? >3.5x user avg → +40 pts >2.0x user avg → +20 pts Night timing? 11PM – 4AM → +25 pts Rapid-fire? <3 min gap → +20 pts Duplicate? same merchant + amount in 10 min → +30 pts │ Score ≥ 50 → status: "flagged" → notification created Score 30-49 → status: "suspicious" Score < 30 → status: "verified"`}

Caching Strategy

Cache backend: Redis → in-memory dict fallback. If Redis is not configured the app silently falls back to an in-process Python dict. No config change needed.

); } function SectionTechStack() { return (

Tech Stack

Frontend

Backend

Infrastructure

Why These Choices

Separating frontend and backend gives clean API contracts and allows each to be deployed independently (Vercel + Render) or together in Docker. The standalone output mode shrinks the Docker image by ~70% vs a full node_modules copy. SQLite needs zero infrastructure — perfect for demos, local dev, and HF Spaces. The same ORM code works with PostgreSQL in production with one env var change. No migration needed between environments. Groq's free tier runs llama-3.3-70b at 500+ tokens/second — fast enough for real-time streaming and free enough for a portfolio project. OpenAI is supported as priority 1 if a key is provided. ); } function SectionFeatures() { return (

Features

Dashboard

A single API call (GET /api/dashboard/overview) returns everything the dashboard needs: total balance, 4 stat cards, 6-month cash flow chart, category spending pie, 5 recent transactions, health score, and AI daily briefing. Cold: ~65ms. Cached: ~10ms.

AI Financial Twin

The AI assistant has full context of your finances injected into every prompt. It knows your actual balance, top spending categories, active goals, investments, and fraud alerts. It responds in English, Hindi, or Marathi depending on your language setting.

File attachment in chat: attach a PDF bank statement, CSV, DOCX invoice, or image directly in the chat input. The backend extracts text, runs an AI analysis, and you can ask questions about the document in the same conversation thread.

Fraud Detection

Rule-based scoring engine that evaluates every transaction on 4 dimensions: amount vs personal average, time-of-day, transaction velocity, and duplicate detection. Flagged transactions create notifications and appear in the Security page with AI explanations.

Financial Health Score

A 100-point composite score across 6 weighted dimensions: savings consistency (20pts), debt ratio (20pts), spending discipline (20pts), emergency fund coverage (20pts), investment diversification (10pts), subscription hygiene (10pts).

What-If Simulator

6 real-time sliders (income, rent, food, transport, entertainment, savings target) that generate an instant 36-month balance projection. Changes are calculated client-side for immediate feedback, with an AI commentary generated on demand.

Multi-Language UI

Full UI translation in English, Hindi, and Marathi. The AI assistant also responds in the selected language. The html lang attribute updates automatically on language change for proper browser accessibility support.

Dark / Light Mode

Full theme system built on CSS custom properties. Every surface — sidebar, navbar, cards, charts, tooltips, notifications — adapts cleanly between dark and light mode with a single DOM class toggle. Persisted to localStorage.

); } function SectionArchitecture() { return (

Architecture

Single-Container HF Deployment

{`Internet → HF Spaces (port 7860) │ ▼ Nginx (port 7860) ┌──────┴──────┐ ▼ ▼ Next.js (3000) FastAPI (8000) (frontend) (backend API) │ ┌────────┴────────┐ ▼ ▼ SQLite in-memory cache (auto-seeded) (Redis fallback)`}

Local / Docker Compose

{`Browser → localhost:3000 (Next.js) Browser → localhost:8000 (FastAPI) ← direct in dev mode Docker mode (docker compose up): nginx: localhost:80 → routes /api/* to fastapi, rest to nextjs fastapi: localhost:8000 nextjs: localhost:3000 postgres: localhost:5432 (optional, override with DATABASE_URL) redis: localhost:6379 (optional, override with REDIS_URL)`}

Directory Structure

{`BankBot New/ ├── Dockerfile # Single-container build (HF Spaces) ├── docker-compose.yml # Multi-service local/prod ├── hf/ │ ├── nginx.conf # Nginx reverse proxy config │ ├── supervisord.conf # Process manager config │ └── start.sh # Container startup script ├── backend/ │ ├── app/ │ │ ├── main.py # FastAPI app + middleware stack │ │ ├── ai/ # AI modules (chat, fraud, coaching, ...) │ │ ├── auth/ # JWT auth router │ │ ├── dashboard/ # Dashboard aggregation router │ │ ├── database/ # SQLAlchemy models + migrations │ │ ├── middleware/ # Logging, caching, rate limiting │ │ └── scripts/ # seed_demo.py │ └── requirements.txt └── frontend/ ├── src/ │ ├── app/ # Next.js App Router pages │ │ ├── page.tsx # Dashboard │ │ ├── chat/ # AI Assistant │ │ ├── analytics/ # Spending intelligence │ │ ├── simulator/ # What-If engine │ │ ├── security/ # Fraud alerts │ │ ├── settings/ # User preferences │ │ └── docs/ # This page │ ├── components/ │ │ ├── layout/ # Sidebar, Navbar, AppShell, DashboardLayout │ │ └── ui/ # Shadcn primitives │ └── lib/ │ ├── api.ts # Typed fetch client for all endpoints │ └── stores/ # Zustand: auth, theme, language, dashboard └── package.json`}
); } function SectionAIEngine() { return (

AI Engine

BankBot's AI layer is a 4-tier fallback chain with automatic provider detection. It never crashes — if all cloud providers fail, it falls back to a deterministic rule-based engine that still produces useful answers using real database data.

Provider Priority

{`1. OpenAI (gpt-4o-mini) if OPENAI_API_KEY is set ↓ on error / unavailable 2. Groq (llama-3.3-70b) if GROQ_API_KEY is set ↓ on error / unavailable 3. Ollama (llama3:latest) if Ollama running on localhost:11434 ↓ on error / unavailable 4. Rule-based fallback always available — uses real DB data`}

Context Injection

Before every chat message, the backend builds a system prompt from live user data:

{"system_prompt = f\"\"\"\nYou are BankBot, an elite AI Financial Analyst.\nALWAYS communicate in {language}.\n\nLIVE USER DATA:\n Name: {user.name}\n Personality: {user.financial_personality}\n Health Score: {score}/100\n Total Balance: ${total_balance:,.2f}\n Checking: ${checking:,.2f}\n Savings: ${savings:,.2f}\n Investment: ${investment:,.2f}\n\nMONTHLY ACTIVITY:\n Income: ${monthly_income:,.2f}\n Expenses: ${monthly_expenses:,.2f}\n Savings Rate: {savings_rate:.1f}%\n\nTOP SPENDING: {top_categories}\nACTIVE GOALS: {goals_summary}\nINVESTMENTS: {investments_summary}\nFRAUD ALERTS: {fraud_count} pending\n\nRULES:\n 1. Never give generic advice — use real numbers above\n 2. Keep answers concise and actionable\n 3. Respond in {language}\n\"\"\""}

Document Analysis

Files attached in the AI chat are uploaded to POST /api/documents/upload, which extracts text (PDF via pypdf + PyMuPDF + Tesseract OCR fallback, DOCX via python-docx, CSV row-by-row) and runs a structured analysis prompt. The extracted text is capped at 50,000 characters for storage and 6,000 characters per AI prompt to stay within token limits.

Streaming

The WebSocket endpoint (WS /api/ai/chat/ws) streams tokens from the AI provider as they arrive. The HTTP fallback (POST /api/ai/chat) returns the full response at once. The frontend simulates word-by-word streaming on HTTP responses using a 28ms interval.

); } function SectionSecurity() { return (

Security

Authentication Flow

{`POST /api/auth/login → validates email + bcrypt hash (rounds=12) → returns access_token (JWT, 60min) + refresh_token (JWT, 7 days) All protected requests: Authorization: Bearer → FastAPI verifies signature + expiry on every request Token expired? → POST /api/auth/refresh with refresh_token → returns new access_token (refresh_token unchanged) Frontend (api.ts): → auto-retry on 401: tries refresh, then clears tokens + redirects to /login`}

Middleware Stack

Every request passes through this stack before reaching a route handler:

{`1. Nginx — rate limit (30 req/min API, 10 req/min auth) 2. FastAPI — CORS validation (allowed origins from BACKEND_CORS_ORIGINS) 3. FastAPI — rate limiter (120 req/min per IP, in-process) 4. FastAPI — security headers: X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Referrer-Policy: strict-origin-when-cross-origin 5. FastAPI — request logger (structured JSON with request-id) 6. FastAPI — process-time header (X-Process-Time: 12.4ms) 7. Route — JWT validation (if protected) 8. Handler — business logic`} The HF demo uses an ephemeral JWT_SECRET_KEY generated at container start. This means sessions don't survive a container restart. Set a persistent JWT_SECRET_KEY in HF Secrets to fix this for real usage.
); } function SectionDatabase() { return (

Database & Models

BankBot uses SQLAlchemy 2.0 with auto-fallback: if DATABASE_URL points to PostgreSQL and the connection fails, it silently falls back to SQLite. All models work identically on both databases.

Core Models

Seed Data

Running python app/scripts/seed_demo.py creates the alex@bankbot.dev demo account with 160 realistic transactions across 6 months, all goals, investments, subscriptions, notifications, and one fraud alert. The script is idempotent — it deletes the existing demo user first, then re-creates everything clean.

); } function SectionAPI() { return (

API Reference

Interactive Swagger UI available at http://localhost:8000/docs when running locally. All protected endpoints require Authorization: Bearer {''}.

Core Endpoints

); } function SectionDeployment() { return (

Deployment

Hugging Face Spaces (Current)

The project deploys as a single Docker container to HF Spaces. The Dockerfile has two build stages: Node.js 20 compiles the Next.js standalone bundle, then a Python 3.11 slim image assembles the final runtime with Nginx, supervisord, Node, and all Python dependencies.

{`# Push to the hf remote triggers an automatic rebuild: git push hf hf-deploy2:main # HF detects the new SHA, builds the Docker image (~5 min), # then starts the container. Live URL: # https://mohsin-devs-bankbot.hf.space/`}

Vercel + Render (Split Deploy)

{`# Frontend → Vercel cd frontend npx vercel --prod # Set env var: NEXT_PUBLIC_API_URL=https://your-backend.onrender.com # Backend → Render # 1. Push to GitHub # 2. Render.com → New Web Service → connect repo # 3. Render reads backend/render.yaml automatically # 4. Set secrets: GROQ_API_KEY, JWT_SECRET_KEY # 5. Render provisions PostgreSQL + Redis from render.yaml`}

Persistent Database Options

); } function SectionUseCases() { return (

Use Cases

BankBot AI was built with specific audiences in mind. Here's who it's for and what they can do with it.

1. Portfolio Project / Viva Demonstration

The primary use case. The project demonstrates end-to-end full-stack development: database design, REST + WebSocket APIs, JWT auth, LLM integration with fallback chains, Docker containerization, CI/CD, and a production-quality UI.

For a college viva or technical interview, you can walk through: the ER diagram, the fraud detection algorithm, the AI context injection, the caching strategy, the Docker multi-stage build, or the theme system — each one a self-contained deep-dive topic.

2. Learning Full-Stack AI Development

The codebase is structured and commented as a learning resource. Each module is independent: you can study just the auth system, just the WebSocket streaming, or just the Zustand stores without needing to understand the whole system.

3. Starter Template for Fintech Projects

The backend routers, database models, JWT auth flow, and AI orchestration layer can be adapted for real financial tools. The 4-tier AI fallback chain is especially reusable — swap the financial domain prompts for any other domain.

4. AI Chatbot Architecture Reference

The pattern of injecting live database context into every LLM prompt (rather than relying on RAG or fine-tuning) is a practical technique for domain-specific chatbots. BankBot shows how to do this cleanly with SQLAlchemy + FastAPI + streaming responses.

5. Demo for Non-Technical Stakeholders

The polished UI, realistic data, and immediate AI responses make it effective as a product demo or mockup for fintech pitches — showing what a modern banking interface with AI could look like, without building a real bank.

); } function SectionVsRealWorld() { return (

BankBot vs Real Banking Apps

This is the most important section for understanding what BankBot is and what it isn't. It's a realistic simulation, not a production banking system.

What BankBot Does That Real Banks Do

Where BankBot Differs from Real Banking

BankBot AI is an educational demo. It does not handle real money, store real financial data, or provide regulated financial advice. AI responses are generated by a language model and may contain errors. Do not use it to make actual financial decisions.

What Makes BankBot Technically Interesting

Despite being a demo, several parts of BankBot reflect real production patterns:

{`✅ 4-tier AI fallback chain — same pattern used in production LLM apps ✅ Cache-aside with TTL per endpoint — standard Redis pattern ✅ JWT access + refresh token flow — same as real OAuth2 implementations ✅ WebSocket with heartbeat + auto-reconnect — production WS pattern ✅ Multi-stage Docker build — Next.js standalone output saves ~200MB ✅ Structured JSON logging with request-id — standard observability pattern ✅ Middleware stack order — CORS → rate limit → auth → handler ✅ Alembic migrations — same tool used in production Python backends ✅ pydantic-settings for env validation — standard FastAPI pattern`} ); } function SectionLimitations() { return (

Known Limitations

These are deliberate simplifications made to keep the project manageable as a portfolio piece. Each one has a note on how it would be addressed in production.

Reporting Issues

The GitHub repository is at{" "} github.com/mohsinkp02/Bankbot-AI . Open an issue for bugs or feature suggestions.

); } // ─── Section registry ───────────────────────────────────────────────────────── const SECTION_COMPONENTS: Record = { "overview": SectionOverview, "quickstart": SectionQuickStart, "how-it-works": SectionHowItWorks, "tech-stack": SectionTechStack, "features": SectionFeatures, "architecture": SectionArchitecture, "ai-engine": SectionAIEngine, "security": SectionSecurity, "database": SectionDatabase, "api": SectionAPI, "deployment": SectionDeployment, "use-cases": SectionUseCases, "vs-real-world": SectionVsRealWorld, "limitations": SectionLimitations, }; // ─── Main docs page ─────────────────────────────────────────────────────────── export default function DocsPage() { const { theme } = useThemeStore(); const isLight = theme === "light"; const [activeSection, setActiveSection] = useState("overview"); const ActiveComponent = SECTION_COMPONENTS[activeSection] ?? SectionOverview; return (
{/* ── Left nav ────────────────────────────────────────────────────────── */}
Documentation

BankBot AI v2.0

{/* ── Content ─────────────────────────────────────────────────────────── */}
{/* Mobile section picker */}
{SECTIONS.map((sec) => ( ))}
{/* Section breadcrumb */}
BankBot AI {SECTIONS.find(s => s.id === activeSection)?.label}
{/* Animated section content */} {/* Next section nav */}
{(() => { const idx = SECTIONS.findIndex(s => s.id === activeSection); const prev = SECTIONS[idx - 1]; const next = SECTIONS[idx + 1]; return ( <> {prev ? ( ) :
} {next ? ( ) :
} ); })()}
); }