Skip to content
OpenSmartRoute
Documentation
Concepts

Mathematical Foundations

The utility function, calibration, IRT, Bradley-Terry, LinUCB and Markov derivations.

Concepts 8 min read

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 xx with signal vector ϕ(x)\phi(x) and candidate set T\mathcal{T} (after policy filtering), choose

t\*=arg⁡max⁡t∈T  U(x,t),U(x,t)=wq q^(x,t)−wc c~t−wl ℓ~tt^\* = \arg\max_{t \in \mathcal{T}} \; U(x,t), \qquad U(x,t) = w_q\,\hat q(x,t) - w_c\,\tilde c_t - w_l\,\tilde \ell_t

subject to q^(x,t)≥qmin⁡\hat q(x,t) \ge q_{\min} (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:

c~t=log⁡(1+s ct)−min⁡klog⁡(1+s ck)max⁡klog⁡(1+s ck)−min⁡klog⁡(1+s ck)\tilde c_t = \frac{\log(1 + s\,c_t) - \min_k \log(1 + s\,c_k)}{\max_k \log(1 + s\,c_k) - \min_k \log(1 + s\,c_k)}

Code: router.py::_norm, Router._rank.

2. Ensemble quality estimate

Each strategy kk returns a score sk(t)∈[0,1]s_k(t) \in [0,1] and a self-confidence κk(t)\kappa_k(t). The ensemble is a confidence-weighted mean:

q^(x,t)=∑kwk κk(t) sk(t)∑kwk κk(t)\hat q(x,t) = \frac{\sum_k w_k\,\kappa_k(t)\,s_k(t)}{\sum_k w_k\,\kappa_k(t)}

Learners report κ=min⁡(1,n/n0)\kappa = \min(1, n/n_0) 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

conf=eU1/τ∑jeUj/τ,τ=0.1\text{conf} = \frac{e^{U_1/\tau}}{\sum_j e^{U_j/\tau}}, \quad \tau = 0.1

Low confidence (or high normalised entropy H/log⁡∣T∣H/\log|\mathcal T|) 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

θt∼Beta(αt,βt)\theta_t \sim \mathrm{Beta}(\alpha_t,\beta_t); on reward r∈[0,1]r\in[0,1]: αt+=r\alpha_t \mathrel{+}= r, βt+=1−r\beta_t \mathrel{+}= 1-r. Optional forgetting α←α0+γ(α−α0)\alpha \leftarrow \alpha_0 + \gamma(\alpha-\alpha_0) for non-stationarity.

4.2 UCB1 — math.bandits.UCB1

μ^t+c2ln⁡n/nt\hat\mu_t + c\sqrt{2\ln n / n_t} (Auer, Cesa-Bianchi & Fischer 2002).

4.3 LinUCB (contextual) — math.bandits.LinUCB, learning.LinUCBStrategy

Per arm At=I+∑xx⊤A_t = I + \sum x x^\top, bt=∑rxb_t = \sum r x, θ^t=At−1bt\hat\theta_t = A_t^{-1} b_t, score x⊤θ^t+αx⊤At−1xx^\top \hat\theta_t + \alpha\sqrt{x^\top A_t^{-1} x} (Li et al., WWW 2010). Context xx = 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 =inner(t)−λct= \text{inner}(t) - \lambda c_t with dual ascent λ←max⁡(0,λ+η(cˉ−B))\lambda \leftarrow \max(0, \lambda + \eta(\bar c - B)) so average spend tracks budget BB (C2MAB-V, Dai et al. 2024).

4.5 Item Response Theory (2PL) — math.irt.IRTModel, learning.IRTStrategy

P(success∣t,i)=σ(ai(θt−bi))P(\text{success}\mid t,i) = \sigma\big(a_i(\theta_t - b_i)\big)

Target ability θt\theta_t, item (domain × difficulty bucket) difficulty bib_i, discrimination aia_i; 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

P(i≻j)=σ(ξi−ξj)P(i \succ j) = \sigma(\xi_i - \xi_j)

Learned per domain → a prompt-specific leaderboard (Prompt-to-Leaderboard, Frick et al. 2025; RouteLLM preference data). Selection probability via Luce: P(t)=eξt/∑keξkP(t) = e^{\xi_t}/\sum_k e^{\xi_k}.

4.7 Markov chain & MDP — math.markov, learning.MarkovStrategy

Conversation state ss = dominant domain. Transition matrix with Dirichlet smoothing

Pij=nij+α∑knik+α∣S∣P_{ij} = \frac{n_{ij} + \alpha}{\sum_k n_{ik} + \alpha|S|}

kk-step prediction πPk\pi P^k, first-passage probability to escalate, stationary distribution by power iteration, next-state entropy. Routing MDP (value iteration): V(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s)V(s′)]V(s) = \max_a\Big[R(s,a) + \gamma\sum_{s'}P(s'|s)V(s')\Big]MarkovStrategy scores (1−β) Q(s,a)+β∑s′P(s′∣s) Q(s′,a)(1-\beta)\,Q(s,a) + \beta\sum_{s'}P(s'|s)\,Q(s',a) — prefer targets that are also good for where the conversation is going.

4.8 Drift detection — math.estimators

  • Page–Hinkley: mT=∑t≤T(xt−xˉt−δ)m_T=\sum_{t\le T}(x_t-\bar x_t-\delta), alarm if max⁡tmt−mT>λ\max_t m_t - m_T > \lambda.
  • ADWIN-lite: split window, Hoeffding bound ϵ=12mln⁡4δ\epsilon=\sqrt{\tfrac{1}{2m}\ln\tfrac{4}{\delta}}. AutoLearner flags drifted targets; HealthStrategy/HealthPolicy can 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 q=norm⁡(W ϕ(x)+Attn⁡(x))q = \operatorname{norm}\big(W\,\phi(x) + \operatorname{Attn}(x)\big) over hashed word / bigram / character-gram features ϕ(x)\phi(x) (and an optional one-block transformer with sinusoidal positions and attention pooling), one learned embedding ete_t and bias btb_t per target, logit st=q⊤et/τ+bts_t = q^\top e_t/\tau + b_t. Losses are softmax cross-entropies over the row's candidate set: multi-positive InfoNCE over the acceptable set PP (RouterDC), L=−log⁡∑p∈Pesp/∑cesc\mathcal L = -\log \sum_{p\in P} e^{s_p} / \sum_{c} e^{s_c}, or Zooter distillation towards y=softmax⁡(r/T)y = \operatorname{softmax}(r/T) of per-target scores rr. Training is SGD with inverse-time decay ηe=η0/(1+e λ)\eta_e = \eta_0/(1+e\,\lambda), 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 1−p1-p, drawn once per fit) and, optionally, labels are smoothed y←(1−ϵ) y+ϵ/∣C∣y \leftarrow (1-\epsilon)\,y + \epsilon/|C|. Reported probabilities are temperature-scaled on the validation rows, p=softmax⁡(s/T\*)p = \operatorname{softmax}(s/T^\*) with T\*T^\* 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 =(cues/n+[asks])⋅((1−ν)+ν r)= (\text{cues} / \sqrt{n} + [\text{asks}]) \cdot ((1-\nu) + \nu\, r) with rr the share of the sentence's words seen at most twice in the prompt and ν\nu the novelty weight - placed first; and a long prompt's query is q=norm⁡(q^window+a q^ask)q = \operatorname{norm}(\hat q_{\text{window}} + a\,\hat q_{\text{ask}}), the unit vectors of the window view and of the asking sentences alone at weight aa. 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 C=d−/(d++d−)C = d^-/(d^+ + d^-) to the ideal point.
  • Weighted sum (the default scalarisation).

6. Real-time capacity — math.decision

  • Erlang-C: P(wait)=Acc!11−ρ∑k<cAkk!+Acc!11−ρP(\text{wait}) = \dfrac{\frac{A^c}{c!}\frac{1}{1-\rho}}{\sum_{k<c}\frac{A^k}{k!} + \frac{A^c}{c!}\frac{1}{1-\rho}}, A=λ/μA=\lambda/\mu, ρ=A/c\rho=A/c.
  • Mean wait Wq=P(wait)/(cμ−λ)W_q = P(\text{wait})/(c\mu - \lambda); servers_for_sla sizes a human/agent pool.
  • Little's law L=λWL=\lambda W.
  • Kingman G/G/1: Wq≈ρ1−ρ⋅ca2+cs22⋅τW_q \approx \frac{\rho}{1-\rho}\cdot\frac{c_a^2+c_s^2}{2}\cdot\tau for bursty LLM endpoints.

7. Resilience state machines — realtime

Circuit breaker (closed → open after kk failures in window WW → half-open after TrT_r → 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 =0.6 1+max⁡2+0.4 1+meank2= 0.6\,\tfrac{1+\max}{2} + 0.4\,\tfrac{1+\text{mean}_{k}}{2} (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 xx (host hidden state, or any embedding) outputs concentrations αk=1+softplus(wk⊤x+bk)\alpha_k = 1 + \mathrm{softplus}(w_k^\top x + b_k) of a Dirichlet over the KK targets, S=∑kαkS=\sum_k \alpha_k. Prediction P(best=k)=αk/SP(\text{best}=k)=\alpha_k/S; epistemic uncertaintyu=K/Su = K/S (all evidence near zero gives u→1u\to 1). Training minimises the expected cross-entropy under the Dirichlet plus a KL term that removes evidence from wrong classes (Sensoy et al., 2018):

L=∑kyk(ψ(S)−ψ(αk))+λ KL ⁣(Dir(α~) ∥ Dir(1)),α~=y+(1−y)⊙α,\mathcal L=\sum_k y_k\big(\psi(S)-\psi(\alpha_k)\big)+\lambda\,\mathrm{KL}\!\big(\mathrm{Dir}(\tilde\alpha)\,\|\,\mathrm{Dir}(\mathbf 1)\big),\qquad \tilde\alpha = y + (1-y)\odot\alpha,

by SGD with ψ\psi (digamma) and ψ′\psi' (trigamma) in pure Python. HiddenStateStrategy uses 1−u1-u 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 nn sampled answers by meaning (cosine over hashed or real embeddings, threshold τ\tau); with cluster mass pcp_c, H=−∑cpclog⁡pcH=-\sum_c p_c\log p_c (nats; response_uncertainty normalises by log⁡n\log n). Agreement =max⁡cpc= \max_c p_c.
  • P(True) (Kadavath et al., 2022): an optional judge returns P(answer is correct)P(\text{answer is correct}).
  • response_uncertainty u=0.5 H~+0.3 (1−agreement)+0.2 min⁡(1,hedging)u = 0.5\,\tilde H + 0.3\,(1-\text{agreement}) + 0.2\,\min(1,\text{hedging}), and with a judge u←0.6 u+0.4 (1−P(True))u \leftarrow 0.6\,u + 0.4\,(1-P(\text{True})); UncertaintyGate returns 1−u1-u as a cascade quality gate. EventTrigger fires named actions on threshold crossings (2607.13048).

12. Optimal stopping during generation — strategies.escalation.SelfEscalation

Competence θ∼Beta(a,b)\theta\sim\mathrm{Beta}(a,b), prior centred on the target's quality_prior. Each streamed chunk adds pseudo-counts: hedges +0.8+0.8, refusals +1.5+1.5, self-corrections +0.6+0.6, repetition +1.0+1.0, length overrun +0.5+0.5 to bb; clean progress +0.4+0.4 to aa. After each chunk

escalate iffθ<θ0 ∧ cesc+ctok(t+T)  <  (1−E[θ]) cfail+ctok (T−t),\text{escalate iff}\quad \theta<\theta_0\ \wedge\ c_{\text{esc}} + c_{\text{tok}}(t + T) \;<\; (1-\mathbb E[\theta])\,c_{\text{fail}} + c_{\text{tok}}\,(T-t),

where tt is tokens decoded, TT 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 Rt=∑s≤trsR_t=\sum_{s\le t} r_s crosses a latent threshold; a fraction π\pi of tasks is cured and never fails; tasks that end without failing are censored.

P(fail by R)=(1−π)(1−e−(R/λ)k),P(uncured∣alive at R)=(1−π)SW(R)π+(1−π)SW(R).P(\text{fail by }R)=(1-\pi)\big(1-e^{-(R/\lambda)^k}\big),\qquad P(\text{uncured}\mid\text{alive at }R)=\frac{(1-\pi)S_W(R)}{\pi+(1-\pi)S_W(R)}.

MixtureCureModel.fit() maximises the censored likelihood (density for failures, survival for censored) over a grid in (π,λ,k)(\pi,\lambda,k) with one refinement. HandoffPolicy hands over permanently when P(uncured∣R)≥τP(\text{uncured}\mid R)\ge\tau or the probability of failing within the next hh steps at the trajectory's mean step risk exceeds τh\tau_h (TACIT-Switch 2608.27911).

14. Error-aware reverse auction — strategies.auction.AuctionStrategy

Bidder ii claims success p^i\hat p_i at price cic_i. Its claim is corrected by the observed bias βi=p^i−ri‾\beta_i=\overline{\hat p_i - r_i} and realised rate rˉi\bar r_i with shrinkage wi=ni/(ni+κ)w_i=n_i/(n_i+\kappa): p~i=(1−wi2)(p^i−wiβi)+wi2rˉi\tilde p_i=(1-\tfrac{w_i}{2})(\hat p_i-w_i\beta_i)+\tfrac{w_i}{2}\bar r_i. Surplus si=p~iV−cis_i=\tilde p_i V - c_i; the highest surplus wins and pays the second price max⁡ ⁣(cw, p~wV−s(2))\max\!\big(c_w,\ \tilde p_w V - s_{(2)}\big) so over-claiming is not rewarded (EA-RAM 2608.12719).

15. Energy and carbon — math.energy

Per target, ridge regression on measured samples gives Wh=e0+ein nprompt+eout noutput\mathrm{Wh}=e_0+e_{\text{in}}\,n_{\text{prompt}}+e_{\text{out}}\,n_{\text{output}} (normal equations, 3×33\times3 solve); gCO2=Wh⋅g/1000\mathrm{gCO_2}=\mathrm{Wh}\cdot g/1000 with the grid factor gg. Without a meter, HardwareProfile estimates Wh=TDP⋅PUE⋅(tprefill+tdecode+tfixed)/3600\mathrm{Wh}=\mathrm{TDP}\cdot\mathrm{PUE}\cdot (t_{\text{prefill}}+t_{\text{decode}}+t_{\text{fixed}})/3600 from the accelerator's throughput (2608.28044; HW-Router).

16. Personalisation by shrinkage — learning.personal.UserAdaptiveStrategy

p^u,t=wu θˉu,t+(1−wu)[wn θˉN(u),t+(1−wn) θˉ⋅,t]\hat p_{u,t}=w_u\,\bar\theta_{u,t}+(1-w_u)\big[w_n\,\bar\theta_{N(u),t}+(1-w_n)\,\bar\theta_{\cdot,t}\big], w=nn+κw=\tfrac{n}{n+\kappa}: a user's own Beta posterior, the similarity-weighted posterior of the kk 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 κ\kappa outcomes (GMTRouter 2511.08590).

17. Multi-turn joint embeddings — learning.multiturn.HistoryTargetStrategy

History vector h=normalise(∑kλk ϕ(mn−k))h=\mathrm{normalise}\big(\sum_k \lambda^{k}\,\phi(m_{n-k})\big) over the last KK role-tagged messages and the current text (ϕ\phi = hashed word/bigram embedding, λ<1\lambda<1 recency decay); target vector ete_t = catalogue embedding. Joint feature z=d (h⊙et)z=\sqrt{d}\,(h\odot e_t) and

p^(success∣h,t)=σ(w⊤z+bt),\hat p(\text{success}\mid h,t)=\sigma\big(w^\top z+b_t\big),

a bilinear form with a diagonal weight matrix shared by every target; only btb_t is target-specific, so an unseen target is scored through ete_t alone (inductive). Online logistic SGD on the reward with L2 shrinkage; btb_t is initialised at logit(quality_prior)\mathrm{logit}(\text{quality\_prior}). Confidence 0.15+0.85 nt/(nt+κ)0.15+0.85\,n_t/(n_t+\kappa). Incumbent continuity adds ±\pmstay_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.