How avtheking/semantic-router works
1. Repository purpose and top-level shape. This is a multi-language platform for semantic, policy-driven routing of LLM requests across heterogeneous model endpoints. Its production core is the Go service in src/semantic-router; surrounding projects provide native ML inference bindings, deployment/control-plane integration, a management dashboard, CLI tooling, simulation/training, benchmarks, and documentation.
2. Primary data plane: Semantic Router. src/semantic-router/cmd builds the router process. It exposes a management/classification API through pkg/apiserver and operates as an Envoy External Processing (ext_proc) service through pkg/extproc. In the normal serving path, a client sends OpenAI-compatible or Anthropic-compatible inference traffic to Envoy or another supported gateway; the gateway calls the router; the router analyzes and may transform the request; the gateway forwards it to the selected upstream model endpoint; and response processing returns the final output to the client.
3. Request-processing pipeline. pkg/extproc is the critical orchestration boundary. It processes request headers and bodies, creates request context, enforces auth/rate-limit/policy behavior, runs configured plugins, classifies the workload, resolves a route/model, and mutates routing headers or request payloads for the proxy. It also processes response headers/bodies, including streaming/SSE variants, for caching, memory persistence, safety checks, usage accounting, replay recording, and response transformations. OpenAI chat/completions, OpenAI Responses API, and Anthropic message/streaming flows are explicit protocol paths rather than merely generic HTTP proxying.
4. Signal, decision, and selection layers. Classification in pkg/classification produces structured signals such as domain, complexity, language, modality, PII, jailbreak risk, context length, user preference, conversation shape, and knowledge-base similarity. pkg/decision evaluates configured boolean/composite decision rules over these signals. pkg/selection then chooses an endpoint or model using static, hybrid, latency-aware, ML, k-NN/SVM/k-means, AutoMix, Router-DC, RL-driven, session-aware, and cache-affinity strategies. These three layers should be shown separately: signals are observations, decisions encode policy, and selection chooses a concrete inference target.
5. Config is the router’s declarative control plane. YAML configuration defines models/endpoints, signals, decisions, selection algorithms, plugins, knowledge bases, and global runtime behavior. pkg/config loads, canonicalizes, validates, and supports runtime updates to this configuration. config/ contains composable reference fragments and examples, while pkg/dsl provides a DSL parser/compiler/decompiler that converts an authoring-oriented route definition into the canonical YAML/runtime configuration. Kubernetes CRDs and the dashboard both ultimately feed this configuration boundary.
6. Plugins and stateful enrichment. The extproc pipeline has optional cross-cutting plugins for semantic caching, RAG/vector search, user memory, tool selection and execution metadata, system prompt/request-parameter mutation, hallucination/fact checking, response jailbreak checks, image generation, router replay, and multi-model “looper” workflows. These are not separate services by default; they are pipeline capabilities enabled by configuration. Some plugins invoke external systems or model endpoints, so they create optional branches in the request path.
7. Persistence and external service adapters. The router abstracts multiple storage domains behind factories/interfaces. Redis and Valkey support caching, response state, session/telemetry-related state, and some vector capabilities; Milvus and Qdrant support semantic cache, memory, and vector/RAG workloads; PostgreSQL is used for durable router replay and some metadata/configuration use cases. In-memory implementations exist for local/testing modes. External OpenAI-compatible embedding providers, vLLM-compatible model servers, MCP servers over HTTP or stdio, Llama Stack, and image-generation backends are adapter boundaries rather than embedded components.
8. Native inference backends. Local classifier and embedding inference is separated from Go through bindings. candle-binding is a Rust/Candle implementation with text, multimodal embedding, traditional classifier, generative guard, LoRA, continuous batching, and FFI layers. onnx-binding is a Rust/ONNX Runtime path, including optional GPU/ROCm optimizations. openvino-binding is a C++/OpenVINO backend. ml-binding and nlp-binding provide smaller Rust-backed ML/NLP algorithms. Go selects these through CGO-backed classifier abstractions, with stub builds where a native backend is unavailable.
9. Management APIs and dashboard. The Go router API (pkg/apiserver) provides classification, embeddings, model/runtime information, config deployment/update, vector store and knowledge-base operations, memory, and routing outcome endpoints. The dashboard is a separate application: a React/TypeScript/Vite frontend in dashboard/frontend, a Go backend in dashboard/backend, and a bundled Svelte/WebGL knowledge-map visualization in dashboard/wizmap. The dashboard backend mediates authentication, configuration versioning/projections, deployment and status collection, evaluation jobs, logs, proxy/websocket traffic, MCP management, and lifecycle actions; it should not be conflated with the latency-sensitive router data plane.
10. User-facing operational interfaces. src/vllm-sr is a Python CLI/package for bootstrapping and operating local or containerized stacks, generating and validating config, managing models and storage, serving the router/dashboard, and interacting with Kubernetes or container runtimes. The dashboard and CLI are alternate management surfaces over router configuration and deployment resources. install.sh, root Makefiles, and tools/make coordinate builds, local dependencies, containers, models, Helm, and validation.
11. Kubernetes and gateway integration. deploy/helm/semantic-router packages the router, dashboard, RBAC, ConfigMaps, services, HPA, optional observability resources, and CRDs. deploy/operator is a separate Go Kubernetes controller that watches SemanticRouter custom resources, validates/canonicalizes specs, discovers backends, and reconciles router workloads, configuration, Envoy/gateway resources, and storage dependencies. Deployment variants target Envoy, Istio, Gateway API/AI Gateway, AgentGateway, AIBrix, llm-d, NVIDIA Dynamo, KServe, OpenShift, and local Docker; these are integration choices around the same router core.
12. Observability and feedback loops. pkg/observability emits Prometheus metrics, structured logs, and distributed tracing propagation. Router outcomes, session telemetry, route diagnostics, tool traces, and replay trajectories can be recorded by extproc and persisted through the replay stores. These artifacts feed dashboard insights/evaluations and router-learning mechanisms, allowing later adaptation of selection policy without making the online request path depend on offline training.
13. Offline and auxiliary systems. src/fleet-sim is an independent Python simulator/API for modeling model fleets, hardware/GPU profiles, workloads, routing strategies, and capacity/cost optimization; the dashboard has dedicated Fleet Sim pages that consume its API. src/training contains Python-based training and evaluation workflows for classifiers, embeddings, LoRA adapters, and learned/RL model-selection artifacts. bench and perf measure routing, classification, cache, fusion, reasoning, and accelerator performance. These systems produce models, policies, and evidence consumed by or used to tune the runtime, but are not required for a basic serving deployment.
14. Testing, release, and documentation boundaries. e2e is a Go test harness that provisions Kind/Kubernetes, Helm stacks, gateways, model simulators, stores, and profile-specific integration tests. Native bindings, dashboard, router, CLI, simulator, and operator each have local unit tests. GitHub Actions build/publish images, Helm charts, Python packages, crates, and run integration/performance/security checks. website is a separate Docusaurus documentation site, while paper contains research-paper sources; neither participates in production request handling.
Main entry points: extproc External Processor · envoy.yaml AI Gateway · backend Dashboard Backend · config Config Runtime
Components 24
Serving Data Plane
Latency-sensitive request routing path.
- Inference Clients · Applications submit compatible inference requests.
- AI Gateway · Forwards client traffic and invokes router external processing.
deploy/local/envoy.yaml - Semantic Router · Production router process hosting external processing and management APIs.
src/semantic-router/cmd - External Processor · Processes protocol-specific headers, bodies, streaming, routing mutations, and response handling.
src/semantic-router/pkg/extproc - Protocol Adapters · Compatible request, response, and SSE translation paths.
src/semantic-router/pkg/anthropic
Routing Intelligence
Signals, policy evaluation, and target selection.
- Signal Engine · Produces domain, complexity, safety, language, modality, context, preference, and KB signals.
src/semantic-router/pkg/classification - Decision Engine · Evaluates configured boolean and composite routing rules over signals.
src/semantic-router/pkg/decision - Target Selection · Chooses models/endpoints via static, hybrid, ML, latency-aware, RL, session, and affinity strategies.
src/semantic-router/pkg/selection - Native Inference · Local classifier and embedding execution selected by Go abstractions.
candle-binding
Configuration & Control
Declarative configuration and management surfaces.
- Config Runtime · Loads, validates, canonicalizes, and publishes live router configuration.
src/semantic-router/pkg/config - Route DSL · Converts authoring-oriented routing definitions to canonical runtime configuration.
src/semantic-router/pkg/dsl - Router API · Serves classification, embeddings, configuration, knowledge-base, memory, and outcome endpoints.
src/semantic-router/pkg/apiserver - Dashboard · Configuration, topology, insights, evaluation, and operational interface.
dashboard/frontend - Dashboard Backend · Mediates auth, versioned config projections, deployment, status, jobs, logs, and proxy traffic.
dashboard/backend
Runtime Integrations
Gateways, model providers, state, and observability.
- Pipeline Plugins · Caching, RAG, memory, tools, safety, replay, image generation, and multi-model workflows.
src/semantic-router/pkg/extproc - State & Vector Stores · Redis/Valkey, Milvus, Qdrant, PostgreSQL, and in-memory implementations.
src/semantic-router/pkg/vectorstore - Model Endpoints · Selected upstream LLM, embedding, image, vLLM-compatible, and related model services.
- MCP Services · External tool and classifier services accessed through the MCP boundary.
src/semantic-router/pkg/mcp - Observability · Exports router telemetry, structured logging, and distributed tracing propagation.
src/semantic-router/pkg/observability
Deployment & Operations
Packaging, Kubernetes reconciliation, and operator tooling.
- Kubernetes Operator · Watches custom resources and reconciles router workloads, gateway resources, config, and dependencies.
deploy/operator - Helm Deployment · Packages router, dashboard, RBAC, services, autoscaling, CRDs, and optional observability.
deploy/helm/semantic-router - vllm-sr CLI · Bootstraps stacks, manages models and storage, generates config, and controls local or Kubernetes runtimes.
src/vllm-sr
Offline Systems
Simulation and model/policy training.
- Fleet Simulator · Models fleets, hardware, workloads, routing strategies, capacity, and cost.
src/fleet-sim - Training Workflows · Trains and evaluates classifier, embedding, LoRA, and learned selection artifacts.
src/training
Connections 35
- Inference Clients → AI Gateway: inference request · Compatible client traffic enters the gateway.
- AI Gateway → External Processor: ext_proc callbacks · Gateway delegates request and response processing.
- Semantic Router → External Processor: hosts · Router entrypoint starts the processor service.
- External Processor → Protocol Adapters: adapts protocols · Applies explicit OpenAI, Responses API, Anthropic, and streaming behavior.
- External Processor → Signal Engine: classifies request · Request processing obtains structured observations.
- Signal Engine → Decision Engine: signals · Observations are inputs to policy rules.
- Decision Engine → Target Selection: eligible policy · Decision outcomes constrain or direct selection.
- Target Selection → External Processor: target resolution · The selected endpoint is returned to the processor.
- External Processor → AI Gateway: route mutations · Headers or payload are updated so the gateway forwards upstream.
- AI Gateway → Model Endpoints: forwarded inference · Gateway sends the routed request to its selected upstream.
- Model Endpoints → AI Gateway: model response · Upstream output returns through the gateway.
- AI Gateway → External Processor: response callbacks · Responses, including SSE streams, are processed before delivery.
- External Processor → Pipeline Plugins: optional pipeline · Configured enrichments run on request or response paths.
- Pipeline Plugins → State & Vector Stores: read/write state · Cache, memory, RAG, and replay plugins use configured stores.
- Pipeline Plugins → MCP Services: invoke tools · Tool and classifier integrations use MCP clients.
- External Processor → State & Vector Stores: responses and replay · Persists response state, telemetry, and routing records.
- External Processor → Observability: emits telemetry · Records metrics, logs, and trace context.
- Signal Engine → Native Inference: local inference · Classifier and embedding signals may invoke native backends.
- Config Runtime → External Processor: runtime configuration · Defines models, signals, decisions, selection, plugins, and globals.
- Route DSL → Config Runtime: compiles to config · DSL authoring produces canonical router configuration.
- Router API → Config Runtime: updates config · Management API deploys and synchronizes live settings.
- Dashboard → Dashboard Backend: management requests · Frontend uses the backend as its control-plane boundary.
- Dashboard Backend → Router API: config and status · Backend manages router runtime through its API.
- Dashboard Backend → Fleet Simulator: simulation API · Fleet pages consume simulator capabilities.
- Dashboard Backend → Observability: insights · Operational views consume runtime telemetry and logs.
- vllm-sr CLI → Config Runtime: generates and validates · CLI creates and validates router configuration.
- vllm-sr CLI → Helm Deployment: operates deployments · CLI manages local/container and Kubernetes stacks.
- Helm Deployment → Semantic Router: deploys · Chart installs the router runtime.
- Helm Deployment → Dashboard Backend: deploys · Chart packages the dashboard service.
- Kubernetes Operator → Config Runtime: canonicalizes specs · Custom resource specifications become canonical router config.
- Kubernetes Operator → Semantic Router: reconciles workload · Controller provisions and maintains router resources.
- Training Workflows → Native Inference: model artifacts · Training produces artifacts consumed by local inference backends.
- Training Workflows → Target Selection: learned policies · Offline evaluation and training tune selection strategies.
- Fleet Simulator → Target Selection: what-if evidence · Simulation evaluates routing and fleet policy choices offline.
- State & Vector Stores → Training Workflows: replay trajectories · Persisted outcomes can inform offline learning workflows.