Sub-millisecond LLM prompt routing using reinforcement learning.
Route every prompt to the optimal model based on latency, cost, and quality β with zero GC pauses.
Built for RegicideOS and production AI infrastructure.
β‘ Quick Start Β· π§ Routing Algorithms Β· π Observability Β· π Deployment
Merlin sits between your application and multiple LLM providers. Instead of hard-coding a model choice, you send a prompt to Merlin and it intelligently selects the best provider in real time based on:
- β‘ Latency β Route to the fastest available endpoint
- π° Cost β Prefer cheaper models for low-stakes queries
- π― Quality β Use premium models when accuracy matters
- π Load β Balance traffic across healthy providers
All routing decisions happen in under a millisecond thanks to Rust + Tokio async.
| Feature | Detail |
|---|---|
| π Multi-Provider | OpenAI, Anthropic, Gemini, local GGUF models β all via a single endpoint |
| π§ Smart Routing | Epsilon-greedy, Thompson sampling, UCB, and contextual bandit algorithms |
| π Real-Time Metrics | Latency, cost, and quality tracking per provider |
| π Learning from Feedback | Star ratings + comment sentiment feed the bandit reward; request success/failure rewards are automatic |
| π Observability | Prometheus metrics, Jaeger 8000 tracing, Grafana dashboards |
| π¦ Zero GC Pauses | Rust + Tokio async for predictable, sub-ms routing |
| π Security Hardened | Systemd service with non-root execution, memory limits, auto-restart |
# Clone
git clone https://github.com/awdemos/merlin.git
cd merlin
# Build
cargo build --release
# Configure
cat > merlin.toml << 'EOF'
[providers]
openai = { api_key = "sk-...", model = "gpt-4-turbo" }
anthropic = { api_key = "sk-ant-...", model = "claude-3-opus" }
[routing]
policy = "thompson_sampling"
exploration_rate = 0.15
[telemetry]
prometheus_port = 9090
EOF
# Run
./target/release/merlin serve --port 7777 --config ./merlin.tomlMerlin implements several multi-armed bandit strategies for provider selection:
Explores random providers with probability Ξ΅, otherwise exploits the current best.
[routing]
policy = "epsilon_greedy"
exploration_rate = 0.10 # 10% explorationBayesian approach that naturally balances exploration and exploitation based on observed reward distributions.
[routing]
policy = "thompson_sampling"Optimistic exploration bonus that favors under-sampled providers.
A per-arm LinUCB model over semantic prompt features (domain, difficulty, tool-need, sensitivity β see the laya sidecar below) that learns which model fits which kind of prompt. Cold-start spreads requests round-robin until rewards arrive; every reward updates the arm's ridge model with the features that drove the selection.
Each provider arm accumulates reward from two real signals:
- Request outcomes β a successful provider response adds a positive reward; a failure adds zero (and the router fails over to the next provider).
- User feedback β star ratings (1β5) are scaled to 0β1, weighted by feedback type (quality and overall count at full weight, speed and cost less), and adjusted by a keyword sentiment scan of the comment ("excellent" pushes the reward up, "terrible" pulls it down). Feedback submitted to
/feedbackis applied to the bandit arms with per-model watermarks, so rewards are never double-counted.
Note: the contextual bandit and
llm_classifierconsume features from the laya sidecar (below). Without it, the bandit falls back to a degraded prompt-length signal and the classifier falls back to a pure length heuristic β both work, but with much less discrimination.
Merlin can classify every prompt semantically before routing by talking to a small sidecar service that wraps laya β a non-autoregressive decision engine (~33 ms per prompt on GPU, 100+ languages). The sidecar replaces Merlin's old length-based heuristics with real signal:
| Signal | Type | Drives |
|---|---|---|
domain |
choice (code, math, writing, factual, data, chitchat) | contextual bandit context vector |
difficulty |
score 0β1 | llm_classifier strong/weak split, bandit context |
is_sensitive |
probability | forces llm_classifier to the strong model β₯ 0.7 |
needs_tools |
probability | bandit context |
jailbreak / prompt_injection |
probability | pre-request guard (HTTP 400) |
# 1. Start the sidecar (downloads laya checkpoints on first run)
pip install -r sidecar/requirements.txt
python sidecar/app.py --port 8765
# 2. Point Merlin at it
./target/release/merlin serve --config examples/laya-sidecar.tomlEverything is config-gated and fail-open: if the sidecar is down, slow, or
returns garbage, Merlin logs a warning and falls back to prompt-length
heuristics β routing never breaks because the classifier did. Prompt features
are cached per Merlin process (default 512 entries, 300 s TTL). Set
guard_enabled = true to block jailbreak/injection prompts with HTTP 400
before any provider is contacted. See sidecar/README.md for the HTTP API and
examples/laya-sidecar.toml for the full [features] configuration.
curl -X POST http://localhost:7777/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "What is the capital of France?", "max_tokens": 100}'{
"response": "The capital of France is Paris.",
"provider": "openai",
"model": "gpt-4-turbo",
"session_id": "9f2c..."
}The model is chosen per-prompt by the routing policy; if the selected
provider fails, Merlin automatically fails over to the next candidate. Pass
session_id to /feedback to rate the response and teach the router.
curl http://localhost:7777/health
curl http://localhost:7777/metricsMerlin exports Prometheus-compatible metrics and Jaeger traces out of the box:
| Metric | Description |
|---|---|
merlin_requests_total |
Total requests routed |
merlin_latency_ms |
p50/p95/p99 latency per provider |
merlin_cost_usd |
Estimated cost per provider |
merlin_reward_score |
Average reward per provider |
Grafana dashboard included in dashboards/.
# Build and install
cargo build --release
sudo ./scripts/install-systemd.sh
# Manage
sudo systemctl enable --now merlin
sudo systemctl status merlin
journalctl -u merlin -fService features:
- π Non-root execution with restricted permissions
- π Memory limits and CPU scheduling
- π Auto-restart on failure
- π Native journald logging
| File | Purpose |
|---|---|
/etc/merlin/merlin.toml |
Main configuration |
/etc/merlin/merlin.env |
Environment variables |
/etc/systemd/system/merlin.service |
Service definition |
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β Client ββββββΆβ Merlin ββββββΆβ Provider β
β (Your App) βββββββ Router βββββββ (LLM) β
βββββββββββββββ ββββββββ¬βββββββ βββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
βΌ βΌ βΌ
βββββββββββ βββββββββββ βββββββββββ
β Metrics β β Traces β β Cache β
β(Prom) β β(Jaeger) β β (Redis) β
βββββββββββ βββββββββββ βββββββββββ
Governance turns merlin into a multi-tenant policy gateway: applications
authenticate with mrl_live_β¦ tokens, per-app policies restrict which
targets may serve them, quotas cap requests-per-minute and daily spend,
and a fail-closed gate keeps sensitive traffic on local infrastructure.
# 1. Enable in merlin.toml
[governance]
enabled = true
redis_url = "redis://127.0.0.1:6379"
# 2. Create an app and issue a token (shown once)
merlin app create --id myapp --name "My App"
merlin app policy --id myapp --locality local_only --max-rpm 60 \
--max-spend-day 20 --sensitive-local-only
merlin app token issue --id myapp
# 3. Call with the token
curl -X POST http://localhost:7777/v1/chat/completions \
-H "Authorization: Bearer mrl_live_β¦" \
-H "Content-Type: application/json" \
-d '{"model": "default", "messages": [{"role": "user", "content": "hello"}]}'Policy enforcement order: authenticate (401) β route allowlist (403) β quotas (429) β sensitivity
(sidecar is_sensitive, falling back to a built-in local detector) β eligibility gate (403 with
self-explaining conflicts). When sensitivity cannot be determined the gate fails closed and
applies the strictest policy; routing-side classification stays fail-open as before. Aggregate
(non-streamed) responses include a merlin_trace object recording the decision.
Notes:
- Apps with a daily spend cap can only route to targets that declare
price_input/price_output(fail-closed). - Spend accounting charges aggregate and streamed responses (stream usage
is accumulated from usage events and charged when the stream ends;
merlin_traceremains aggregate-only by design β injecting non-standard events would break OpenAI SSE clients). - Denials are counted in
merlin_governance_denials_total{code}and include anerror.conflictslist explaining the denial. - Governance denials use a string
error.code(e.g."policy_denied"); legacy error responses (upstream failures) use a numericcodeβ check the shape before reading it. - See
examples/governance.tomlfor a full config.
- Multi-provider routing
- Epsilon-greedy & Thompson sampling
- Prometheus metrics
- Systemd service deployment
- Automatic provider failover
- TensorRT-LLM backend for local GPU inference
- Dynamic model warm/cold pool management
- Distributed routing cluster (Raft consensus)
- Circuit breakers per provider
Contributions welcome! Areas of interest:
- Additional routing algorithms (UCB, EXP3)
- New provider backends (Azure OpenAI, Bedrock, Vertex)
- Performance benchmarks and profiling
- Grafana dashboard improvements
Β© 2026 Andrew White Β· RegicideOS Project Β· GPL v3