# onhighengineer/ai_gateway_llm_router_ architecture

> Architecture diagram of the GitHub repository onhighengineer/ai_gateway_llm_router_, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-07). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/onhighengineer/ai_gateway_llm_router_
- Repository: https://github.com/onhighengineer/ai_gateway_llm_router_

## Overview

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`](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/gateway_server.py) (Gateway), [`routing_model.py`](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/routing_model.py) (Router), [`poc.py`](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/poc.py) (POC eval), [`cache_layer.py`](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/cache_layer.py) (Cache)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_serving["Serving Runtime"]
  node_user(("User<br/>request source"))
  node_gateway_server["Gateway<br/>[gateway_server.py]"]
  node_cache_layer[("Cache<br/>[cache_layer.py]")]
  node_groq_llama(("Fast LLM<br/>external provider"))
  node_gemini_flash(("Capable LLM<br/>external provider"))
  node_env_example["Env template<br/>config template<br/>[.env.example]"]
end

subgraph group_routing["Routing Engine"]
  node_routing_model["Router<br/>intent classifier<br/>[routing_model.py]"]
  node_intent_policy{{"Intent map<br/>route policy"}}
  node_router_nn["NN backend<br/>embedding classifier<br/>[router_nn.pth]"]
  node_router_tfidf["TFIDF backend<br/>linear classifier<br/>[router_tfidf.pkl]"]
end

subgraph group_observability["Observability"]
  node_telemetry[("Logs & stats<br/>runtime telemetry")]
  node_log_viewer["Dashboard<br/>streamlit ui<br/>[log_viewer.py]"]
end

subgraph group_offline["Offline Evaluation"]
  node_poc["POC eval<br/>offline benchmark<br/>[poc.py]"]
  node_test_suite["Test set<br/>labeled prompts<br/>[test_suite.json]"]
end

node_user -->|"prompt"| node_gateway_server
node_gateway_server -->|"check first"| node_cache_layer
node_cache_layer -->|"cached response"| node_gateway_server
node_cache_layer -->|"miss"| node_routing_model
node_routing_model -->|"primary path"| node_router_nn
node_routing_model -->|"fallback path"| node_router_tfidf
node_routing_model -->|"intent class"| node_intent_policy
node_intent_policy -->|"fast intents"| node_groq_llama
node_intent_policy -->|"capable intents"| node_gemini_flash
node_groq_llama -->|"answer"| node_gateway_server
node_gemini_flash -->|"answer"| node_gateway_server
node_gateway_server -->|"record"| node_telemetry
node_telemetry -->|"inspect"| node_log_viewer
node_poc -->|"load cases"| node_test_suite
node_poc -->|"evaluate"| node_routing_model
node_poc -->|"compare"| node_router_nn
node_poc -->|"compare"| node_router_tfidf
node_gateway_server -.->|"configure"| node_env_example

click node_gateway_server "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/gateway_server.py"
click node_cache_layer "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/cache_layer.py"
click node_routing_model "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/routing_model.py"
click node_router_nn "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/router_nn.pth"
click node_router_tfidf "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/router_tfidf.pkl"
click node_log_viewer "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/log_viewer.py"
click node_poc "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/poc.py"
click node_test_suite "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/test_suite.json"
click node_env_example "https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/.env.example"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_user,node_gateway_server,node_cache_layer,node_groq_llama,node_gemini_flash,node_env_example toneBlue
class node_routing_model,node_intent_policy,node_router_nn,node_router_tfidf toneAmber
class node_telemetry,node_log_viewer toneMint
class node_poc,node_test_suite toneRose
```

## Components

### Serving Runtime

Live request path for chat and routing APIs

- **User**: request source · Client sending prompts into the gateway
- [Gateway](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/gateway_server.py): API gateway · Serving API that handles cache, routing, provider calls, and metadata · `gateway_server.py`
- [Cache](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/cache_layer.py): prompt cache · Exact and near-duplicate response reuse layer · `cache_layer.py`
- **Fast LLM**: external provider · Groq-hosted Llama 3.1 8B used for fast-routed intents
- **Capable LLM**: external provider · Gemini 1.5 Flash used for capable-routed intents
- [Env template](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/.env.example): config template · Example environment variables for provider and runtime setup · `.env.example`

### Routing Engine

Model backend selection and intent classification

- [Router](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/routing_model.py): intent classifier · Dual-backend classifier that maps prompts to intents · `routing_model.py`
- **Intent map**: route policy · Boundary that maps intents onto fast or capable routing
- [NN backend](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/router_nn.pth): embedding classifier · Sentence-embedding model with neural network weights · `router_nn.pth`
- [TFIDF backend](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/router_tfidf.pkl): linear classifier · Lightweight fallback model for routing · `router_tfidf.pkl`

### Observability

Logs, stats, and dashboard inspection

- **Logs & stats**: runtime telemetry · Request history, routing split, cache behavior, and cost metadata
- [Dashboard](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/log_viewer.py): streamlit ui · Operational dashboard for analysis and manual inspection · `log_viewer.py`

### Offline Evaluation

Research and benchmark workflow

- [POC eval](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/poc.py): offline benchmark · Standalone evaluation of the router without serving traffic · `poc.py`
- [Test set](https://github.com/onhighengineer/ai_gateway_llm_router_/blob/main/test_suite.json): labeled prompts · Benchmark prompts used for offline router evaluation · `test_suite.json`

## Connections

- 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
