Semantic Routing
A semantic router gives applications one stable model alias while AISIX selects a target based on the meaning of each request. AISIX embeds the request's latest user text, compares it with examples for each route, and dispatches to the best match. When no route reaches its threshold, AISIX uses a default target. Each target is a direct model or a model group.
Use semantic routing when requests should reach different models by topic without requiring the application to choose a model. For example, one alias can send legal questions to a reasoning model, translation requests to a multilingual model, and all other requests to a general-purpose model.
Semantic routers serve these endpoints:
/v1/chat/completions/v1/messages/v1/messages/count_tokens/v1/responses
So a coding agent such as Claude Code or Codex can call a semantic router directly. To keep an agent session on the route its first request matched, turn on session affinity.
This page describes the embedding-based decision backend. A semantic router can instead let TypeSafe's hosted jev decision model choose the route from each route's description, with no examples or thresholds. See Semantic Routing with TypeSafe Jev.
How Semantic Routing Works
For each request, AISIX uses the configured embedding model to compare the latest user text with route examples, then dispatches the request to one target.
AISIX embeds route examples on the first request that needs them and caches their vectors in the gateway process. It recomputes the vectors when the examples, embedding model, or embedding dimensions change. Each request therefore requires one embedding call for its latest user text, followed by local similarity calculations.
Prerequisites
Before starting, prepare the following:
- A provider key for an OpenAI-compatible
/v1/embeddingsendpoint that returns float vectors. - A default target and at least one route target. Each is a direct model or a model group. The router sends them chat requests, so a direct model's provider must serve chat completions. AISIX Enterprise and AISIX Cloud reject a model whose provider does not, such as a model on a
jina,runwayml, ortypesafeprovider key, as a route, default, or failure target, and refuse to move a referenced model onto such a key. - A caller API key that can call the semantic router alias.
- For AISIX Enterprise or AISIX Cloud, an environment with an attached gateway and permission to manage models and caller API keys.
- For the open-source AISIX gateway, access to the declarative resources file and the gateway process.
Configure a Semantic Router
Create the embedding model, default model, and route targets before creating the semantic router. The control plane references these resources by model ID. The open-source AISIX gateway references them by display_name in the declarative resources file.
The embedding model's dimensions must match the number of values returned by its upstream endpoint. Set normalize to false only when AISIX must normalize the vectors before comparing them.
Each route requires a name, a target, and at least one example. The description is optional. A route-level threshold overrides the router-level threshold for that route.
AISIX Enterprise or AISIX Cloud
Export the control-plane connection details and the provider key used by the embedding model:
# AISIX_CP is the Admin API base URL; include /api and omit a trailing slash.
# The local AISIX Enterprise quickstart uses http://localhost:8080/api.
export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"
export AISIX_TOKEN="YOUR_ADMIN_TOKEN"
export ENV_ID="YOUR_ENVIRONMENT_ID"
export PROVIDER_KEY_ID="YOUR_EMBEDDING_PROVIDER_KEY_ID"
Create the embedding model and capture its ID:
EMBEDDING_MODEL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/models" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"kind": "embedding",
"display_name": "embedding-prod",
"model_name": "text-embedding-3-small",
"provider_key_id": "'"$PROVIDER_KEY_ID"'",
"embedding": {
"dimensions": 1536,
"normalize": true
}
}' | jq -r '.model.id')
Export the IDs of the target models. Each can be a direct model or a model group:
export DEFAULT_MODEL_ID="YOUR_DEFAULT_MODEL_ID"
export LEGAL_MODEL_ID="YOUR_LEGAL_MODEL_ID"
export TRANSLATION_MODEL_ID="YOUR_TRANSLATION_MODEL_ID"
Create the semantic router. Its default threshold applies to every route that does not define its own:
SEMANTIC_MODEL_ID=$(curl -sS -X POST "$AISIX_CP/environments/$ENV_ID/models" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"kind": "semantic",
"display_name": "topic-router",
"semantic": {
"embedding_model_id": "'"$EMBEDDING_MODEL_ID"'",
"default_model_id": "'"$DEFAULT_MODEL_ID"'",
"threshold": 0.75,
"routes": [
{
"name": "legal",
"target_model_id": "'"$LEGAL_MODEL_ID"'",
"description": "Contract and legal-risk analysis",
"examples": [
"Analyze this contract for legal risk",
"Review this NDA for liability exposure"
],
"threshold": 0.8
},
{
"name": "translation",
"target_model_id": "'"$TRANSLATION_MODEL_ID"'",
"examples": [
"Translate this paragraph to French"
]
}
]
}
}' | jq -r '.model.id')
Add SEMANTIC_MODEL_ID to the caller API key's allowed_models list. The saved configuration is projected to attached gateways automatically.
You can also create and edit the embedding model and semantic router on the dashboard Models page. The semantic router form provides two threshold-tuning helpers:
- Test routing shows the route selected for a prompt, each route's similarity score, and whether the score reached its threshold.
- Auto-detect thresholds recommends a starting threshold for each route based on the similarity within and between the configured example sets.
Both helpers call the embedding endpoint from the control plane, so that endpoint must be reachable from the control-plane services.
AISIX OSS
Add the embedding model and semantic router to the models collection. References in the semantic block use model display_name values:
models:
- display_name: embedding-prod
provider: openai
model_name: text-embedding-3-small
provider_key: embeddings-provider
embedding:
dimensions: 1536
normalize: true
- display_name: topic-router
semantic:
embedding_model: embedding-prod
default: general-chat
match:
distance_metric: cosine
aggregation: max
threshold: 0.75
routes:
- name: legal
target: legal-chat
description: Contract and legal-risk analysis
examples:
- Analyze this contract for legal risk
- Review this NDA for liability exposure
threshold: 0.8
- name: translation
target: translation-chat
examples:
- Translate this paragraph to French
The complete resources file must also contain the referenced provider key and the general-chat, legal-chat, and translation-chat direct models. Add topic-router to the caller key's allowed_models, then validate and reload the file.
Verify Route Selection
Export the gateway URL and caller API key for the deployment you configured:
# Use the gateway origin without a trailing slash or endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
Send a request that should match the legal route:
curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "topic-router",
"messages": [
{"role": "user", "content": "Review this contract for liability risk."}
]
}'
The response body retains topic-router as the caller-facing model name. To see which route matched, find the request's access-log line by its x-aisix-request-id response header: a matched request carries semantic_route="legal". On a gateway whose startup configuration sets proxy.expose_debug_headers to true, the response also includes x-aisix-route: legal and x-aisix-served-by with the direct model that served the request.
Send a prompt unrelated to every route to confirm that AISIX uses the default model. Its access-log line carries semantic_fallback instead of semantic_route, and the response omits x-aisix-route.
The request's access-log line records how the router decided: the matched route, its similarity score, and why the default model served the request when no route did. See Read the Semantic Routing Decision.
Tune Matching Behavior
AISIX applies these rules when selecting a route:
- Only one user turn is classified, chosen as described in What the Router Classifies.
- Each route's score is the highest cosine similarity between the request and that route's examples.
- A route matches when its score is at least its route-level threshold, or the router-level threshold when the route does not override it.
- When several routes match, the route with the highest score wins. When none match, AISIX uses the default model.
What the Router Classifies
The same rule applies on every endpoint a semantic router serves. AISIX walks the request's user turns from the newest to the oldest and classifies the first one that carries text the user wrote:
- Only the turn's text parts are read. When a turn has several, AISIX joins them with a space.
- A turn that holds only tool results, images, or reminders has no such text, so AISIX moves on to the turn before it.
- The system prompt, the Responses API
instructions, and assistant turns are never classified.
Before classification, AISIX removes every complete <system-reminder>…</system-reminder> block and keeps the text around it. For a Codex client, identified by its User-Agent as described in Where the Session ID Comes From, AISIX also removes these separate tag-delimited blocks:
<environment_context>...</environment_context>
<recommended_plugins>...</recommended_plugins>
<user_instructions>...</user_instructions>
<environments_instructions>...</environments_instructions>
AISIX also removes one AGENTS.md instructions span. The span starts at the heading and ends at the closing instructions tag:
# AGENTS.md instructions for ...
<instructions>
...
</instructions>
The delimiters are matched case-insensitively. An opening delimiter without its closing delimiter remains part of the text. For clients other than Codex, only complete <system-reminder> blocks are removed from the text before classification.
A request with no such text goes to the default target without an embedding call, unless its session is pinned to a route.
So while an agent such as Claude Code or Codex runs a tool-call loop, each request is still classified on the user's most recent question rather than on a tool result. Per protocol, a user turn is a user message on /v1/chat/completions, a user message with string content or text blocks on /v1/messages and /v1/messages/count_tokens, and a string input or an input_text part of a user message item on /v1/responses.
On /v1/chat/completions, a request whose last user message holds only an image is classified on the newest earlier user message that has text. Gateways before 1.10.0 sent such a request to the default target.
Cross-lingual matching depends on the embedding model. Tune thresholds with representative prompts and examples from the intended workload rather than assuming one cutoff works for every embedding model. Routing decisions can also be influenced by adversarial prompts, so apply input guardrails before dispatch when the destination has security or compliance consequences. Attach those guardrails to the semantic routing model itself: a guardrail attached to a destination model does not run for a request the caller addressed to the router. See Guardrail Scope Follows the Addressed Model.
Handle Embedding Failures
Use embedding_timeout_ms to bound the embedding call and on_embedding_failure to choose what happens after an embedding error or timeout. The default behavior is to use the router's default model.
In AISIX Enterprise and AISIX Cloud, the fallback policy is an object. To reject the request with 503:
{
"semantic": {
"embedding_timeout_ms": 500,
"on_embedding_failure": {
"mode": "fail"
}
}
}
Set mode to default to use the default model. To use another direct model or a model group, set mode to target and provide its target_model_id.
With fail, the 503 carries error.code semantic_routing_failed and a message naming the router and the reason, such as embedding_timeout. The access-log line records semantic_fallback="decision_failed" and error_class="semantic_decision_failed". See Semantic Routing Failures for the reasons.
In the open-source resources file, use default, fail, or an object that names a direct model or a model group:
semantic:
embedding_timeout_ms: 500
on_embedding_failure:
target: safe-chat
Route to a Model Group
A route target, the default target, and the failure target can each be a model group (kind: routing) instead of a direct model. Use one when a route should spread its traffic over several deployments, or fail over between them, rather than reach a single model.
In AISIX Enterprise and AISIX Cloud, set the group's model ID wherever a direct model's ID goes: a route's target_model_id, default_model_id, or on_embedding_failure.target_model_id. In the dashboard, the target lists mark each group with model group. An ensemble model, another semantic router, or an embedding model is rejected as a target with 400. A group is also rejected unless at least one of its members uses a provider that serves chat completions. That check runs when the router is saved: later changes to the group or its members are not checked again.
In the open-source resources file, name the group in target, default, or on_embedding_failure.target, the same way as a direct model.
Once the router picks a group, the group dispatches the request the way it does when a caller addresses it directly: its strategy picks the member, and its failover, cooldown, and the target models' own limits apply. When the group has no member to dispatch to, or its own client-IP allowlist excludes the caller, the router's default target serves the request, and the access log records semantic_fallback="target_unavailable".
Each mechanism takes effect at one of the three layers:
| Mechanism | Applies to |
|---|---|
| Guardrails, model access control, and the response cache | The semantic router the caller addressed. |
| Rate limits | The router's own limit counts once per request. The group's own limit counts once per request in which that group is chosen. The limit of the target model the group dispatches to counts once per upstream attempt sent to it. See API Key and Model Rate Limits. |
| Cost and usage | The member that served the request. |
| Metrics | The model label is the semantic router; upstream_model is the member. |
Session affinity pins a session to a route, and so to the group, never to one of its members. When a session should also stay on one member, give the group the consistent_hash strategy and hash on a session header, as in Pin Sessions with Pool Failover. For example, a group serving Claude Code and other clients could read its hash key from these sources, the first non-empty one winning:
"routing": {
"strategy": "consistent_hash",
"hash_on": [
{"type": "header", "name": "x-claude-code-session-id"},
{"type": "header", "name": "x-aisix-session-id"},
{"type": "api_key"}
],
"targets": [...]
}
A gateway before 1.10.0 loads a router with a group target but fails every request routed to the group. AISIX Enterprise and AISIX Cloud therefore refuse to save such a router with 422 DP_INCOMPATIBLE while a gateway older than 1.10.0 is registered in the environment.
Pin a Session to Its Route
By default, a semantic router classifies every request on its own, so one agent conversation can move between models from turn to turn. Session affinity keeps a session on the route its first matched request took: later requests of the session skip classification and go straight to that route's target. It works with both the embedding backend and the TypeSafe jev backend.
Enable Session Affinity
Add a session_affinity block to the router's semantic configuration:
| Field | Default | Description |
|---|---|---|
enabled | false | Whether sessions are pinned. While it is false, existing pins are not used. |
ttl_seconds | 3600 | How long a pin lasts after the last request that used it, from 60 to 604800 seconds. |
Without the block, every request is classified.
Session affinity requires gateway 1.10.0 or later. An older gateway ignores the block and classifies every request. AISIX Enterprise and AISIX Cloud still save the router while such a gateway is registered, and the save warns that the gateway ignores the field.
In AISIX Enterprise and AISIX Cloud:
{
"semantic": {
"session_affinity": {
"enabled": true,
"ttl_seconds": 3600
}
}
}
In the dashboard, set Session affinity and Pin TTL (seconds) on the semantic router form.
In the open-source resources file:
semantic:
session_affinity:
enabled: true
ttl_seconds: 3600
How Pins Behave
- The first request of a session that matches a route pins the session to that route as soon as the route is chosen. A later request of the session goes to the pinned route without being classified, and each such request extends the pin by another
ttl_seconds. - A pin belongs to one semantic router, one caller API key, and one session ID. Two API keys sending the same session ID, or one session calling two routers, never share a pin.
- Only a matched route creates a pin. A request that goes to the default target or a failure target pins nothing, and the session's next request is classified again.
- When the pinned route's target is temporarily unavailable to the request, the default target serves it and the pin is kept.
- When the pinned target is no longer the target of any of the router's routes, for example after the router was edited, the pin is dropped and the request is classified again.
/v1/messages/count_tokensuses and extends an existing pin, but never creates one.- A side request that a coding agent sends outside the session's main loop, such as one that generates the session title, never creates a pin either. When the session already has a pin, the side request follows and extends it; otherwise it is classified as usual. AISIX recognizes a side request by the
x-claude-code-request-class: auxiliaryheader, or by text that matches the known title-generation, progress-summary, and input-suggestion prompts of Claude Code and Codex.
Recognizing side requests by their prompts works only for prompts AISIX knows, so a client release that changes them can make a side request pin its session. To keep such requests out of classification entirely, point the client's background or small model at a direct model rather than at the semantic router. For Claude Code, that is the small, fast model set by ANTHROPIC_DEFAULT_HAIKU_MODEL; see Configure Claude Code.
In AISIX Enterprise and AISIX Cloud, every gateway of an environment shares the environment's pins through the control plane, so a session stays on its route whichever gateway receives the request. An environment holds about 1,000,000 pins; beyond that, a new pin is kept only by the gateway that created it. When a gateway cannot reach the shared pins, it keeps pins of its own and the request is unaffected; until it reaches them again, different gateways can pin a session to different routes. An open-source gateway keeps its pins in its own process.
Where the Session ID Comes From
AISIX reads the session ID from the first of these sources that carries a valid value. A value over 256 bytes is ignored.
- The
x-aisix-session-idheader. - Any
x-<vendor>-session-idheader, such as thex-claude-code-session-idheader that Claude Code sends. When several are present, the header whose name sorts first wins. - For a Codex client, one whose
User-Agentstarts withcodexfollowed by-,_,/, or a space: thesession-id,session_id,thread-id, orconversation_idheader. - The
x-session-idheader. - The request body's
metadata.user_id: thesession_idof an object, thesession_idof a JSON object written as a string, or the text after the last_session_in a string. - The request body's
metadata.session_id. - The
session.identry of the W3Cbaggageheader.
The headers in sources 2, 3, and 4 count only when their value is at least 8 letters, digits, _, or -. A request without a session ID is classified as usual and pins nothing.
Claude Code and Codex already send a session ID from this list, so their sessions are pinned with no client configuration. For another client, send x-aisix-session-id with an ID that stays the same for the whole conversation:
curl -sS -X POST "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "x-aisix-session-id: conversation-1a2b3c" \
-H "Content-Type: application/json" \
-d '{
"model": "topic-router",
"messages": [
{"role": "user", "content": "Review this contract for liability risk."}
]
}'
Observe Pinned Requests
A request that went to its pinned route carries semantic_pinned=true and the route in semantic_route on its access-log line. It has no semantic_score, because nothing was classified. When the pinned target was unavailable, the line carries semantic_pinned=true and semantic_fallback="target_unavailable" and no semantic_route.
Next Steps
Use Semantic Routing with TypeSafe Jev to choose routes by description instead of by example similarity. Use Multi-Target Routing and Failover to build the model groups a route can target. Continue with Ensemble Models when one request should call several panel models and synthesize their answers. Use Guardrails when requests need policy checks before model dispatch.