How onhighengineer/ai_gateway_llm_router_ works
1. What this repo is
- This is a small AI gateway that sits between users and two external LLM providers. Its main job is to decide, per prompt, whether to send the request to a cheaper/faster model or a more capable model.
2. Top-level architecture
- The repo has four runtime pieces:
- gateway_server.py: live request-serving API
- routing_model.py: intent router that decides fast vs capable
- cache_layer.py: near-duplicate prompt response cache
- log_viewer.py: Streamlit dashboard for observability and manual interaction
- poc.py is separate from serving; it evaluates the router offline.
3. Live request flow
- A prompt enters the gateway server.
- The cache layer checks for an exact or highly similar prior prompt first.
- On cache miss, the routing model classifies the prompt into one of 8 intents.
- That intent maps to either the Fast model or the Capable model.
- The selected external LLM is called, and the response is returned with metadata such as route, confidence, latency, token counts, and estimated cost.
4. Routing subsystem
- routing_model.py is the core decision engine and is explicitly designed as a dual-backend classifier.
- Primary path: sentence embeddings feeding a small neural network stored in router_nn.pth.
- Fallback path: TF-IDF + logistic regression stored in router_tfidf.pkl.
- The router auto-selects the embedding/NN backend when sentence-transformers and torch are available; otherwise it falls back to the lightweight TF-IDF model.
5. Intent-to-route boundary
- The router does not directly predict “which LLM should answer” from arbitrary complexity signals; it predicts an intent class.
- Fast-routed intents are simple_factual, simple_task, and chit_chat.
- Capable-routed intents are code_generation, code_analysis, complex_reasoning, system_design, and explanation_detailed.
- This intent layer is the main architectural boundary between classification and model selection.
6. Cache subsystem
- cache_layer.py is a response reuse layer using TF-IDF cosine similarity with a configurable threshold, plus exact-hash lookup and LRU eviction.
- Its role is to avoid repeated LLM calls for prompts that are effectively duplicates.
- Architecturally, it sits in front of the router, so cache hits bypass both classification and model invocation.
7. Gateway/server boundary
- gateway_server.py exposes the external API surface, including /chat for full execution and /route for routing-only inspection.
- It also exposes operational endpoints for health, stats, logs, and cache/log clearing.
- This file is the integration point that connects cache, router, provider calls, and telemetry into one serving path.
8. External dependencies and providers
- The live system depends on two external LLM services:
- Groq-hosted Llama 3.1 8B for the fast path
- Google AI Studio Gemini 1.5 Flash for the capable path
- Environment configuration is handled via .env based on .env.example.
- Token costing is part of the response metadata, so the gateway is not just routing for quality; it is also measuring cost savings.
9. Observability and user-facing ops
- log_viewer.py is a Streamlit dashboard rather than part of the serving path.
- It reads gateway logs/metrics to show routing split, cache behavior, cost analysis, and request history.
- This creates a clear operational boundary: serving happens in FastAPI, inspection and analysis happen in Streamlit.
10. Offline evaluation / research workflow
- poc.py evaluates the router independently of the gateway and does not require API keys.
- test_suite.json provides labeled prompts for the 30-case benchmark used in the README.
- This means the repo separates research validation of the routing model from production-like request handling.
11. Persistent artifacts
- The trained router artifacts are checked into the repo as router_nn.pth and router_tfidf.pkl.
- These files are the deployable model state; the code in routing_model.py is the inference/training logic, while the artifacts are the serialized weights/features.
- No database is shown in the tree; state appears to be limited to local artifacts, in-memory cache/logs, and whatever the server persists for logging.
12. Diagram-friendly summary
- A good architecture diagram should show: user/request source → cache → router → one of two external LLMs → response with metadata, plus a side path from gateway to logs/stats/dashboard.
- Also show the offline evaluation path separately: poc.py + test_suite.json → router artifacts/metrics, because it is a non-serving subsystem.
Main entry points: gateway_server.py Gateway · routing_model.py Router · poc.py POC eval · cache_layer.py Cache
Components 14
Serving Runtime
Live request path for chat and routing APIs
- User · Client sending prompts into the gateway
- Gateway · Serving API that handles cache, routing, provider calls, and metadata
gateway_server.py - Cache · Exact and near-duplicate response reuse layer
cache_layer.py - Fast LLM · Groq-hosted Llama 3.1 8B used for fast-routed intents
- Capable LLM · Gemini 1.5 Flash used for capable-routed intents
- Env template · Example environment variables for provider and runtime setup
.env.example
Routing Engine
Model backend selection and intent classification
- Router · Dual-backend classifier that maps prompts to intents
routing_model.py - Intent map · Boundary that maps intents onto fast or capable routing
- NN backend · Sentence-embedding model with neural network weights
router_nn.pth - TFIDF backend · Lightweight fallback model for routing
router_tfidf.pkl
Observability
Logs, stats, and dashboard inspection
- Logs & stats · Request history, routing split, cache behavior, and cost metadata
- Dashboard · Operational dashboard for analysis and manual inspection
log_viewer.py
Connections 18
- User → Gateway: prompt · User request enters the live API
- Gateway → Cache: check first · Gateway consults cache before routing
- Cache → Gateway: cached response · Exact or similar match returns without model invocation
- Cache → Router: miss · Cache miss passes the prompt to the router
- Router → NN backend: primary path · Embedding-plus-neural backend when available
- Router → TFIDF backend: fallback path · TF-IDF plus logistic regression backend
- Router → Intent map: intent class · Router emits one of the supported intent categories
- Intent map → Fast LLM: fast intents · simple_factual, simple_task, and chit_chat routes
- Intent map → Capable LLM: capable intents · code, reasoning, design, and detailed explanation routes
- Fast LLM → Gateway: answer · Fast model response returns to the gateway
- Capable LLM → Gateway: answer · Capable model response returns to the gateway
- Gateway → Logs & stats: record · Gateway stores route, confidence, latency, token, and cost metadata
- Logs & stats → Dashboard: inspect · Dashboard reads logs and metrics for analysis
- POC eval → Test set: load cases · Offline evaluation consumes the labeled benchmark set
- POC eval → Router: evaluate · Standalone router evaluation path
- POC eval → NN backend: compare · Benchmarking against the serialized NN backend
- POC eval → TFIDF backend: compare · Benchmarking against the serialized TF-IDF backend
- Gateway → Env template: configure · Environment template supports live provider setup