Production Deep Dive: Targeted Context Routing β Neo4j Graph RAG & ADK Harness β Multi-Tenant RBAC & Privacy Defense β 7-Fold Autonomous SRE Closed Loop
Pure prompting causes LLMs to fabricate metrics and prices. Missing hard citations creates fatal legal and compliance risks.
Feeding all user stocks (20+ tickers) into a single prompt consumes 30k+ tokens, causing 12s+ latency and token waste.
Without database security rules and token masking, portfolios, webhooks, and private chat histories risk cross-user leakage.
Mixing unverified Reddit/X rumors with quantitative feeds without sanitization ruins research rigor and triggers false trades.
Multi-Turn Chat, ADK Tools & Targeted Routing
NVDA) and prunes other 18 stocks, slashing tokens by >80% (28k β 2.5k) and latency to 1.8s.High-Concurrency Quant Risk Fitting
Institutional-Grade Qualitative Research
sequenceDiagram
actor User as User (Business Query)
participant ADK as Google ADK Agent Harness
participant Gemini as Gemini 2.5 Flash Model
participant Engine as [ADK Tool] 17-Quarter TTM Engine
User->>ADK: "What is PATH's historical P/E valuation range over recent years?"
ADK->>Gemini: Inject Prompt & Registered Tools
Gemini->>ADK: Trigger Tool Call: get_stock_historical_valuations('PATH')
ADK->>Engine: Run data refinery engine, extract 17-quarter real TTM financial data
Engine-->>ADK: Return P/E 18.5x, P/B 3.2x, FCF Yield 6.51%
ADK->>Gemini: Feed authentic Tool Response back to model
Gemini-->>User: Output hallucination-free, rigorous structured answer
Neo4jGraphService inside neo4j_service.py.2-hop supply chain & customer relations (e.g., NVDA β SUPPLIED_BY β TSM β CUSTOMER_OF β ASML).request.auth.uid == userId.uid strictly from Google-signed JWT Bearer tokens; passing arbitrary user_id in body/query is rejected.stock_pools and macro_cache allow authenticated reads, but require Admin SDK writes.key=36a2****6987) and Discord (.../f0C3****q6tk) are masked in responses to prevent token exposure.****), backend preserves existing stored credentials.T10Y2Y), 10Y/2Y Yields, Fed Funds (FEDFUNDS), Core PCE, CPI, Nonfarm Payrolls, Unemployment Rate, Consumer Sentiment.. markers; attaches official release dates with 15-min TTL cache.β οΈ [Unverified Social Rumor] to prevent misinformation.Pydantic intercepts Gemini output; validation failures assemble Reflection Error Prompt for re-reasoning (up to 3 retries).
FMP failures trip breaker (CLOSED β OPEN), triggering seamless fallback to yfinance or Firestore cache.
Cloud Scheduler scans Firestore missing cache and executes Prewarm prior to report dispatch.
Scans past 30-day stock signals vs T+5 actual prices, calculating profit factor and emitting OPTIMAL/CRITICAL ratings.
FastAPI error interception connects to GCP Error Reporting and dispatches Discord alerts with fix suggestions.
Eliminates degenerate table delimiter loops and enforces 5-chunk caps with 0.35s sleep to prevent WeChat/Discord rate limits.
sequenceDiagram
autonumber
participant CS as GCP Cloud Scheduler
participant BE as Cloud Run Backend
participant CB as Circuit Breaker
participant FMP as FMP Primary API
participant Gemini as Gemini 2.5 Flash
participant Webhook as WeCom & Discord Webhooks
CS->>BE: 1. Trigger Pre-Market Briefing Job
BE->>CB: 2. Request Multi-Source Data
alt FMP Healthy
CB->>FMP: 3a. Query Quotes, Technicals & FRED Macro
FMP-->>CB: 4a. Return Verified Data
else FMP Fails 3x (Tripped to OPEN)
CB-->>BE: 3b. Fallback to yfinance / Firestore Cache
end
BE->>Gemini: 5. Targeted Context Routing & Anti-Hallucination Prompt
Gemini-->>BE: 6. Generated Actionable Guidance
BE->>BE: 7. Runaway Cleaner & Chunk Capping (Max 5 chunks)
BE-->>Webhook: 8. Paced Delivery (0.35s delay) to WeCom & Discord
| Performance / Technical Metric | Measured Value / Result | Technical Implementation & Notes |
|---|---|---|
| Time to First Token (TTFT) | < 450 ms | Real-time streaming via HTTP/2 + FastAPI StreamingResponse. |
| Targeted Context Routing Token Savings | > 80% Token Reduction | Symbol regex prunes irrelevant portfolio reports; latency drops from 12s to 1.8s. |
| Serverless Cold Start | < 1.8 s | Based on Python 3.11-slim with lazy loading client optimization. |
| Base Fixed Monthly Cost | $0 / month | Cloud Run Scale to Zero mechanism, billing strictly for actual requests. |
| Multi-Tenant & Data Rigor Test Suite | 22/22 Unit Tests Passed (100%) | Verifies 401/403 RBAC, Webhook masking, quote sanitization, FRED parsing, and chunk delivery. |