Semantic routing for LLMs sends each request to a model suited to its task, rather than using one expensive model for everything. Done well, it can reduce inference spend without making users pay for that saving in weaker answers. Start with your own traffic and quality criteria, then test the router against a fixed evaluation set before you send it live. Our AI automation team can help design that production path.
The principle sounds simple: use a lightweight model for routine work and reserve a stronger model for requests that need more reasoning, context or care. The difficult part is deciding which requests are safe to route down, and proving that the cheaper path still meets your standard. This guide walks through the design, implementation and operating decisions that make the difference.
What semantic routing for LLMs does, and what it does not do
A semantic router is a decision layer between your application and its model endpoint. It examines a prompt, estimates what kind of task it represents, and selects a model or route. The router may compare prompt embeddings with examples of known task categories, or use a small classifier trained to identify intent or difficulty.
The word semantic means that the system considers meaning, not just exact words. A rule that sends every message containing the word refund to a customer-service model is keyword routing. An embedding-based router can recognise that Please reverse the charge from last Tuesday is likely a billing request even when it does not contain the word refund.
Routing is not a quality guarantee. Similarity to a category example does not prove a model can answer the actual request. A prompt may look like routine summarisation but contain a high-stakes instruction, an unusual exception or a request that depends on a long conversation history. Routing should therefore combine semantic signals with simple rules, confidence thresholds, fallbacks and ongoing evaluation.
It also helps to separate three related approaches:
| Approach | Decision it makes | Good fit | Main limitation |
|---|---|---|---|
| Rules and metadata | Is this request allowed on this route? | Data boundaries, product tiers, fixed formats | Rules do not understand meaning well |
| Semantic or intent routing | What task or topic is this? | Clearly separated workflows such as extraction and FAQ handling | Similar topics can have very different difficulty |
| Difficulty routing | How much capability does this request appear to need? | Requests within one workflow that vary in complexity | Requires reliable labelled examples or comparisons |
| Cascade routing | Did the cheap model produce an acceptable answer? | Outputs with machine-checkable constraints | Escalation adds a second model call and latency |
These approaches can be combined. A rule can enforce data residency first, a semantic router can identify the task, and a validator can decide whether the result needs escalation. For a deeper overview of router patterns, see Aurelio AI’s semantic router documentation. The RouteLLM paper is useful for understanding a different problem: choosing between stronger and weaker models based on predicted preference or capability, rather than only matching a prompt to a topic.
What do you need before building a router?
Do not start by choosing an embedding model or a framework. First establish the workload, the cost you are trying to change and the quality failures you will not accept.
1. Request and response records
You need enough historical traffic to understand what people ask and what the application returns. Collect a representative sample from production logs, or from a controlled pilot if the system is not live. The research brief suggests reviewing 1,000 to 5,000 prompts. Treat that as a useful planning range, not a universal minimum. A narrow product with few task types may need fewer examples to reveal its patterns. A broad assistant with many workflows will need more variety.
For each record, keep the prompt and the context the model actually received, such as relevant conversation turns or retrieved documents. A prompt by itself can be misleading if the application supplies important context separately. Record the chosen model, response, latency, token use, tool calls, validation result and any user feedback that is available.
Remove or mask personal and confidential information before using records for analysis unless you have an approved basis and controls for processing it. Limit access to the sample and define a retention period. Routing work is not a reason to copy sensitive production data into a new third-party service.
2. A clear quality definition
Write down what acceptable means for each workflow. For a field extraction task, that could mean required fields are present, values match the source and the output passes a schema check. For an answer about an internal policy, it may mean the answer is supported by an approved source, does not invent a rule and knows when to abstain.
Avoid using a single score for everything. A concise summary, a correct calculation and a safe refusal are different outcomes. Include human review for cases where an automated score cannot establish correctness.
3. Current unit economics
Gather your actual provider rates, including input and output token prices, cached input treatment, tool charges and any platform or hosting costs. Model names and prices change. Do not base a December 2026 business case on an old comparison chart. Use the relevant provider’s current official pricing page when you calculate production economics, and record the date of the calculation.
Also check whether your current model mix already uses different models for different tasks. If so, the potential saving from routing is the difference between today’s system and a realistic routed system, not the price of sending every prompt to your most expensive model.
4. A path back to safety
Before writing routing code, decide what the system does when it is unsure. Typical choices include sending the request to a stronger model, asking a clarifying question, returning a safe message, or sending it to a human. The fallback is a product and risk decision, not an afterthought.
Step 1: Profile traffic and define the separation boundary
Start by grouping sampled requests into tasks that map to different model requirements. Do not make a category for every wording variation. Categories should represent a real change in the work the model must do.
A first pass might identify:
- Routine extraction from a known document format.
- Short, source-grounded FAQ answers.
- Basic classification or sentiment labelling.
- Standard formatting or schema conversion.
- Summarisation of short, bounded text.
- Multi-step analysis across several documents.
- Ambiguous requests that need clarification.
- High-impact decisions or advice that need review.
Then mark each category as a candidate for the lightweight route, a stronger route, a rule-based route or human review. Do not assume that all short prompts are easy. A short instruction to decide whether a disputed insurance claim is covered could have significant consequences. Do not assume that every long prompt needs a frontier model either. A long, predictable document can be summarised through a reliable workflow using a smaller model.
For each category, inspect both the prompt and the failure cost. Ask:
- Is the task bounded, with a clear expected output?
- Can the answer be checked against a source or schema?
- Does the task require several reasoning steps or trade-offs?
- Could a wrong answer cause material customer, financial, legal or safety harm?
- Is a human already expected to review the result?
If the answer to the first two questions is yes and the failure cost is low, the task may be a good candidate for a smaller model. If the task is ambiguous, high-impact or difficult to verify, keep it on a stronger route or add a human check.
A useful output from this step is a traffic map, not a vague statement that most prompts are easy. Count examples in each category, estimate input and output tokens, and note how often the answer requires tools or retrieved context. The traffic map will drive the cost model and test plan.
Step 2: Choose the routing method for each decision
There is no reason to use semantic similarity for every routing decision. Choose the simplest method that reliably answers the decision you need to make.
Start with rules for hard boundaries
Use deterministic rules for constraints that cannot be negotiated by a probability score. These can include tenant entitlements, permitted data locations, approved model lists, maximum context size or a route that must never call an external provider. Check these conditions before semantic routing.
Rules are fast and easy to audit. Their weakness is brittleness: they only cover conditions someone has anticipated. Use them to enforce boundaries, not to classify every natural-language request.
Use embeddings when task categories are distinct
An embedding turns text into a numerical representation that captures aspects of its meaning. A router can compare the incoming prompt’s embedding with examples for each route, then choose the closest route if it is sufficiently similar.
This is useful when workflows form clear groups, such as an invoice-field extraction route and a product FAQ route. It is less reliable when the same topic includes both simple and difficult requests. A question about payroll could ask for a basic definition or ask the system to reconcile a complex exception across records. Topic similarity alone does not tell you which model can solve it.
The Aurelio AI semantic router project describes a vector-based approach. Its reported latency depends on the specific deployment, hardware, embedding model and search method. Measure the overhead in your own stack rather than treating any published result as a service-level commitment.
Use a classifier when difficulty matters more than topic
A small classifier can estimate whether a prompt is likely to need a stronger model. This can help when requests have the same subject but vary in complexity, such as a coding assistant handling both a small syntax question and a multi-file change.
The RouteLLM research evaluates several model-routing methods and studies the trade-off between cost and response quality. Its benchmark results show what routing can achieve under those experimental conditions. They are not a forecast for your traffic, models or quality bar. Your application needs its own evaluation data.
Use a cascade when the answer has a reliable check
In a cascade, the low-cost model answers first. Your application validates the output and escalates if it fails a defined check. For example, a response that must follow a JSON schema can be parsed and checked for required fields. A failed parse is a clear reason to retry or escalate.
A valid schema does not prove that the values are correct. For factual extraction, compare values against the source where possible. For advice or reasoning, use more than a formatting check. Cascades are strongest when failures are observable and a second model call is an acceptable trade-off.
A practical system often combines all four methods: rules for policy, semantic routing for task type, a difficulty signal for borderline cases and validation for output quality.
Step 3: Build and label a representative evaluation set
Your router is a model in its own right. It makes mistakes, so you need examples that show whether it is making the right decision.
Split your records into a development set and a holdout set. Use the development set to create categories, tune thresholds and adjust rules. Keep the holdout set untouched until you compare candidate designs. If you keep tuning against the same examples you report as your final result, the evaluation will look better than performance on new traffic.
Label each example with at least:
- The intended task or route.
- Whether the lightweight model can handle it to your stated standard.
- Whether it needs a stronger model, a question, a human or a refusal.
- The failure impact if it takes the wrong route.
- Any output checks that can be applied automatically.
Have a knowledgeable person review a sample of labels, especially for borderline or high-impact cases. If reviewers disagree, record the disagreement. The uncertainty may mean the task definition is unclear, or that the system should ask the user for more information rather than make a confident route decision.
Include edge cases deliberately. Add prompts with multiple intents, unusual wording, long context, negation, quoted instructions, incomplete details and adversarial attempts to override system instructions. Historical logs show what users have asked so far. They do not cover every way the system can be used.
Step 4: Create route examples and tune thresholds
For an embedding router, write reference utterances that represent the actual request types in your evaluation set. A starting point of 15 to 30 examples per route is suggested in the research notes. Use it as an initial design target, not as a rule. What matters is that the examples cover varied wording without blending categories that require different treatment.
For a routine extraction route, examples might include:
- Pull the invoice date and total from this document.
- Return the names and phone numbers in this email.
- Convert these supplied fields into the required JSON structure.
Make the examples diverse in phrasing and length. Do not simply write the same instruction with different punctuation. Add negative examples too: prompts that look related but should go to another route. For instance, extraction of a single stated amount may be routine, while reconciling conflicting amounts across multiple records may require stronger reasoning.
Do not rely on one route centroid without testing it. A centroid is an average vector representing the route. Averaging can blur subtypes and edge cases. Compare approaches such as maximum similarity to individual examples, multiple example clusters or a trained classifier. The right choice depends on the size and shape of your data.
Tune similarity thresholds on the development set. A universal score such as 0.70 is not a safe default because similarity scores depend on the embedding model, the examples and the route. Set thresholds per route if the evidence supports that. Test the number of false lightweight routes, not just overall classification accuracy. Misrouting a difficult prompt down to a weak model is usually more costly than sending an easy request to the stronger model.
Add a margin rule for ambiguity. If two routes score closely, or several routes pass their similarity floors, treat the request as ambiguous. Send it to a safer route or ask a clarifying question. A multi-intent prompt should not be forced into whichever category happens to score slightly higher.
Before release, test how changes to the reference examples affect route selection. If you change the embedding model, rebuild all reference embeddings and repeat threshold tuning. Scores from one embedding space should not be carried over unchanged to another.
Step 5: Connect the router to model endpoints
Put the routing decision in a shared service or gateway where you can apply consistent policy, logging and model configuration. Keeping the logic in one gateway can help multiple applications use the same routes, but it also creates a critical dependency. Design for monitoring, timeouts and safe failure.
A typical request flow is:
- Authenticate the request and identify the tenant, user and application.
- Apply access, privacy and data-location rules.
- Assemble the prompt and relevant conversation or retrieval context.
- Classify the task and estimate route confidence or difficulty.
- Select a model, prompt template and permitted tools for the route.
- Call the model with timeouts and retry limits.
- Validate the output and escalate or abstain when needed.
- Record route, model, token usage, latency and validation outcome.
Keep the response contract stable for the calling application. An OpenAI-compatible interface can reduce integration effort where your clients already use that contract, but compatibility does not mean every provider behaves identically. Test streaming, tool calls, structured outputs, error handling and context limits for each model you configure.
If the router itself fails, define the fallback explicitly. Automatically sending every request to the most expensive model may preserve availability but can create a cost spike. Automatically sending everything to the smallest model may silently reduce quality. You may instead fail closed for sensitive workflows, return a retryable error, or use a pre-approved fallback model with a budget limit.
Keep model selection, thresholds and prompt versions in configuration rather than scattering them across application code. Version each change. That makes it possible to compare performance and roll back a bad threshold or model update without a full software release.
Step 6: Evaluate quality, cost and latency together
A router is successful only if it improves the economics without breaking the product. Measure three outcomes together:
- Quality: task-specific correctness, completeness, format compliance, groundedness or human acceptance.
- Cost: input and output tokens by route, model charges and router infrastructure cost.
- Latency: router time, model time, retries, validation time and total response time.
Use the same evaluation prompts to compare at least three baselines: your existing system, all traffic on the stronger model, and the proposed routed design. The existing system is the commercial baseline. The all-stronger-model baseline helps measure quality headroom, but it may not represent the system you actually operate.
The RouteLLM paper reports reductions of up to 85% in inference cost while retaining 95% of a stronger model’s response quality on selected benchmarks and model settings. The paper also reports that its router sent a minority of benchmark requests to the stronger model. Read those numbers as research findings under defined test conditions, not as a promised saving for a business application.
The Red Hat overview of the vLLM Semantic Router Athena release describes reported classification and serving benchmarks for that system. Router latency varies by implementation and infrastructure. A remote LLM used as a router may add an extra network call and model cost; a local encoder or embedding search may avoid that call but still needs operational capacity and monitoring.
Calculate the expected monthly cost from your own token distribution. For each route, multiply the number of requests by average input and output tokens, then apply the current provider rate. Add embedding charges if you use a hosted embedding service, and include compute, observability, retries and validation. If a cascade calls a second model on failed attempts, include those calls as well.
Use a simple comparison:
| Measure | Existing system | Routed design |
|---|---|---|
| Requests per month by task | From production records | Same traffic mix or a documented forecast |
| Input and output tokens | Measure separately | Measure separately by route |
| Model charges | Current provider rates | Current provider rates for each route |
| Extra costs | Retries, tools, hosting | Router, embeddings, validation and escalation |
| Quality | Existing acceptance and failure rates | Same checks, segmented by task and impact |
| Latency | Total and percentile measures | Include routing and any second call |
A rough scenario can use proportions without claiming a guaranteed saving. Suppose a fraction of requests moves to a lower-priced model. Calculate that fraction with the actual input and output token rates, then add the cost of requests that stay on the stronger model and the router overhead. A high percentage of cheap-model requests does not automatically mean a high saving if those requests produce long outputs, use costly tools or require frequent escalation.
Set quality guardrails before you run a live test. For example, define which failures block release, which require investigation and which are acceptable for a low-risk workflow. Avoid one global failure threshold across unrelated tasks. A small increase in a harmless formatting error is not equivalent to an increase in incorrect financial extraction.
Step 7: Launch gradually and monitor for drift
Start with shadow mode. The router makes and records decisions, but the existing model still serves the user. Compare the proposed route with the known response and review disagreements. This exposes classification problems without changing the customer experience.
Next, run a limited live rollout for low-risk traffic. Keep a control group on the existing configuration. Compare quality, cost and latency across the two groups, and break results down by route, model, tenant and task. Make sure the sample is large and varied enough to support the decision. A short test on a quiet day can miss unusual but important traffic.
Monitor at least:
- Route distribution and changes in the percentage of requests per route.
- Similarity scores or classifier confidence, including low-confidence cases.
- Escalation, retry, refusal and validation-failure rates.
- User corrections, negative feedback and support contacts where available.
- Token use and cost per successful task, not only cost per call.
- Router and model latency, including high-percentile latency.
- Provider errors and fallback volume.
Use a sampled quality review to catch issues automated checks miss. An LLM-as-judge process can help prioritise review, but it is not a definitive answer key. A judge model can share weaknesses with the model being assessed, and its scoring can vary. Keep human review for important workflows and calibrate automated scores against reviewed examples.
Traffic changes over time. New product features, customer vocabulary, policies and prompt templates can change the requests the router sees. Re-sample real traffic on a regular schedule and when the product changes materially. Review new clusters, out-of-distribution prompts and routes with rising escalation. Treat a proposed quarterly refresh as a cadence to consider, not a substitute for monitoring triggers.
Step 8: Make cost and quality visible to the business
A dashboard should let an operator answer a few direct questions: Which tasks are using the stronger model? Which routes are failing validation? Is cost per successful task falling? Has response quality changed? Are there groups of users experiencing worse latency or more errors?
Report both total spend and unit economics. Total spend can rise because usage grows even while routing lowers cost per request. Cost per successful task captures more of the real trade-off because repeated attempts, human correction and escalations all consume resources.
Keep a route change log with the reason for each change, the evaluation set used, the expected effect and the rollback plan. When a model or embedding service changes, repeat the relevant tests. Providers can change capabilities and service behaviour over time, and models can be retired. Do not let a route depend on an unpinned alias without an owner and update process.
For Australian organisations, include data handling and accountability in the release review. Confirm what prompt content is sent to each provider, where it is processed, how logs are retained and who can access them. If your use case is regulated or sensitive, review the route design against your internal policies and relevant obligations before production. A cheaper endpoint is not an acceptable route if it violates a data boundary.
Common mistakes to avoid
Routing by topic alone
A topic label is not a capability assessment. The same subject can contain routine questions and difficult decisions. Add difficulty signals, validation or explicit exception routes where complexity varies inside a category.
Treating similarity as confidence in correctness
A close match means the prompt resembles examples in vector space. It does not establish that a model will answer correctly. Use route confidence to decide where to send the request, then evaluate the answer separately.
Using one threshold for every category
Different routes have different example diversity and consequences. Fit thresholds using held-out examples, inspect false matches and bias toward safer escalation where the cost of a weak answer is high.
Counting only model token charges
Router compute, embeddings, retries, second calls, tool use, monitoring and human correction all affect total cost. Measure cost per successful task rather than reporting only the reduction in a model’s token bill.
Letting routing become invisible
If a team cannot tell which model answered a request or why, it cannot investigate a quality issue. Log the decision and its inputs at an appropriate level, while protecting sensitive content and access to logs.
Assuming the router stays accurate
Reference examples can become stale as users and workflows change. Review new traffic and failure patterns. Re-evaluate after changes to prompts, embedding models, classifiers or model endpoints.
A short implementation checklist
Before you release semantic routing, confirm that you can answer yes to these questions:
- Have we profiled real traffic and separated tasks by both difficulty and impact?
- Do we have a labelled, held-out evaluation set with important edge cases?
- Are compliance and data-location rules applied before semantic decisions?
- Have we tested thresholds by route and defined what happens when routes conflict?
- Can the system validate outputs and escalate, abstain or ask for clarification?
- Have we included current model prices, router costs and retries in the cost estimate?
- Can we monitor quality, cost and latency by route after launch?
- Is there a tested rollback or safe fallback if the router or provider fails?
Where PADISO fits
Semantic routing sits across AI design, application architecture and production operations. PADISO helps teams assess use cases, build routing and evaluation into their AI systems, and establish the controls needed to operate them. Our AI strategy and solutioning service can help define the business case, while platform engineering can support the gateway and operational design.
Wrap-up: optimise the decision, not just the model bill
The most reliable way to build a semantic router is to start with traffic evidence, make route decisions explicit and test them against a defined quality bar. Use rules for hard constraints, semantic matching for clear task categories, difficulty signals for uncertain cases and validation where outputs can be checked. Roll out gradually, measure the complete cost per successful task and keep a safe path for requests the router cannot classify confidently.
Your next step is to take a representative sample of requests and map each task to a model, a quality check and a fallback. If you want help turning that map into an implementation plan, start with PADISO’s AI readiness test.