Model Routing
models-router selects and, when asked, invokes a model from a mixed fleet of
in-process and hosted clients. The application supplies the clients it already
uses. The router does not embed OpenAI, Anthropic, or another provider SDK.
dependencies {
implementation("com.integrallis:models-router:0.5.20")
}
Bind Local And Hosted Clients
ModelFleet<T> is provider-neutral: T can be a Spring AI ChatModel, a
LangChain4j model, or an application interface. This Spring AI fleet combines
a local Models adapter and an existing hosted client:
ChatModel local = localModelsChatModel;
ChatModel hosted = hostedSpringAiChatModel;
var fleet = ModelFleet.<ChatModel>builder()
.model(ModelCandidate.builder("local/qwen3")
.local(true)
.costPerMillionTokens(0, 0)
.timeToFirstTokenMillis(180)
.tokensPerSecond(24)
.quality(Map.of("chat", 0.82))
.build(), local)
.model(ModelCandidate.builder("hosted/frontier")
.local(false)
.costPerMillionTokens(2.50, 10.00)
.timeToFirstTokenMillis(450)
.tokensPerSecond(70)
.quality(Map.of("chat", 0.96))
.build(), hosted)
.policy(RoutingPolicy.LOCAL_FIRST)
.build();
ChatModel routed = new RoutedSpringAiChatModel(
fleet,
prompt -> RoutingRequest.builder(prompt.getContents())
.sessionId("conversation-42")
.build());
var chatClient = ChatClient.builder(routed).build();
The selected delegate receives the original Spring AI Prompt, including its
messages, tools, model options, and metadata. RoutedChatModel and
RoutedStreamingChatModel provide the same boundary for LangChain4j
ChatRequest instances.
Blocking calls try the ranked fallbacks when a client fails. Streaming calls may fall back only before the first response fragment reaches the application; switching after that point would combine output from two models.
Standard CancellationException and InterruptedException signals, including signals nested in
SDK cause chains, stop fallback without recording a model-health failure. Blocking interruption
restores the caller’s interrupt flag. Streaming adapters preserve the original error signal;
they do not interrupt an asynchronous callback thread. Spring subscription disposal propagates
upstream cancellation. Ordinary provider timeouts remain eligible for fallback before content
has been emitted. LangChain4j’s newer rich callback/cancellation-context forwarding still needs
separate qualification; this change handles cancellation delivered as an error or thrown by a client.
Per-Request Capabilities And Data Boundaries
All three framework adapters accept a fourth constructor argument that maps the complete
original Prompt or ChatRequest to RoutingRequirements. That mapping can inspect history,
tool results, options, and application metadata instead of relying only on the latest user text.
The requirements apply to the winner and every fallback, including streaming fallback:
ChatModel routed = new RoutedSpringAiChatModel(
fleet,
prompt -> RoutingRequest.builder(prompt.getContents()).build(),
prompt -> RoutingContinuity.builder()
.activeToolLoop(!prompt.getInstructions().isEmpty()
&& prompt.getInstructions().getLast() instanceof ToolResponseMessage)
.build(),
prompt -> RoutingRequirements.builder()
.requireCapability("tool-calling")
.dataBoundary(RoutingDataBoundary.LOCAL_ONLY)
.build());
This example permits only candidates declared local and tool-capable. If none remain, routing
fails before invoking a client. Declare capabilities with ModelCandidate.Builder.capabilities;
quality/task tags do not grant capabilities. The same four-argument constructor is available on
RoutedChatModel and RoutedStreamingChatModel.
The application owns this policy: the adapters do not automatically classify PII, infer required
modalities, or validate a client’s locality declaration. Existing constructors use
RoutingRequirements.none(). A requirements factory returning null fails before any client is
invoked. Spring AI evaluates the factory once per stream subscription; blocking calls and
LangChain4j streaming evaluate it once per invocation.
How A Decision Is Made
Routing happens in two stages:
-
Hard constraints remove models that are unavailable, cooling down, too small for the prompt, outside a price or latency ceiling, below a quality floor, or rejected by an application
CandidateFilter. -
Named scorers rank the eligible models by the selected policy, task quality, cost, TTFT, reliability, locality, cache affinity, residency, queue depth, and any application
CandidateScorer.
Immutable catalog or application measurements are the cold-start priors. Live state and explicit outcomes refine those priors:
var router = fleet.router();
router.updateRuntimeState("local/qwen3", ModelRuntimeState.builder()
.available(true)
.resident(true)
.queueDepth(0)
.build());
router.record(RoutingFeedback.success("local/qwen3")
.sessionId("conversation-42")
.timeToFirstTokenMillis(143)
.tokensPerSecond(26.4)
.tokenUsage(920, 780)
.build());
Feedback updates bounded exponential moving averages. Repeated failures place
a candidate in a temporary cooldown. RoutingDecision.explain() and
scoreBreakdown() expose why a model won.
Conversation Continuity And Caches
A session id creates bounded, expiring affinity; it does not permanently pin the first model. A challenger must clear the configured switch margin before the router moves an ordinary conversation. Active tool loops and explicitly non-portable provider state are hard-locked to the current healthy model by default:
var request = RoutingRequest.builder(question)
.sessionId(conversationId)
.estimatedTokens(promptTokens)
.build();
var continuity = RoutingContinuity.builder()
.activeToolLoop(waitingForToolResult)
.contextPortable(!providerOwnsConversationState)
.cachedPrefixTokens("local/qwen3", locallyReusableTokens)
.cachedPrefixTokens("hosted/frontier", providerReportedCachedTokens)
.build();
RoutingDecision decision = router.route(request, continuity);
KV tensors are valid only for the model weights and runtime that created them,
so the router never moves a KV cache between different models. Cached-token
counts instead add affinity to the specific model that can reuse them. The
Models generation loop already reuses exact prefixes for a compatible local
model; hosted cached-token measurements can be reported through
RoutingFeedback.
Session state defaults to a five-minute idle timeout and 1,024 entries. Use
AdaptiveRoutingOptions to tune those bounds, and call closeSession(…)
when a conversation ends.
For one semantic conversation that routes directly among independently stateful local Models sessions, including member-specific templates, constraints, KV-prefix accounting, and optional background catch-up, see Virtual Models.
Extension Points
Use a CandidateFilter for non-negotiable application rules such as tenant
residency or a required capability. Use a named CandidateScorer for a
preference such as region proximity. Scorers return a value from zero to one,
and their named weighted contribution appears in the routing explanation.
Keep hard rules in filters. A model that cannot satisfy a request should not win merely because unrelated scores compensate for it.
Request Accounting, Budgets And Completion Deadlines
The price ceiling is a candidate filter. To limit total spending, use execution controls:
// Reuse this object for every request in this session (or tenant).
var sessionBudget = new RoutingBudget(new java.math.BigDecimal("2.00"));
var controls = RoutingExecutionOptions.builder()
.tokenBounds(new RoutingTokenBounds(4000, 512))
.requestBudget(new java.math.BigDecimal("0.10"))
.sharedBudget(sessionBudget)
.timeout(java.time.Duration.ofSeconds(20))
.build();
var result = fleet.execute(request, requirements, continuity, controls,
client -> client.call(originalRequest),
response -> new RoutingUsage(response.inputTokens(), response.outputTokens()));
The last two lambdas adapt your own client and response types. Return null for missing usage;
never substitute zero. Prices and limits must use one currency. Each attempt reserves its full
input/output bound atomically in the shared account. Known usage settles the actual token cost;
failed, cancelled or unknown usage retains the full reservation. Reservations and settlement are
idempotent. A rejected reservation can try a cheaper eligible fallback without invoking or
penalizing the rejected model. All retries consume the same request and shared budgets.
sessionBudget.snapshot() exposes spent, reserved and available amounts. This ledger is in-process;
sharing a budget across JVMs requires an application-owned external admission service.
The input bound covers all history, system instructions, tool definitions/calls/results,
attachments, provider framing and hidden state. Input plus reserved output is used for context
admission. Both adapter packages expose RoutingRequests.account(…): supply model-specific
text and media counters, additional provider overhead, and an output reserve. No attachment is
fetched to count it. Standard tool descriptions are included, but their exact vendor serialization,
unresolved Spring tool names and vendor-specific state need an additional application bound.
In a mixed fleet use bounds valid for every eligible tokenizer/provider, or use separate fleets.
The default adapter request factory now estimates the entire standard text history and tools using
UTF-8 bytes plus message framing and the explicit output limit. This is a context estimate, not a
universal tokenizer bound or a spending guarantee. Media requires an explicit accounting factory.
Custom request factories remain supported. To use execution controls with a framework adapter,
pass a fifth constructor argument: a function from the complete ChatRequest or Prompt to
RoutingExecutionOptions. The original provider request is passed to the delegate public API. LangChain4j delegates receive
chat(…), allowing their SDK to apply provider-specific defaults and listeners before its
internal doChat(…) hook. Explicit request options retain precedence over those defaults.
Include provider defaults that add prompt content or tools in the accounting overhead.
Budgeted adapter calls require an explicit maxOutputTokens (LangChain4j) or maxTokens (Spring)
within the reserved output bound. Spring AI 1.x internal tool execution must be explicitly disabled;
route each tool turn separately. Disable billable SDK retries and hidden multi-call behavior in
application-owned clients. A provider can still ignore its cap, report different billing units,
or continue working after cancellation. Such behavior cannot be controlled by this ledger. If
reported token usage exceeds a bound, actual cost is recorded and execution fails without fallback.
A late response after cancellation does not refund the conservative reservation. Local electricity
and infrastructure costs are not inferred from zero token prices.
The deadline starts before classification and spans retries and the entire stream; chunks do not
reset it. It uses monotonic time. Blocking controlled calls run on a virtual thread, so deadline or
explicit cancellation can return while an uncooperative provider is still running. Applications
that depend on thread-local state must propagate it in their supplied client. Provider interruption
and cancellation are best effort. RoutingCancellationToken supports cancellation before the first
response. Spring subscriber disposal cancels upstream and retains unknown usage. LangChain4j forwards
all callbacks supported by the runtime SDK, including thinking, tools, raw events and original
cancellation contexts; any observable event prevents switching providers. Use the explicit token
when cancellation must be observable even if the provider never sends another callback.
A local-only boundary also applies to classification and its embedding call. Unknown classifiers
are treated as potentially remote. Wrap an entirely local classifier with
TaskClassifier.local(classifier), or provide a task override. Budgeted calls likewise require a
local classifier or an override so classification cannot silently create unaccounted API spend.
The declaration is the application’s responsibility; it is not a network sandbox.
A hard continuity lock removes other models from the fallback list. For an active tool loop or
non-portable state, supply a live session or RoutingContinuity.builder().ownerModelId(id).
Missing/conflicting ownership or an owner that violates current requirements fails closed.
Explicitly disabling the corresponding adaptive hard-lock option retains its previous opt-out
meaning and makes portability the application’s responsibility.
Selection Quality Evaluation
models-bench provides router-evaluate MANIFEST.json REPORT.json for paired observation replay.
It requires multiple datasets, disjoint calibration/evaluation prompts, pinned input hashes and
complete observations from every model. It compares each model, static cheapest, static best chosen
on calibration, the router, and classifier/quality/performance ablations. See
models-bench/router-evaluation.md for the input contract and collection protocol.
Replay measures selection against reference answers and reports per-dataset/task quality, cost, latency distributions, budget/deadline violations and changed selections under ablation. It is not live-provider SLA or cancellation qualification. Synthetic regression fixtures test the evaluator; they do not establish model capability. No new multi-dataset model-quality claim accompanies these execution-control changes.
