Technical Requirements Document #

TRD v1.0 · ronilprasad8.tech · Full-Stack Portfolio & AI Assistant Platform

1. System Architecture Overview #

The application employs a resilient, high-throughput, hybrid client-server architecture built on Python Flask and modern ES6+ web standards, deployable across serverless environments. The backend orchestrates a multi-tiered concurrency pipeline, multi-key round-robin client pools, in-flight failover, and real-time token streaming to deliver low-latency interactions for "The GOAT" AI assistant.

Client (Browser) UI & Auth (HTML/JS) Firebase Auth Tokens SSE Stream Consumer ReadableStreamReader 60fps Adaptive Typewriter Dynamic Markdown UI Backend (Vercel / Flask) Auth & Rate Limiter JWT / HMAC + Sliding Window Parallel Pre-Fetch (3 Workers) Firestore Facts + Memory + Sports Intent Gate & Tag Sanitizer Selective Intro + StreamTagFilter Strip Tags / Filter Intros Multi-Key Round-Robin Engine Gemini Pool <-> Groq Pool 1.2s Speculative Timeout / 429 Failover Async Background Executor Audit Logs & Learned Memory External Services & Key Pools Firebase Auth / Firestore User Profiles & Messages Gemini Multi-Key Pool gemini-3.6-flash Atomic Round-Robin Groq Multi-Key Pool openai/gpt-oss-120b In-Flight 429 Failover (<50ms) Live Match Daemon Cache Background Pre-Warmed (<1ms) POST /chat SSE Chunks

2. Technology Stack #

Dependency / ToolVersionPurposeSource
Flask 3.1.3 Core backend web framework & routing engine. requirements.txt
groq 1.1.2 Primary ultra-low latency LLM inference engine (openai/gpt-oss-120b) with multi-key round-robin client pool and in-flight HTTP 429 failover (<50ms). requirements.txt
google-genai 1.72.0 Secondary high-reasoning fallback engine (gemini-2.5-flash) supporting multi-key round-robin client pools and automatic zero-downtime failover. requirements.txt
concurrent.futures Python Built-in Multi-threaded parallel pre-fetching (ThreadPoolExecutor(max_workers=3)) for Firestore facts, memory, and match caches, plus async daemon logging (_bg_executor). Python Standard Library
Server-Sent Events (SSE) W3C Standard Real-time chunked token streaming protocol (text/event-stream) driving the frontend 60fps typewriter engine. HTTP/1.1 Protocol
Firebase JS SDK 11.0.1 (Unified) Client-side authentication and Firestore database access. templates/, static/js/ & package.json
python-dotenv 1.2.2 Loads environment variables from .env file (local dev). requirements.txt
@vercel/speed-insights 2.0.0 Web performance tracking. package.json
Gunicorn 25.3.0 WSGI HTTP Server for production deployment. requirements.txt

3. Project Structure #

ronilprasad8/
β”œβ”€β”€ .env                  # Environment variables (Keys: Gemini, Groq, Firebase)
β”œβ”€β”€ .github/              # GitHub Actions workflows / config (if any)
β”œβ”€β”€ CV/                   # Stores static CV.pdf
β”œβ”€β”€ app.py                # Main Flask application entrypoint & routing
β”œβ”€β”€ chatbot.py            # AI Engine logic (Failover, context injection)
β”œβ”€β”€ documentation/        # Project documentation hub (SRS, PRD, TRD, etc.)
β”œβ”€β”€ package.json          # Node dependencies (Vercel speed insights, Firebase)
β”œβ”€β”€ requirements.txt      # Python backend dependencies
β”œβ”€β”€ sitemap.xml           # Static SEO sitemap
β”œβ”€β”€ static/               # Client-side assets
β”‚   β”œβ”€β”€ css/              # Application stylesheets
β”‚   β”œβ”€β”€ js/               # Client scripts (chatbot.js)
β”‚   └── images/           # Badges, icons, hero images
β”œβ”€β”€ templates/            # Jinja2 HTML views (index, about, chat, etc.)
β”œβ”€β”€ vercel.json           # Vercel deployment and serverless build configuration
└── workflows/            # Additional pipeline or task definitions

4. APIs & Endpoints #

MethodPathArchitectural HandlerPurpose & Security Boundary
GET / app:index Renders index.html (Portfolio Landing). Public.
GET /about app:about Renders about.html. Public.
GET /project app:project Renders project.html. Public.
GET /contact app:contact Renders contact.html (Secure contact interface). Public.
POST /contact app:contact Processes contact form submissions with honeypot bot filtering, sliding-window IP rate limiting (5 req/10 min), sanitization, and async Firestore persistence.
GET /login app:login Renders login.html (Firebase Authentication flow). Public.
GET /cv app:view_cv Serves international ATS-compliant Western CV (CV_Western.pdf) by default; serves regional format via ?format=regional.
GET /architecture app:architecture Renders dedicated architecture.html showcase page (failover pipeline, zero-trust security architecture, and system diagrams). Dedicated server-rendered route.
GET /privacy app:privacy Renders privacy.html (Privacy Policy & Terms of Service). Public.
GET /chat app:chat Renders dedicated chat.html conversational interface. Public.
POST /chat app:chat Dual-Protocol AI Inference & Streaming Gateway:
  • Security & Rate Limiting: Cryptographically validates Authorization Bearer token (RSA-256 Firebase JWT or HMAC SHA-256 guest token). Enforces tiered sliding-window rate limiting (5 req/min guest, 15 req/min authenticated).
  • Concurrent Pre-Fetch: Runs parallel retrieval of Firestore global knowledge facts, episodic memory, and cached sports data via ThreadPoolExecutor(max_workers=3) (<200ms).
  • Context-Aware Output Governance: Detects user query intent to route between conversational dialogue and direct technical answers, eliminating conversational noise for focused technical requests.
  • Multi-Key Round-Robin & Failover: Dispatches across pooled keys for Gemini and Groq. Enforces a 1.2s speculative TTFT window on primary Gemini with instant Groq fallback, plus in-flight HTTP 429 failover (<50ms) to adjacent pool keys.
  • Streaming Protocol (SSE): When requested with Accept: text/event-stream, returns text/event-stream; charset=utf-8 yielding progressive chunks (data: {"chunk": "..."}\n\n) sanitized in real time via StreamTagFilter. Falls back to standard JSON (application/json) for legacy clients.
  • Non-Blocking Async Audit: Offloads message logging, trigger updates, and learned memory extraction to a daemon background worker (_bg_executor) with 0ms delay on the stream.
POST /api/guest-session app:guest_session Mints an ephemeral HMAC SHA-256 signed guest session token for zero-friction interactive preview.
GET /api/chat/history app:get_chat_history Retrieves conversation history for authenticated user UID. Requires valid Bearer JWT.
GET /sitemap.xml app:sitemap Serves generated XML sitemap for search engine crawlers.
GET /google[id].html app:google_verify Serves Google Search Console domain verification.

5. Threat Model & Architectural Transparency Policy #

Intentional Security Model (Kerckhoffs's Principle & NIST Open Architecture): The platform's operational architecture is intentionally documented as a public reference implementation. Security guarantees rely strictly on cryptographic primitives, strict server-side authorization enforcement, and defensive data sanitization, never on security through obscurity.

Defensive LayerImplementation MechanismSecurity Rationale
Authentication RSA-256 Google ID token verification & HMAC SHA-256 guest session signatures. Guarantees identity authenticity at the server boundary without trusting client assertions.
Rate Throttling Tiered sliding-window in-memory throttling (5 req/min guest, 15 req/min authenticated). Shields upstream LLM endpoints (Gemini / Groq) against denial-of-wallet and scraper exhaustion.
Knowledge Gating Strict owner-only gating (verified administrative identity) and confirmation review queues. Prevents visitors or prompt injection attacks from planting false claims in persistent portfolio memory.
Contact Privacy Server-side contact form with hidden honeypot field and IP throttling replacing raw mailto: and tel: links. Protects personal phone and email addresses from automated scrapers and spam harvesting.
Configuration Schema Environment variable specifications documented publicly; secrets stored exclusively in platform vaults. Separates functional interface documentation from runtime secrets management.

Environment Variable Schemas

Variable NameClassificationFunctional Description
GEMINI_API_KEY Secret (Vault) Google Gemini API key(s) enabling primary LLM reasoning. Supports comma-separated keys (key1,key2,...) parsed into a singleton client pool with atomic round-robin dispatch and a 1.2s speculative TTFT window.
GROQ_API_KEY Secret (Vault) Groq platform API key(s) powering openai/gpt-oss-120b. Supports comma-separated keys (key1,key2,key3,...) parsed into a thread-safe client pool with synchronized round-robin rotation and automatic in-flight HTTP 429 failover (<50ms).
FIREBASE_API_KEY Public (Client Config) Public client initialization key injected server-side into Jinja templates.
GUEST_SECRET_KEY Secret (Vault) Server-side secret used to sign and verify ephemeral HMAC guest session tokens.

6. Deployment & Build Process #

Deployment is managed through Vercel via continuous integration from a connected GitHub repository.

// vercel.json
{
  "version": 2,
  "builds": [
    { "src": "app.py", "use": "@vercel/python" }
  ],
  "routes": [
    { "src": "/(.*)", "dest": "app.py" }
  ]
}

7. Third-Party Integrations #


8. Technical Constraints & Dependencies #