Scrivio Interview library
AI10 October 202612 min read

How LinTS and bandits choose models in an AI gateway

Four Models Behind One Endpoint#

An AI gateway is a single endpoint that sits in front of several language models and forwards each incoming request to one of them. Model routing is the choice it makes on every request: which model should answer this one. In most gateways that choice comes from a rule somebody typed into a config file, and the rule never finds out whether it chose well.

Call the running example the four-model gateway: four models behind one endpoint, spanning a wide range of price and capability. In a lineup like this the premium model can cost considerably more per token than the cheapest one (a token is a chunk of text, usually a word or part of one), with latency and answer quality spread out in between. Picking among them is a balance of cost, latency, and accuracy, and teams weight those factors differently, some chasing low latency, others accuracy or cost-efficiency1. So a request arrives (400 tokens of prompt, a summarization task, a customer on the free tier), the rule sends it to the mid-sized model, and the answer is fine. Whether the cheapest model would also have been fine is unknowable, because the cheapest model never saw the request.

The facts you actually have at decision time are modest but real: how long the prompt is, what kind of task it looks like, and which tenant tier the caller belongs to. A config file turns those three facts into a fixed mapping. Free tier plus short prompt goes to the small model; enterprise tier plus anything long goes to the expensive one; a hand-tuned percentage split covers the murky middle. Every one of those lines is a bet placed once and never settled, because a request routed to one model produces no information at all about the other three.

That is the driving question for everything that follows: how can a gateway learn which model was good enough on a request it never sent there? The static config cannot answer it, and neither can a dashboard built on top of the config, since the data it summarizes only ever describes the choices the config already made. Spend six months routing all long legal-summarization prompts to the premium model and you will have six months of evidence that the premium model handles them, and none about the cheaper alternative that might have handled them too.

The good news is that the gateway is the right place to fix this. Pointing traffic at it is a base-URL substitution, swapping https://api.cohere.ai/v1 for the gateway's Cohere endpoint, for example2, and on platforms like Cloudflare's the gateway can even create itself on the first authenticated request3. Once that substitution is done, a single component sees every request going out and every response coming back. It already holds both halves of the thing we want to learn from. What it lacks is a decision rule that treats each route as a question worth asking.

A Bandit Is a Choice You Learn From#

A bandit problem is one where you repeatedly choose among several options, only ever observe the outcome of the option you picked, and are expected to get better at choosing anyway. The name comes from slot machines: each machine is an "arm" you can pull, and nobody tells you the payout rates. Send a request to one of your four models and you learn how that answer turned out. What the other three would have produced for the same request is unavailable, permanently, no matter how much you log. That missing comparison is the whole difficulty.

"Contextual" adds the part that matters for a gateway: some description of the request arrives before each choice, and the reward depends on it. That description is the context vector, which is just a short list of numbers standing for the request. Three features follow this example the whole way: prompt length, task type, and tenant tier. A single request might show up as 1,800 tokens, task type "code generation", tenant tier "enterprise", with the categorical fields one-hot encoded, meaning each possible task type and each tier gets its own slot, set to 1 when it applies and 0 when it does not. The formal setting matches this closely: there are N arms, and at each round a context vector in d dimensions (a list of d numbers) is revealed for every arm before the learner commits to one4.

What turns that list into a decision is a weighted score. Every slot in the context gets a weight saying how much it pushes reward up or down for a given model: long prompts might count against the small open-weights model, while the enterprise tier counts in favor of the expensive one. Multiply each feature by its weight, add the products, and the total is the predicted reward. That sum has a name in notation, the dot product. The linear-payoff model says the reward for arm i at round t comes from an unknown distribution with mean b_i(t)^T μ, where μ is a fixed but unknown weight vector shared across all rounds4. Linear means nothing fancier than that one weighted sum: no feature gets multiplied by another.

You never get to see μ. What you see is noisy rewards, one request at a time, which means every weight estimate you hold is provisional and some are barely informed at all. Which sets up a question that sounds backwards on first reading: why would it ever pay to deliberately route a request to a model your current estimate says is worse? Doing exactly that, on purpose, is what LinTS is built on, and the reason arrives with the algorithm.

The algorithm itself is not new or exotic. Thompson Sampling is one of the oldest bandit heuristics, a randomized method built on Bayesian ideas, which is to say it holds a belief about each option and revises that belief as evidence arrives. It drew renewed attention because several studies showed better empirical performance than the state of the art well before its theoretical properties were understood5. Before applying any of it, the three pieces need real definitions on your gateway: what counts as an arm, what goes into the context vector, and where a reward number actually comes from.

Your Gateway in Three Pieces: Arms, Context, Reward#

The four models sitting in that config file map onto the bandit vocabulary almost mechanically:

Bandit pieceYour gateway
Armsthe four candidate models you are allowed to route to
Contextfeatures of the request you have before you route: prompt length, task type, tenant tier
Rewarda single number per served request, computed once the response comes back

Arms and context cost you nothing: you already have the model list, and the request fields are sitting in the handler. Reward is the part you build, and it is where the whole thing is won or lost, because "better model" is not a measurable quantity until you decide what you meant by better.

Start with quality, which is the hard signal. Cost and latency arrive for free with every response; quality has to be supplied by a feedback channel you choose: a benchmark grader while you are evaluating offline, or in production an operator-defined validator, a model-based judge, or a user-feedback signal6. Cloudflare's AI Gateway takes the logs route: you filter the Logs tab into a dataset and run evaluators over it, and its first evaluator is human feedback, currently in open beta1. None of these is cheap. All of them beat the alternative of having no quality number at all, which leaves you optimizing for whichever model is fastest and most wrong.

The rest is arithmetic, with one trick in it. Dollars and milliseconds cannot be added, so each is divided by a calibration constant set per deployment and clipped at 1: cost becomes min(1, c/c_max) and latency becomes min(1, l/l_max)6. Both now live on the same 0-to-1 scale as the quality score, so a single weighted sum makes sense: reward is the quality score minus the weighted normalized cost, minus the weighted normalized latency, minus an operational penalty for discrete failures such as rate-limiting or malformed output6. Reasonable defaults put quality at 1.0, cost at 0.4, latency at 0.3, a rate-limit hit at 0.5, and a format failure at 0.36.

Say a tenant sends a short classification prompt, with c_max set to $0.02 per call and l_max to 3,000 ms. The premium model grades 0.9, costs $0.011, takes 2,400 ms: reward 0.9 - 0.4(0.55) - 0.3(0.8) = 0.44. The cheap model grades 0.6, costs $0.001, takes 600 ms: reward 0.6 - 0.02 - 0.06 = 0.52. On this request the cheap model is genuinely the better choice, and the weights are where your own priorities enter, since some teams want low latency and others accuracy or cost-efficiency1. Change the weights and you change which model wins, which is the honest version of the knob you were turning by hand.

One more detail from the same request: if that cheap response comes back as unparseable JSON, the 0.3 format penalty drops it to 0.22 and the premium model wins. With a number like that attached to every served request, learning which arm suits which context turns into an ordinary fitting problem, one per model: find the weights that best explain the rewards that model has earned.

LinTS: Draw a Sample, Route to the Winner#

Here is one request moving through the four-model gateway, start to finish:

Python
def route(request):
x = features(request) # context vector: token count, task type, latency budget
scores = {}
for model in ("gpt-4o", "claude-sonnet", "llama-70b", "mistral-small"):
w = sample(posterior[model]) # one draw from this model's current belief
scores[model] = w @ x # the weighted score from Section 2
choice = max(scores, key=scores.get)
reward = observe(choice, request) # quality, cost and latency rolled into one number
posterior[choice] = update(posterior[choice], x, reward)
return choice

Nine lines, and every one of them is the actual algorithm. LinTS is the Agrawal and Goyal (2013) method for contextual bandits with linear reward models: observe a context, sample reward weights from each arm's Gaussian posterior, pick the arm with the largest predicted reward, update the posterior of the arm you played7. The formal setting matches the gateway exactly: with N arms, a context vector in R^d is revealed for every arm at each round before the learner chooses one4. Your four models are the arms; x is that vector.

The word posterior is doing real work in line 5, and it means something plain: the current belief about a model's weights, including how unsure you are about them. Gaussian describes the shape of that belief, a bell curve with a most-likely set of weights in the middle and a spread around it. The agent never learns the true reward distribution. It keeps a belief over each arm's linear weights, and sampling from that belief is what produces exploration, with no ad-hoc parameters to tune7.

This answers the question left open earlier, the one about routing to a model you expect to be worse. A model that has served thirty requests has a wide posterior, so sample returns a noticeably different w each call, and on some fraction of requests that draw scores highest and wins the route. That is the exploration. The mirror image matters just as much: once mistral-small has ten thousand measured requests and its weights are pinned down as mediocre for long-context summarization, its draws stop landing in first place for that context, and the traffic quietly stops.

Set that against the hand-written config split:

ApproachWho sets the exploration rateDoes the explore share decayDoes it vary by request type
Fixed-percentage split (70/20/5/5)A human, by hand, in a config fileNo, not until someone edits the fileNo, the same split applies to every request
LinTSNobody; it falls out of posterior widthYes, automatically, as data accumulatesYes, per context vector

Nobody picks an exploration percentage, nobody schedules its decay, and there is no separate A/B phase that someone has to remember to end. The approach sits at the intersection of online learning and Bayesian inference, and it runs in production inside recommendation pipelines at Yahoo7, which is to say it is a baseline rather than an experiment.

Two lines in that loop are yours rather than the algorithm's: where observe gets its quality number, and what posterior holds on the very first request, before any traffic has arrived.

Rolling It Out Without Breaking Production#

So what do you turn on first? Not the router. The first three stages of a LinTS rollout on your four-model gateway change nothing about which model serves a request; they only make the gateway able to tell, later, whether a different choice would have been better. If you are already proxying through a gateway, the decision point exists (Cloudflare's gateway will even create itself under the ID default on the first authenticated request if you omit the ID)3, so this is a logging and scoring exercise before it is a routing one.

Stage one: log the context vector. Write the feature vector you would feed the model alongside the model actually chosen: prompt token count, task tag, tenant tier, whether tools are requested, time of day. What you learn is whether your features have any spread at all; if 95% of requests land in one bucket, your context is not yet informative enough to route on.

Stage two: write and backfill the reward. Compute a single number per request from the quality, cost, latency and operational-penalty terms defined above6, then recompute it over the logs you already have. For example:

Python
def reward(log, w_q=1.0, w_c=0.3, w_l=0.2):
cost = min(1.0, log["cost_usd"] / 0.02) # per-call budget scales
latency = min(1.0, log["latency_ms"] / 4000) # are yours to pick
penalty = 0.5 * log["rate_limited"] + 0.5 * log["format_failed"]
return w_q * log["quality"] - w_c * cost - w_l * latency - penalty

The backfill is where you find out whether your weights say what you meant. Flip w_c from 0.3 to 0.8 and watch which model wins the historical traffic.

Stage three: shadow mode. Run LinTS sampling for real and log the arm it would have picked, while the old rules still decide. What you learn is the disagreement rate per segment, and whether the historical reward of LinTS's choices beats the reward your rules actually collected.

Stage four: bounded live slice. Hand real routing to LinTS for a capped fraction of traffic with per-tier floors, so a premium tenant always gets the strong model and exploration happens on segments where a bad draw costs little.

Quality labels are the part the evidence actually covers: Cloudflare's evaluations build datasets by filtering the Logs tab, with human feedback as the first evaluator, in open beta1. The rest (how wide a floor, how long to shadow, what starting belief a brand-new arm should get) is your judgment on your traffic.

Day one is a text file: the reward formula with your weights, and the list of context features. Once both exist, the next model you add is a new arm with a wide posterior rather than another round of hand-tuning percentages.

Sources

  1. Evaluations · Cloudflare AI Gateway docsdevelopers.cloudflare.com
  2. Cohere · Cloudflare AI Gateway docsdevelopers.cloudflare.com
  3. Manage gateways · Cloudflare AI Gateway docsdevelopers.cloudflare.com
  4. Thompson Sampling for Contextual Bandits with Linear ...arxiv.org
  5. Thompson Sampling for Contextual Bandits with Linear Payoffsproceedings.mlr.press
  6. OrcaRouter: A Production-Oriented LLM Router with Hybrid Offline–Online Learningarxiv.org
  7. Contextual Bandit (Linear Thompson Sampling) Explainedmetricgate.com

Keep reading

AI10 October 2026

Chain of Thought or ReAct: Choosing Between Them

A support queue needs priorities. Every incoming ticket has to carry a label, P1 through P4, before it reaches a human, and you have been handed the feature. Two implementations...

13 min readRead the article
AI22 May 2026

How Spring AI Works: LLMs, Embeddings, and RAG for Java Engineers

Spring AI is a Spring Boot framework that connects Java applications to LLMs and vector stores using the same dependency-injection patterns Spring developers already know. Your...

20 min readRead the article
Career6 November 2026

What a forward deployed engineer does, and how to prepare

A forward deployed engineer is a software engineer who works inside the customer's organization rather than inside the product team. The job is to build and ship custom solutions...

12 min readRead the article