# 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](#route-to-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](#pin-a-session-to-its-route).

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](https://docs.api7.ai/ai-gateway/routing/semantic-routing-typesafe-jev.md).

## How Semantic Routing Works[​](#how-semantic-routing-works "Direct link to 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.

In AISIX Enterprise and AISIX Cloud, a semantic router has no price of its own. The embedding call is billed at the embedding model's price as an [internal call](https://docs.api7.ai/ai-gateway/cloud/model-pricing.md#bill-the-gateways-internal-model-calls). The routed request is billed at the selected target. See [Bill a Semantic Router's Requests](https://docs.api7.ai/ai-gateway/cloud/model-pricing.md#bill-a-semantic-routers-requests). The semantic-router form therefore has no sale-price section.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before starting, prepare the following:

* A [provider key](https://docs.api7.ai/ai-gateway/models/provider-keys.md) for an OpenAI-compatible `/v1/embeddings` endpoint that returns float vectors.
* A default target and at least one route target. Each is a [direct model](https://docs.api7.ai/ai-gateway/models/model-aliases.md#create-a-direct-model) or a [model group](#route-to-a-model-group).
* Targets that serve Chat Completions. AISIX Enterprise and AISIX Cloud reject models on non-chat providers, including `jina`, `runwayml`, and `typesafe`, and prevent referenced models from moving to those provider keys.
* A [caller API key](https://docs.api7.ai/ai-gateway/traffic-controls/caller-api-keys.md) that can call the semantic router alias.
* For AISIX Enterprise or AISIX Cloud, an environment with an attached gateway. Dashboard users need permission to manage models and caller API keys. AISIX Cloud Admin API users need a write-scoped admin token.
* For the open-source AISIX gateway, access to the declarative resources file and the gateway process.

## Configure a Semantic Router[​](#configure-a-semantic-router "Direct link to 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 Cloud
* AISIX OSS

Create the embedding model and router in the environment serving the application.

* Dashboard
* Admin API

First create the embedding model in the environment:

1. Open **Models**, select **Create model**, and choose **Embedding model**.
2. Set **Display name** to `embedding-prod`, **Upstream model id** to `text-embedding-3-small`, and select the embedding provider key.
3. Set **Dimensions** to `1536`. Keep **Upstream already returns L2-normalized vectors** selected for this model.

![Embedding model configuration with 1536 dimensions and upstream-normalized vectors](https://static.api7.ai/uploads/2026/11/18/UZkD19JD_semantic-embedding.webp)

4. Select **Create embedding model**.

Create the router:

1. Select **Create model** again and choose **Semantic router**.
2. Set **Display name** to `topic-router`, keep **Embedding similarity** as the **Decision backend**, and select `embedding-prod` under **Embedding model**.

![Embedding-based semantic router with its embedding model selected](https://static.api7.ai/uploads/2026/11/18/sNmSWVya_semantic-router-top.webp)

3. Under **Routes**, add `legal` and select the legal target. Enter the two **Example prompts** on separate lines and set its optional threshold to `0.8`:

```
Analyze this contract for legal risk

Review this NDA for liability exposure
```

![Legal route with its target, two example prompts, and a route-specific threshold](https://static.api7.ai/uploads/2026/11/18/ejNxM26G_semantic-route-legal.webp)

4. Add `translation`, select its target, and enter `Translate this paragraph to French` as its example prompt.

![Translation route with an example prompt](https://static.api7.ai/uploads/2026/11/18/bMqfyeG1_semantic-route-translation.webp)

5. Select the prepared default model and set **Router threshold** to `0.75`. Keep **On embedding failure** set to fall back to the default model for this example.

![Default model, router threshold, and embedding-failure behavior](https://static.api7.ai/uploads/2026/11/18/uVejOImc_semantic-defaults.webp)

6. Select **Create semantic router**. Check the saved backend and route count. Reopen **Edit** to inspect the individual routes and default model.

![Saved topic-router showing its backend and configured route count](https://static.api7.ai/uploads/2026/11/18/wqr3Gqxt_semantic-saved.webp)

An existing caller key with all-model access already grants the new alias. Otherwise:

1. Open **API keys** in the same environment.
2. Select **Edit** for an existing caller whose plaintext you have saved, or select **New API key** and enter a display name.
3. Keep **Selected models** and select `topic-router` under **Allowed models**, retaining any other required models.

![Caller model access with topic-router selected](https://static.api7.ai/uploads/2026/11/18/8e5iBL3y_semantic-grant.webp)

Finish the key according to the path you chose:

* For an existing key, select **Save changes**.
* For a new key, select **Create API key**, copy its plaintext from **One-time view**, then select **I've saved it**.

Embedding-model and router rows support **Edit** and **Delete**. Remove a router's reference before deleting an embedding or target model that it uses. Deleting the router itself requires confirmation.

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"

export API_KEY_ID="YOUR_CALLER_API_KEY_RESOURCE_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')
```

If the caller key uses all-model access, it already grants the new router. Otherwise, read its current allowlist, append the router ID, and write the complete list back. The saved configuration is projected to attached gateways automatically:

```
curl -sS "$AISIX_CP/environments/$ENV_ID/api_keys" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  | jq -ec --arg key_id "$API_KEY_ID" --arg id "$SEMANTIC_MODEL_ID" '

      .data[] | select(.id == $key_id)

      | {allowed_models: ((.allowed_models // []) + [$id] | unique)}' \

  | curl -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/api_keys/$API_KEY_ID" \

      -H "Authorization: Bearer $AISIX_TOKEN" \

      -H "Content-Type: application/json" \

      --data-binary @- | jq
```

The Dashboard tuning helpers call the embedding endpoint from the control plane, so that endpoint must be reachable from the control-plane services.

Add the embedding model and semantic router to the `models` collection. References in the `semantic` block use model `display_name` values:

resources.yaml (semantic routing models)

```
models:

  - id: fa0a743f-703c-4b18-8f08-9371506cad15

    display_name: embedding-prod

    provider: openai

    model_name: text-embedding-3-small

    provider_key_id: 2f87ee16-6c99-4817-96fd-ff2b8ee08eb7

    embedding:

      dimensions: 1536

      normalize: true



  - id: 79de16c6-8204-4bd0-82a7-aebc4595ea85

    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[​](#verify-route-selection "Direct link to 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. Use the `x-aisix-request-id` response header to find the request's [access-log line](https://docs.api7.ai/ai-gateway/observability/access-logs-and-request-correlation.md#read-the-semantic-routing-decision).

| Signal                 | Expected result                                                        |
| ---------------------- | ---------------------------------------------------------------------- |
| Access log             | `semantic_route="legal"`                                               |
| Debug response headers | `x-aisix-route: legal` and `x-aisix-served-by` naming the direct model |

Debug headers appear only when [`proxy.expose_debug_headers`](https://docs.api7.ai/ai-gateway/reference/configuration-files.md#expose-debug-response-headers) is enabled in the gateway startup configuration.

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](https://docs.api7.ai/ai-gateway/observability/access-logs-and-request-correlation.md#read-the-semantic-routing-decision).

## Tune Matching Behavior[​](#tune-matching-behavior "Direct link to 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](#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.

### Test and Suggest Thresholds in the Dashboard[​](#test-and-suggest-thresholds-in-the-dashboard "Direct link to Test and Suggest Thresholds in the Dashboard")

Select **Edit** on the router. Save any changed route examples before running **Test routing** or **Auto-detect thresholds**, because those helpers evaluate the saved configuration. The embedding endpoint must be reachable from the control-plane services.

For a routing test, expand **Test routing**, enter a representative prompt, and run the test. Inspect the selected route and each route's score against its threshold.

![Routing test result selecting the legal route and showing similarity scores](https://static.api7.ai/uploads/2026/11/18/jtWgqEaV_semantic-test-routing.webp)

Select **Auto-detect thresholds** to fill the route threshold fields with suggestions. Review the suggested values and warnings, then select **Save changes** to apply them.

![Suggested legal-route threshold with its positive and negative example scores](https://static.api7.ai/uploads/2026/11/18/eAcMfUJA_semantic-threshold-suggestion.webp)

### What the Router Classifies[​](#what-the-router-classifies "Direct link to What the Router Classifies")

AISIX classifies the newest non-empty user text and ignores tool-only turns. This keeps an agent loop focused on the user's latest request instead of a tool result. See [Classified Input](https://docs.api7.ai/ai-gateway/routing/semantic-routing-behavior.md#what-the-router-classifies) for the exact Chat Completions, Messages, Responses, and coding-agent rules.

## Handle Embedding Failures[​](#handle-embedding-failures "Direct link to 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.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

Edit the router and use **On embedding failure** to select the fallback behavior. To route failures to a prepared fallback model, choose the specific-model option, select that target, and save the changes.

![Embedding-failure behavior configured to use a specific fallback model](https://static.api7.ai/uploads/2026/11/18/2eBPyADl_semantic-failure-target.webp)

The managed 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`.

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
```

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](https://docs.api7.ai/ai-gateway/reference/headers-and-error-codes.md#semantic-routing-failures) for the reasons.

## Route to a Model Group[​](#route-to-a-model-group "Direct link to Route to a Model Group")

A route target, the default target, and the failure target can each be a [model group](https://docs.api7.ai/ai-gateway/routing/routing-and-failover.md) (`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.

* AISIX Enterprise or Cloud
* AISIX OSS

The group must contain at least one member whose provider serves Chat Completions. AISIX rejects ensemble models, embedding models, and other semantic routers with `400`. This validation runs when the router is saved; later group changes are not rechecked.

Gateway compatibility

A gateway before 1.10.0 cannot serve a semantic route whose target is a group. AISIX Enterprise and AISIX Cloud reject the router with `422` `DP_INCOMPATIBLE` while an older gateway is registered in the environment.

* Dashboard
* Admin API

Edit the router and select the prepared group in the route, default, or failure target selector. Groups are marked **model group**. Select **Save changes** to apply the choice.

![A semantic route target selector with chat-prod marked as a model group](https://static.api7.ai/uploads/2026/11/18/0DIT0xPP_semantic-group-target.webp)

Reference the group by model ID in the same fields used for direct models:

| Use                      | Field                                  |
| ------------------------ | -------------------------------------- |
| Route target             | `target_model_id`                      |
| Default target           | `default_model_id`                     |
| Embedding-failure target | `on_embedding_failure.target_model_id` |

Update the existing router with the appropriate field, using the request shape shown in [Configure a Semantic Router](#configure-a-semantic-router).

In the complete resources file, name the group in `target`, `default`, or `on_embedding_failure.target`, the same way as a direct model. Preserve the router's other fields, then validate and reload the file.

After the router selects a group, the group applies its own strategy, failover, cooldown, and target limits. If no group member is available, the router uses its default target.

See [Semantic Routing Decisions and Session Affinity](https://docs.api7.ai/ai-gateway/routing/semantic-routing-behavior.md#model-group-targets) for rate-limit, cost, metrics, fallback, and two-layer session-affinity behavior.

## Pin a Session to Its Route[​](#pin-a-session-to-its-route "Direct link to Pin a Session to Its Route")

By default, a semantic router classifies each request independently, so one conversation can move between routes. Session affinity keeps later requests on the first matched route and skips further classification. It works with both the embedding backend and the [TypeSafe jev](https://docs.api7.ai/ai-gateway/routing/semantic-routing-typesafe-jev.md) backend.

### Enable Session Affinity[​](#enable-session-affinity "Direct link to 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.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

Edit the semantic router, select **Session affinity**, and set **Pin TTL (seconds)**. This example uses the default `3600` seconds. Select **Save changes**.

![Session affinity enabled with a 3600-second pin lifetime](https://static.api7.ai/uploads/2026/11/18/S4xPW1Rx_semantic-session-affinity.webp)

Update the router with the following block inside its `semantic` configuration, preserving its routes and other settings:

```
{

  "semantic": {

    "session_affinity": {

      "enabled": true,

      "ttl_seconds": 3600

    }

  }

}
```

Add the block to the router's `semantic` configuration in the resources file:

```
semantic:

  session_affinity:

    enabled: true

    ttl_seconds: 3600
```

### How Pins Behave[​](#how-pins-behave "Direct link to How Pins Behave")

The first request that matches a route creates the pin. Later requests with the same router, caller key, and session ID use that route without another classification call, and each request refreshes the TTL. Requests sent to the default or failure target do not create a pin.

Claude Code and Codex already send a recognized session ID. Other clients can send `x-aisix-session-id` with a stable conversation ID. AISIX Enterprise and AISIX Cloud share pins across gateways in an environment; AISIX OSS keeps them in the gateway process.

See [Semantic Routing Decisions and Session Affinity](https://docs.api7.ai/ai-gateway/routing/semantic-routing-behavior.md#how-pins-behave) for pin invalidation, side-request handling, session-ID precedence, capacity behavior, and access-log fields.

## Next Steps[​](#next-steps "Direct link to Next Steps")

* Use [Semantic Routing with TypeSafe Jev](https://docs.api7.ai/ai-gateway/routing/semantic-routing-typesafe-jev.md) to choose routes by description rather than example similarity.
* Build route targets with [Multi-Target Routing and Failover](https://docs.api7.ai/ai-gateway/routing/routing-and-failover.md).
* Use [Ensemble Models](https://docs.api7.ai/ai-gateway/routing/ensemble-models.md) when one request should call several panel models and synthesize their answers.
* Add [Guardrails](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/keyword.md) when requests need policy checks before dispatch.
