Mathematical Foundations
The utility function, calibration, IRT, Bradley-Terry, LinUCB and Markov derivations.
Every routing decision in OpenSmartRoute is the output of explicit, inspectable formulas. This document lists them, the research they come from, and where they live in the code.
1. The routing problem
Given a request with signal vector and candidate set (after policy filtering), choose
subject to (quality floor, Hybrid-LLM). Costs and latencies are log-min-max normalised so one outlier (a $0.50/1k human queue) doesn't flatten the rest:
Code: router.py::_norm, Router._rank.
2. Ensemble quality estimate
Each strategy returns a score and a self-confidence . The ensemble is a confidence-weighted mean:
Learners report so they are silent until they have data — this is what lets rules and declared capabilities dominate at cold start and learned models take over as evidence accumulates.
3. Decision confidence
Low confidence (or high normalised entropy ) triggers the
LLM-judge escalation (Router-R1 pattern). Calibration is measured with ECE
(math.estimators.expected_calibration_error).
4. Online learning (auto-learn)
4.1 Thompson sampling (Beta–Bernoulli) — math.bandits.ThompsonBeta
; on reward : , . Optional forgetting for non-stationarity.
4.2 UCB1 — math.bandits.UCB1
(Auer, Cesa-Bianchi & Fischer 2002).
4.3 LinUCB (contextual) — math.bandits.LinUCB, learning.LinUCBStrategy
Per arm , , ,
score (Li et al., WWW 2010).
Context = learning.signal_vector (complexity, length, PII, jailbreak, tools,
language, multimodal, domain one-hots). This is the MixLLM formulation.
4.4 Cost-aware bandit (Lagrangian) — math.bandits.CostAwareBandit
Score with dual ascent so average spend tracks budget (C2MAB-V, Dai et al. 2024).
4.5 Item Response Theory (2PL) — math.irt.IRTModel, learning.IRTStrategy
Target ability , item (domain × difficulty bucket) difficulty , discrimination ; fitted by online SGA on Bernoulli log-likelihood with L2. Interpretable and cold-start friendly (IRT-Router, Song et al., ACL 2025).
4.6 Bradley–Terry / Elo — math.preference, learning.PreferenceStrategy
Learned per domain → a prompt-specific leaderboard (Prompt-to-Leaderboard, Frick et al. 2025; RouteLLM preference data). Selection probability via Luce: .
4.7 Markov chain & MDP — math.markov, learning.MarkovStrategy
Conversation state = dominant domain. Transition matrix with Dirichlet smoothing
-step prediction , first-passage probability to escalate, stationary
distribution by power iteration, next-state entropy.
Routing MDP (value iteration):
MarkovStrategy scores —
prefer targets that are also good for where the conversation is going.
4.8 Drift detection — math.estimators
- Page–Hinkley: , alarm if .
- ADWIN-lite: split window, Hoeffding bound .
AutoLearnerflags drifted targets;HealthStrategy/HealthPolicycan demote them.
4.9 Uncertainty on success rates
Wilson interval lower bound is used as the reliability estimate so a target with 2/2 successes is not considered 100 % reliable.
4.10 The routing SLM — learning.contrastive, learning.attention, learning.slm
Dual encoder: query over hashed
word / bigram / character-gram features (and an optional one-block transformer with
sinusoidal positions and attention pooling), one learned embedding and bias per target,
logit . Losses are softmax cross-entropies over the row's candidate set:
multi-positive InfoNCE over the acceptable set (RouterDC), ,
or Zooter distillation towards of per-target scores . Training is
SGD with inverse-time decay , L2 shrinkage, early stopping on a
validation split, and two regularisers on the inputs: every row is also presented as augment_views
word-dropout copies (each word kept with probability , drawn once per fit) and, optionally, labels
are smoothed . Reported probabilities are temperature-scaled
on the validation rows, with minimising the NLL of the
top pick being acceptable, and SLMStrategy reads its margin and confidence from those calibrated
probabilities. Prompts are read up to max_tokens whitespace tokens through a reading window
(learning.window): head and tail shares of the budget, the rest for the most instruction-salient sentences
of the middle - salience with the
share of the sentence's words seen at most twice in the prompt and the novelty weight - placed first;
and a long prompt's query is , the
unit vectors of the window view and of the asking sentences alone at weight . The attention block
has its own window under the same policy. The numpy path runs the same steps as dense products and draws the
same random numbers, so both backends produce the same model file (§ Speed in User guide).
5. Multi-objective decisions — math.decision
- Pareto front over (quality↑, cost↓, latency↓).
- TOPSIS closeness to the ideal point.
- Weighted sum (the default scalarisation).
6. Real-time capacity — math.decision
- Erlang-C: , , .
- Mean wait ;
servers_for_slasizes a human/agent pool. - Little's law .
- Kingman G/G/1: for bursty LLM endpoints.
7. Resilience state machines — realtime
Circuit breaker (closed → open after failures in window → half-open after → closed on probe success), token-bucket rate limit, rolling-window budget.
8. Similarity — strategies.similarity
Hashing-trick embeddings (word + bigram, signed hashing, L2-normalised), cosine similarity; score (UniRoute-style example-based target representation). Swap in sentence-transformers for semantic quality.
9. Adversarial robustness — security.InputGuard
Confounder-gadget score compares head vs tail of the prompt on: alphabetic-token ratio, function-word share, Shannon entropy jump, all-unique tail. Based on the attack in "Rerouting LLM Routers" (Shafran et al., 2025). Signals are computed on the cleaned head.
10. Evidential routing — math.dirichlet.DirichletProbe, strategies.HiddenStateStrategy
A linear head over a feature vector (host hidden state, or any embedding) outputs concentrations of a Dirichlet over the targets, . Prediction ; epistemic uncertainty (all evidence near zero gives ). Training minimises the expected cross-entropy under the Dirichlet plus a KL term that removes evidence from wrong classes (Sensoy et al., 2018):
by SGD with (digamma) and (trigamma) in pure Python. HiddenStateStrategy uses
as its confidence so an unfamiliar state hands the decision to the other strategies.
11. Response-side uncertainty — signals.uncertainty
- Semantic entropy (Kuhn et al., 2023): cluster sampled answers by meaning (cosine over
hashed or real embeddings, threshold ); with cluster mass ,
(nats;
response_uncertaintynormalises by ). Agreement . - P(True) (Kadavath et al., 2022): an optional judge returns .
response_uncertainty, and with a judge ;UncertaintyGatereturns as a cascade quality gate.EventTriggerfires named actions on threshold crossings (2607.13048).
12. Optimal stopping during generation — strategies.escalation.SelfEscalation
Competence , prior centred on the target's quality_prior. Each
streamed chunk adds pseudo-counts: hedges , refusals , self-corrections ,
repetition , length overrun to ; clean progress to . After each chunk
where is tokens decoded, the expected answer length: restarting elsewhere pays the escalation overhead and regenerates the answer, continuing risks a failed answer (2608.24087).
13. Mixture-cure hand-off — learning.handoff
A task fails once its cumulative teacher risk crosses a latent threshold; a fraction of tasks is cured and never fails; tasks that end without failing are censored.
MixtureCureModel.fit() maximises the censored likelihood (density for failures, survival for
censored) over a grid in with one refinement. HandoffPolicy hands over
permanently when or the probability of failing within the next
steps at the trajectory's mean step risk exceeds (TACIT-Switch 2608.27911).
14. Error-aware reverse auction — strategies.auction.AuctionStrategy
Bidder claims success at price . Its claim is corrected by the observed bias and realised rate with shrinkage : . Surplus ; the highest surplus wins and pays the second price so over-claiming is not rewarded (EA-RAM 2608.12719).
15. Energy and carbon — math.energy
Per target, ridge regression on measured samples gives
(normal equations,
solve); with the grid factor . Without a
meter, HardwareProfile estimates from the accelerator's throughput
(2608.28044; HW-Router).
16. Personalisation by shrinkage — learning.personal.UserAdaptiveStrategy
, : a user's own Beta posterior, the similarity-weighted posterior of the nearest users (cosine over hashed profile vectors) and the global posterior. New users are routed by their neighbours and the crowd and take over after outcomes (GMTRouter 2511.08590).
17. Multi-turn joint embeddings — learning.multiturn.HistoryTargetStrategy
History vector over the last role-tagged messages and the current text ( = hashed word/bigram embedding, recency decay); target vector = catalogue embedding. Joint feature and
a bilinear form with a diagonal weight matrix shared by every target; only is target-specific,
so an unseen target is scored through alone (inductive). Online logistic SGD on the reward with
L2 shrinkage; is initialised at . Confidence
. Incumbent continuity adds stay_bonus (MTRouter 2604.23530).
References
See Research for the full bibliography.
Something wrong or out of date on this page? Tell us - the page is named for you, so a one-line note is enough.