← ALL EXPERIMENTS / thrifty-router
Thrifty Router
LANGUAGE / STACK: Python LIVE

Thrifty Router

Dynamic LLM routing, spend guardrails, and sub-10ms semantic caching across Vertex AI Gemini tiers.

OVERVIEW

Thrifty Router is an open-source, cost-optimizing LLM proxy for Google Cloud Vertex AI (Gemini 2.5 and 1.5). Running on Google Cloud Run with FastAPI, it intercepts prompt requests and dynamically determines the most cost-effective model tier — lite (Gemini 2.5 Flash at $0.075/$0.30 per 1M), standard (Gemini 1.5 Flash), or pro (Gemini 2.5 Pro at $1.25/$5.00 per 1M) — capable of fulfilling the request with high fidelity. The gateway implements four distinct routing strategies: static fixed mapping, semantic anchor classification using 768-dim embeddings via gemini-embedding-001, zero-shot LLM classification with automated fallback, and opportunistic cascade routing that attempts generation on cheaper tiers before validating and selectively escalating. Integrated with a two-tier semantic caching engine (SHA-256 exact match + Firestore vector search with cosine similarity >= 0.92) and a thread-safe micro-dollar cost ledger with a daily budget circuit breaker, Thrifty Router achieves up to 73% cost reductions on benchmark workloads while maintaining a 0.954 quality score evaluated by Gemini 2.5 Pro LLM-as-a-judge.

THE PROBLEM

Defaulting all LLM workloads to flagship reasoning models (like Gemini 2.5 Pro or GPT-4o) inflates inference bills by 10x to 20x for simple tasks like factual extraction, sentiment analysis, text formatting, and conversational greetings. Conversely, locking an application into a smaller, cheaper model causes hallucinations or silent failures when users present complex reasoning, code synthesis, or nuanced logic. Furthermore, unmetered public API endpoints risk unbounded cloud charges without real-time spend caps, and repetitive queries incur full model inference latency and expense without semantic deduplication.

Thrifty Router implements a layered defense-in-depth architecture. First, incoming requests pass through Slowapi per-IP rate limiting and an in-memory CostLedger that fails closed with HTTP 402 if daily spend exceeds DAILY_BUDGET_USD. Second, the semantic cache layer normalizes prompts, computes SHA-256 hashes for sub-millisecond hits, and queries Firestore vector indexes using gemini-embedding-001 with a 0.92 cosine similarity threshold — serving near-duplicate queries instantly at $0.00 cost with fail-safe error recovery. Third, cache misses enter the strategy router: the flagship Cascade Strategy invokes Gemini 2.5 Flash (lite) with an optional self-rated confidence tag, evaluating the response through a multi-factor verifier checking finish reason, non-empty text, JSON schema compliance, and confidence >= 70%. If any check fails, it cleanly escalates to standard and pro tiers. Fourth, an automated evaluation harness featuring 300 curated golden prompts across 8 task categories runs blinded evaluations scored by a Gemini 2.5 Pro judge, continuously validating that cost optimization does not compromise downstream response accuracy.

Production Architecture

End-to-end request flow, spend guardrails, and tier routing

Production Architecture CLICK TO ENLARGE
Evaluation Pipeline

300-prompt golden benchmark and LLM-as-a-judge evaluation

Evaluation Pipeline CLICK TO ENLARGE
Medium EFFORT
api

FastAPI

Python 3.12+ Async REST Gateway

auto_awesome

Vertex AI

Gemini 2.5 Flash, 1.5 Flash, 2.5 Pro

psychology

Google Gen AI SDK

google-genai 1.x with Vertex AI Backend

search

Firestore Vector Search

find_nearest() 768-dim Cosine Similarity

alt_route

Cascade Router

Multi-Factor Verification & Escalation

timer

Slowapi Limiter

Per-IP Token Bucket Rate Limiting

attach_money

Cost Ledger

Micro-Dollar Tracking & 402 Stop

cloud

Cloud Run

Scale-to-Zero Container Deployment

[DYNAMIC TIER ROUTING][73% COST REDUCTION][CASCADE VERIFICATION][SEMANTIC CACHE (COSINE >= 0.92)][DAILY SPEND CIRCUIT BREAKER][GOLDEN SET BENCHMARK (N=300)][LLM-AS-A-JUDGE][CLOUD RUN NATIVE]