Skip to main content
Version: Dev

Resources File Reference

The open-source AISIX gateway can load provider credentials, models, caller credentials, and runtime policies from a declarative resources.yaml file. A resources file is a set of etcd documents written down: each entry is a resource's ID plus the document etcd would store for that resource. The gateway reads the file into the rows etcd would return and loads them with the same loader it uses for etcd, so a document loads from a file exactly when it would load from etcd.

Set resources_file in the startup configuration to select the file. To create and load a working configuration, start with the AISIX OSS getting-started guide. Use the CLI Reference to validate changes and Configuration Status to inspect the active or rejected configuration.

File Format​

AISIX loads exactly one YAML document from one resources file. The filename is not fixed: resources.yaml is the convention used in these docs, but resources_file can point to any readable file path.

The setting accepts one path only. AISIX does not load a directory, resolve include or import directives, or combine multiple resource files. If you maintain the configuration as separate source fragments, assemble them into one YAML document before validating and loading it.

Apply Resource Examples Safely​

Preserve the complete active snapshot

AISIX does not merge a resources file with the previously loaded configuration. Each successful load replaces the active resource snapshot. Start with the complete file your gateway currently uses when adding or changing resources; entries and collections omitted from the assembled file disappear from the active configuration.

Code-block titles distinguish complete documents from partial blocks:

  • A block titled resources.yaml is a self-contained document with _format_version. Read the nearby prose to determine whether it is a new-gateway configuration or a reference example.
  • A title such as resources.yaml (OIDC provider) identifies a partial block without _format_version. The short parenthetical description names the block's contents; the surrounding prose states whether to add, replace, update, or only inspect it.

When applying a partial block, start with the complete file your gateway currently uses. Update or create each affected collection once, preserve unrelated entries and collections, and do not create a second copy of an existing top-level collection key. An entry that a partial block shows with an id already in your file replaces that entry; keep the id of an entry you edit.

The IDs in these examples are sample values. A partial block that references an entry from another example uses that example's ID, so replace both together when you choose your own.

After assembling any partial blocks, validate the complete file rather than a partial block alone.

The document's top level is a mapping with a mandatory _format_version and the resource collections:

resources.yaml
_format_version: "2"

provider_keys:
- id: 0b6f3c1e-2f0a-4c5e-9d55-7d1a8b0c2e11
display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}

models:
- id: 6efd592d-a73b-473d-8e2c-e9e103692f92
display_name: gpt-4o
provider: openai
model_name: gpt-4o-2024-11-20
provider_key_id: 0b6f3c1e-2f0a-4c5e-9d55-7d1a8b0c2e11

api_keys:
- id: 4a1c9e2b-7d3f-4b6a-8c5e-1f2a3b4c5d6e
display_name: ci-bot
key_hash: ${CI_BOT_KEY_SHA256}
allowed_model_ids: ["6efd592d-a73b-473d-8e2c-e9e103692f92"]

rate_limit_policies:
- id: 48af7a5c-79ff-4813-9a33-f4f5f5ace21f
name: cap-gpt4o
scope: model
scope_ref: 6efd592d-a73b-473d-8e2c-e9e103692f92
window: minute
max_requests: 300

global:
pricing:
- id: 2b7e4f10-6c3a-4d58-9e21-8f0a1b2c3d4e
key: openai/gpt-4o
input_per_1k: 0.0025
output_per_1k: 0.01

This reference documents the following collections:

CollectionPurpose
provider_keysStore upstream provider credentials and connection settings.
modelsDefine caller-facing model aliases and dispatch behavior.
api_keysAuthenticate callers and control their model, MCP tool, and A2A agent access.
oidc_providersTrust JWT issuers for caller authentication.
mcp_auth_settingsConfigure OAuth discovery and optional anonymous access for MCP clients.
claim_mappingsResolve verified JWT claims to caller API keys.
guardrailsScreen or transform request and response content.
guardrail_attachmentsBind a guardrail to the traffic it inspects.
mcp_serversExpose MCP servers or OpenAPI operations as tools.
a2a_agentsRegister upstream agents for A2A callers.
passthrough_routesRelay matched HTTP traffic to a provider endpoint with gateway auditing and policy.
cache_policiesCache matching non-streaming model responses.
observability_exportersExport request telemetry to external systems.
rate_limit_policiesApply conditional or single-scope request and token limits.

The file accepts every resource kind the etcd loader reads, so the other kinds the control plane stores, such as mcp_policies, teams, users, and pricing, load from a file the same way. The optional global mapping holds the documents of the shared prefix that the control plane uses for its pricing catalog, which accepts only pricing.

Entries and etcd Keys​

A collection name is the kind segment of an etcd key, and an entry is the document stored under that key plus its id. The models entry above is the row etcd holds at /aisix/models/6efd592d-a73b-473d-8e2c-e9e103692f92, and the global.pricing entry is the row at /aisix/global/pricing/2b7e4f10-6c3a-4d58-9e21-8f0a1b2c3d4e. Fields, types, defaults, and references are those of the stored document. A document that loads from etcd loads unchanged from a file, and aisix export writes the documents of an etcd store as a resources file.

Resource IDs​

Every entry needs an id:

  • The value is a UUID in lowercase hyphenated form, such as 0b6f3c1e-2f0a-4c5e-9d55-7d1a8b0c2e11. References compare IDs as strings, so an uppercase, braced, or URN spelling is not accepted.
  • An ID is unique within its collection. Two collections can use the same UUID.
  • The ID is the resource's identity, not its name. Keep the ID when you edit an entry: a different ID is a different resource, and every reference to the old ID stops matching.

Generate an ID with any UUID tool, for example:

uuidgen | tr '[:upper:]' '[:lower:]'

display_name and name are ordinary document fields. The loader does not require them to be unique, but keep them unique within a collection, because a reference by name resolves to only one entry.

References​

A field that references another resource by ID takes that entry's id: provider_key_id, allowed_model_ids, semantic.classifier.model_id, guardrail_id and scope_id on an attachment, scope_ref and the api_key and model condition values on a rate limit policy, resolve.api_key_id, anonymous.api_key_id, anonymous_key_id, and applies_to: "api_key:<id>".

Fields that the documents themselves define by name keep taking names, exactly as on etcd: allowed_models, a routing target's model, ensemble panel[].model and judge.model, a semantic router's embedding_model, route target, and default, applies_to: "model:<name>", jwt_provider, allowed_agents, allowed_routes, mcp_access patterns, mcp_rate_limits keys, and anonymous.servers.

The loader does not check that a referenced ID or name exists. An entry whose reference matches nothing still loads, and the reference resolves to nothing at request time, as it does on etcd.

Caller API Key Hashes​

A caller API key document stores key_hash, never the plaintext key. The value is the SHA-256 digest of the plaintext key as 64 lowercase hexadecimal characters, with no prefix: the digest the gateway computes from the key a caller presents. Compute it in the shell and supply it through interpolation:

export CALLER_API_KEY="YOUR_CALLER_API_KEY"
export CALLER_API_KEY_SHA256="$(printf '%s' "$CALLER_API_KEY" | sha256sum | cut -d ' ' -f 1)"
resources.yaml (caller API key)
api_keys:
- id: 85b60b85-09dc-40fc-a403-5c7c8beb4e8d
display_name: quickstart-caller
key_hash: ${CALLER_API_KEY_SHA256}

printf '%s' hashes the key without a trailing newline; echo adds one, and that digest matches no request. On macOS, use shasum -a 256 in place of sha256sum. The gateway process needs only the hash variable. The loader does not check the value's format, so an uppercase or otherwise wrong digest loads but authenticates no request.

YAML Structure​

_format_version must be exactly the string "2", quoted so YAML parses it as a string. A missing or different version means the file cannot be loaded, and an unquoted 2 gets a dedicated error asking you to quote it.

The gateway applies the following YAML constraints:

  • The file must contain exactly one YAML document whose top level is a mapping. Multiple documents separated by --- cannot be loaded.
  • The top level and every nested mapping must use string keys.
  • Each collection, when present, must be a sequence of mappings. An absent or null collection loads as empty. A collection name is one key segment and cannot contain /.
  • A top-level key that is not a known collection is read as a resource kind, the same as an unknown kind segment in an etcd key. Its entries are reported as unknown kinds and are not served.
  • A field the loader does not define is ignored and reported as partially compatible, the same as an unknown field in an etcd document. A misspelled field name therefore does not reject its entry: check the warnings from aisix validate.
  • YAML anchors and aliases can reuse values. Merge keys (<<) are not expanded; the loader ignores << as an unknown field.

Environment Interpolation​

${VAR} references resolve against the gateway process environment only when they appear in string scalars. The value is substituted into the parsed YAML tree, so an environment value can never inject YAML structure, and mapping keys are never interpolated.

This interpolation is for user-defined process variables. For AISIX-defined startup and connection variables, see Environment Variables.

  • Partial interpolation is supported: api_base: https://${UPSTREAM_HOST}/v1.
  • A variable that is unset or empty means the file cannot be loaded. The error names the variable but never its value.
  • Shell-style fallback and required-value expressions, such as ${VAR:-default} and ${VAR:?message}, are not supported.
  • $$ produces a literal $; a bare $VAR without braces passes through untouched; an unterminated ${ or empty ${} is an error.
  • Non-string scalars, including integer, float, boolean, and null values, are never interpolated.

Loading, Errors, and Reload​

The gateway reads the file at startup and on SIGHUP. It does not watch the file for changes, so an edit takes effect only after the next SIGHUP or restart. aisix validate runs the same read and load without starting a listener.

Problems fall into two levels.

The first level is the file itself. The file cannot be turned into rows when it cannot be read, is not valid YAML, does not have a mapping at the top level, has a missing or wrong _format_version, has a collection that is not a sequence of mappings, or has an entry with a missing, malformed, or duplicate id or an unset ${VAR}. Every such problem is reported together, identified by collection and position, for example models[2]. At startup, the gateway exits. On a SIGHUP reload, it keeps serving the configuration it already has, GET /status/config reports out_of_sync with each problem in rejected, and the next SIGHUP reads the file again.

The second level is each entry, checked exactly as an etcd row is. The loader validates the document against the gateway's lenient read schema, which enforces types, required fields, ranges, closed enums, and the shape of each resource, and then decodes it. An entry that fails is rejected: it is dropped and reported in the rejected array of /status/config and in aisix_config_rejected_resources, and the rest of the file serves. A rejected entry does not stop the gateway at startup. On a reload, an entry that stops loading keeps serving its last valid value, and its rejected item carries serving_stale_since.

Format Version 2​

From 1.11.0, the resources file format is version 2, and a version-1 file no longer loads: the gateway reports unrecognized _format_version "1" and does not start. Version 1 identified each entry by name, derived its ID from that name, and accepted name forms that the stored documents do not have. Version 2 removes them all:

Version 1Version 2
_format_version: "1"_format_version: "2"
No id; IDs derived from <kind>/<name>id: <UUID> on every entry
provider_key: <name> on a model, passthrough route, or semantic classifierprovider_key_id: <id>
semantic.classifier.model_ref: <name>semantic.classifier.model_id: <id>
key_env: VARkey_hash: ${VAR_SHA256}, with the digest computed as in Caller API Key Hashes
anonymous_key: <name> on a passthrough routeanonymous_key_id: <id>
anonymous.api_key: <name> on mcp_auth_settingsanonymous.api_key_id: <id>
resolve.api_key: <name> on a claim mappingresolve.api_key_id: <id>
guardrail_id and scope_id on an attachment as namesThe guardrail's and the target's IDs; a team scope keeps the team ID
scope_ref and api_key or model condition values on a rate limit policy as namesThe target entry's ID
applies_to: "api_key:<derived ID>"applies_to: "api_key:<id>" with the caller API key's id
secret on a provider keyapi_key
display_name on an MCP server, A2A agent, or passthrough routename
A semantic guardrail with deny_examples or allow_examples but no matching threshold, which loaded at 0.75deny_threshold or allow_threshold set explicitly, measured as described in Calibrate Semantic Screening Guardrails

The following file is the same configuration in both versions. Version 1:

resources.yaml (version 1, no longer loads)
_format_version: "1"
provider_keys:
- display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}
models:
- display_name: gpt-4o
provider: openai
model_name: gpt-4o
provider_key: openai-prod
api_keys:
- display_name: ci-bot
key_env: CI_BOT_KEY
allowed_models: ["gpt-4o"]

Version 2:

resources.yaml
_format_version: "2"
provider_keys:
- id: 0b6f3c1e-2f0a-4c5e-9d55-7d1a8b0c2e11
display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}
models:
- id: 6efd592d-a73b-473d-8e2c-e9e103692f92
display_name: gpt-4o
provider: openai
model_name: gpt-4o
provider_key_id: 0b6f3c1e-2f0a-4c5e-9d55-7d1a8b0c2e11
api_keys:
- id: 4a1c9e2b-7d3f-4b6a-8c5e-1f2a3b4c5d6e
display_name: ci-bot
key_hash: ${CI_BOT_KEY_SHA256}
allowed_models: ["gpt-4o"]

Loading behavior changes with the format:

  • An invalid entry is rejected on its own instead of rejecting the whole file, as described in Loading, Errors, and Reload.
  • An unknown field is ignored and reported instead of rejecting the file, and an unknown top-level key is reported as an unknown kind.
  • The checks that only the file performed are gone: unique names, references that must name an entry in the file, two caller API keys with the same credential, a unique jwt_provider and jwt_subject pair, and the strict write-schema checks that the read schema does not repeat.

Provider Keys​

A provider key stores an upstream credential together with the connection settings used for that provider. Models and passthrough routes reference a provider key by its id through provider_key_id.

FieldTypeRequiredDescription
display_namestringyesName of the provider key.
api_keystringconditionalThe upstream provider's API key. Supply it as ${VAR}. The gateway does not read the former spelling secret: an entry that still uses it has no api_key and is rejected. Some provider credentials contain more than one field. For these providers, supply a JSON credential document through one environment variable. See the credential shapes for AWS Bedrock and Azure OpenAI with Entra ID.
providerstringnoUpstream provider identifier, such as openai or deepseek. An open string used for provider-specific dispatch. Default: empty.
adapterenumnoUpstream protocol family used when no provider-specific dispatch applies: openai, anthropic, bedrock, vertex, or azure-openai. See Adapter Protocol Families.
api_basestringnoOverride base URL for the upstream provider. Required in practice for private OpenAI-compatible endpoints. Supports partial interpolation, such as https://${UPSTREAM_HOST}/v1.
api_versionstringnoAzure OpenAI REST API version for this key's requests: a dated version such as 2024-10-21 or 2025-04-01-preview, or v1 (preview and latest are aliases of v1). Applies only when adapter is azure-openai; other adapters ignore it. Default: each operation's own dated version. See Set the API Version.
apisobjectnoNative API surfaces this endpoint serves, and where. Present with a surface omitted means that surface is not served natively and the gateway translates to chat completions instead. Omit the block entirely to resolve every surface from provider and adapter, which is the default. The bedrock, vertex, and azure-openai adapters do not accept it. See Declare the API Surfaces.
apis.responsesobjectnoThe endpoint serves /v1/responses natively. Authoritative once apis is present: leaving it out is how you state the endpoint has no such route. The surface is unavailable with bedrock, vertex, and azure-openai adapters, which use the bridge. Codex Lite-mode requests add a provider-dependent exception; see Lite-Mode Tool Requests.
apis.messagesobjectnoThe endpoint serves /v1/messages and /v1/messages/count_tokens natively. Additive — a key whose adapter is anthropic serves them either way; listing the surface adds them to a key whose adapter is something else.
apis.<surface>.basestringnoBase URL for that surface, when the endpoint serves it on a different path from api_base. Same shape rules as api_base. Omit it when the surface is served at api_base.
strip_headersarray of stringsnoInbound headers removed before forwarding on inject-mode passthrough routes that use this key, on top of the credential slots those routes always remove. Default: authorization, cookie, set-cookie, x-api-key. Entries are trimmed, lowercased, and deduplicated. An explicit [] clears this list and releases no credential slot: inject mode always strips authorization, proxy-authorization, x-api-key, api-key, x-goog-api-key, cookie, x-amz-security-token, x-amz-date, and x-amz-content-sha256. Not an absolute prohibition: the route's own forward_client_headers overrides it, a credential slot needs a pattern that names it exactly, and for a name that is neither a credential nor a trace-context header a glob such as x-* is enough to put the header back on the wire.
tlsobjectnoPer-endpoint TLS settings for HTTP provider dispatch. Amazon Bedrock and Realtime dispatch ignore this block; use the applicable deployment-wide upstream.tls setting instead.
tls.ca_certstringnoPEM-encoded certificate authority certificates trusted as additional issuers for this HTTP endpoint. A bundle can contain several certificates. See TLS and mTLS.
tls.verifybooleannoWhether to verify this HTTP endpoint's certificate. Default: true. Setting it to false accepts any certificate and is for test environments only.
resolve_addressesarraynoIP addresses the gateway connects to for this key's api_base host, instead of resolving that host through DNS. Each entry is an IPv4 or IPv6 address literal, without a port and without brackets; they are tried in the order given. Host, the TLS server name, the certificate check, the scheme, and the port keep coming from api_base. Not honored for Amazon Bedrock, for /v1/realtime, or when the gateway reaches its upstreams through a forward proxy. See Pin the Endpoint Addresses.
telemetry_tagsobjectnoAttribution tags emitted with requests routed through this key.
telemetry_tags.kindenumnoAttribution category: catalog or byo.
telemetry_tags.featuredbooleannoWhether the provider key is featured. Default: false.
telemetry_tags.branded_providerstringnoBranded provider slug for catalog entries.
telemetry_tags.pk_labelstringnoOperator-defined provider-key label, such as production.
telemetry_tags.byo_labelstringnoOperator-defined bring-your-own label, such as a team name.
requestobjectnoRequest-shape overrides applied before dispatch.
request.param_renamesmap of string to stringnoTop-level request body keys named on the left are renamed to the key on the right before dispatch.
request.param_constraintsobjectnoClamp bounds for temperature in chat completion bodies.
request.param_constraints.temperature_minnumbernoMinimum accepted temperature. When omitted, no lower bound is applied.
request.param_constraints.temperature_maxnumbernoMaximum accepted temperature. When omitted, no upper bound is applied.
request.default_headersmap of string to stringnoHeaders added to the outbound request. Because the loader resolves ${...} from the environment first, write request-context references as $${...}; for example, $${request.api_key.team_id} loads as ${request.api_key.team_id} for per-request rendering. A header whose variables have no value is dropped rather than sent empty. These headers outrank a header relayed by forward_client_headers for every name except a credential slot, where the forwarded value wins; and they cannot replace a name the gateway sets itself. host, the hop-by-hop headers, and x-aisix-* are dropped whatever the source, and the AISIX Cloud Admin API rejects those same names when you save the provider key. A credential name is accepted on both paths, and reaches the upstream only in a slot the provider bridge left empty. This half of the request block does not apply on /v1/realtime, where only forward_client_headers takes effect. See Upstream Request Headers.
request.forward_client_headersarray of stringsnoInbound client headers relayed to the upstream, as exact names or single-* globs such as x-trace-*, matched case-insensitively. Empty (the default) forwards nothing, with one exception: on /v1/messages and /v1/messages/count_tokens sent to Anthropic or an Anthropic-compatible endpoint, the caller's anthropic-beta is forwarded as sent, every value of it, without being listed here. An anthropic-beta that default_headers sets on the request applies in its place. Listing anthropic-beta here, by name or by a pattern that matches it such as * or anthropic-*, still sends only the caller's value, under the rules for listed headers, so only its first value is forwarded. A credential slot and the trace-context headers traceparent / tracestate are relayed only when a pattern names them exactly; a glob never matches them, x-amz-* included. A relayed credential takes the slot this key would otherwise inject into, never joining it. host, hop-by-hop headers, x-aisix-*, the body and negotiation headers the gateway re-serializes (content-type, content-length, accept, accept-encoding, content-encoding, expect), set-cookie, anthropic-version, and x-stainless-* are never relayed. On a Bedrock-shaped key the SigV4-signed names (authorization, x-amz-date, x-amz-content-sha256, x-amz-security-token, x-amz-target, x-amzn-bedrock-accept) are dropped rather than delivered. To Claude on Amazon Bedrock or Vertex AI, anthropic-beta is filtered to the betas that platform accepts, and Bedrock receives it in the body's anthropic_beta rather than as a header; on /v1/messages the caller's betas reach the platform even when no pattern names the header. See Claude Beta Values. On /v1/realtime the handshake slots that face owns (sec-websocket-accept, sec-websocket-extensions, sec-websocket-key, sec-websocket-protocol, sec-websocket-version) are refused even when a pattern names one in full. See Upstream Request Headers.
request.default_body_fieldsmap of string to JSON valuenoTop-level body fields added to the outbound request when the caller did not set them.
responseobjectnoResponse-shape overrides applied by provider bridges that support them.
response.stream_done_markerenumnoWhether the upstream SSE stream is expected to emit data: [DONE]: required, optional, or none. Omitted accepts either.
response.content_list_to_stringbooleannoWhen true, flattens a messages[*].content array of text blocks into a single string before dispatch. Default: false.
response.reasoning_fieldstringnoPath used to lift reasoning content from the provider response, such as delta.reasoning_content.
response.error_envelopestringnoStored error-envelope preference kept for compatibility with control-plane configuration; the proxy does not currently apply it.

The following example brings those settings together. It defines one OpenAI provider key and one private OpenAI-compatible endpoint. The private endpoint declares the openai adapter, builds its base URL from the environment, and trusts an additional certificate authority.

resources.yaml
_format_version: "2"

provider_keys:
- id: 83eba07c-0ad3-4b81-b760-247f2d978e95
display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}
- id: dd566077-11b5-4131-84b7-7eeeef830acb
display_name: internal-vllm
provider: internal-vllm
adapter: openai
api_base: https://${UPSTREAM_HOST}/v1
api_key: ${INTERNAL_LLM_KEY}
# Only needed when this endpoint's certificate is signed by a
# private or enterprise certificate authority.
tls:
ca_cert: |
-----BEGIN CERTIFICATE-----
MIIB...
-----END CERTIFICATE-----

Models​

A model entry defines a caller-facing alias. Direct, embedding, routing, ensemble, and semantic aliases all appear in /v1/models; wildcard patterns do not (see Model Aliases). Every entry uses exactly one dispatch shape: direct, routing, ensemble, or semantic. An entry that mixes shapes is rejected.

The following fields for timeouts, retries, access, cost, and inline limits are shared across model shapes, but each is accepted only on the kinds where the gateway resolves it — the Applies to column lists them. A field set on a kind that does not resolve it is ignored and reported as partially compatible:

FieldTypeApplies toDescription
display_namestringallThe caller-facing alias. Required on every shape. Keep it unique within models, because name references resolve to one entry.
timeoutinteger (ms)direct, embedding, routing, semanticEnd-to-end deadline for non-streaming upstream calls. On a routing model or semantic router this is the group/router-level slot applied to every target that does not set its own; absent falls back through that slot, then the deployment-wide upstream.timeout_ms default (6000000 ms = 6000 s). 0 disables it. Ignored on ensemble — its per-call deadline is ensemble.timeout_ms.
stream_timeoutinteger (ms)direct, embedding, routing, semanticMaximum gap between upstream streaming chunks. 0 or absent falls back to the group/router stream_timeout, then to timeout, then to the deployment defaults. Ignored on ensemble.
retriesintegerdirect, embedding, semanticRetry attempts against this model after a retryable upstream failure. On a semantic router this is the router-level slot. 0 disables same-target retries. A routing model does not take a top-level retries — its group slot is routing.retries (below); a routing target's own retries overrides that. Ignored on ensemble.
rate_limitobjectallPer-model request, token, and concurrency limits, enforced on the entry the caller addressed. See below.
allowed_cidrsarray of stringsallClient IP allowlist in CIDR notation (IPv4 and IPv6). Empty or absent allows all clients. With a restriction configured, a missing or malformed source IP is denied.
costobjectdirect, embeddingPer-token price metadata for least_cost ranking: input_per_1k and output_per_1k, both prices per 1,000 tokens and both required when the block is present. Set it on the direct/embedding models a group dispatches to, not on the group.

Within rate_limit, each field is optional and unlimited when absent:

FieldLimit
rate_limit.rpsRequests per fixed 1-second window.
rate_limit.rpmRequests per 60-second window.
rate_limit.rphRequests per 3,600-second window.
rate_limit.rpdRequests per 86,400-second window.
rate_limit.tpmTokens per 60-second window.
rate_limit.tpdTokens per 86,400-second window.
rate_limit.concurrencyMaximum in-flight requests. This is a semaphore, not a window.
rate_limit.window_typefixed (default) or sliding. How rpm, rph, rpd, tpm, and tpd count; rps and concurrency are not affected. See Choose a Window Type. Requires gateway 1.10.0 or later.

With the default fixed, windows are aligned to the UTC clock and reset as a whole at each boundary: the top of the second, minute, or hour, and 00:00 UTC for rpd and tpd.

Direct Models​

The direct shape names one upstream model behind one provider key:

FieldTypeRequiredDescription
providerstringyesVendor identity such as openai or anthropic. Starts with a lowercase letter or digit; ., _, and - are allowed after the first character; 1–64 characters.
model_namestringyesUpstream model identifier sent in provider requests, such as gpt-4o-2024-11-20.
provider_key_idstringyesid of the provider_keys entry the model sends its requests with.
embeddingobjectnoMarks the model as embedding-capable: dimensions (required, vector dimensionality) and normalize (default true, whether the endpoint already returns L2-normalized vectors). The model can then serve /v1/embeddings and back a semantic router.
background_model_checkobjectnoBackground health checks. See Health Checks. Sub-fields enabled, interval_seconds (min 5), timeout_seconds, prompt, max_tokens, and stale_after_seconds are required when the block is present; ignore_statuses (array of status codes) is optional.
cooldownobjectnoRequest-path cooldown after retryable upstream failures. Cooldown is opt-in: omit the block, or leave enabled unset, and request-path failures never take the model out of rotation. See below.
auto_prompt_cachingobjectnoAutomatic Anthropic prompt-cache marker injection. Supported only for direct models whose provider is anthropic. enabled is required when the object is present; ttl is 5m (default) or 1h. See Anthropic Prompt Caching.
effort_mappingobject of strings or nullnoDirect-model request-effort rewrites. Each key is a caller value and each value is the upstream value, or null to remove the effort. The key "" matches a request that sets no effort and "*" matches any other value without an entry of its own. The lookup runs once after final target selection — exact key first, then "*"; absent or empty disables it. See Reasoning Effort Mapping.

The optional cooldown object accepts these settings. Only enabled: true turns cooldown on; the remaining settings are the parameters it uses once it is on, and setting one of them on its own does not enable the feature:

FieldDefaultBehavior
cooldown.enabledfalseEnables request-path cooldown tracking. A model that omits the cooldown block, or leaves this field unset, stays in rotation regardless of upstream failures.
cooldown.default_seconds30Sets the cooldown TTL when no usable Retry-After header exists. 0 switches cooldown off for the model entirely, including the Retry-After path, rather than producing a zero-length cooldown.
cooldown.max_seconds600Caps a cooldown derived from Retry-After.
cooldown.honor_retry_aftertrueUses a valid Retry-After value when available.
cooldown.trigger_statuses[401, 408, 429, 500, 502, 503, 504]Status codes that trigger cooldown. Setting the field replaces the complete default list.
cooldown.trigger_on_timeouttrueTriggers cooldown after an upstream timeout.
cooldown.trigger_on_transporttrueTriggers cooldown after an upstream transport failure, or an in-band error that carries no status. On /v1/realtime, a refused handshake has a status and takes trigger_statuses, and a dial past upstream.connect_timeout_ms takes trigger_on_timeout.

Embedding settings, background model checks, and cooldown are accepted only on direct models; an entry of another shape that sets one is rejected. Automatic prompt caching applies only to direct models whose provider is Anthropic.

Routing Models​

A routing entry selects one target per request and dispatches through that target model's upstream configuration:

FieldTypeRequiredDescription
routing.targetsarrayyesOrdered target set with at least one entry. Per-request routing-tag and allowed_cidrs filters narrow this set before the configured strategy orders the survivors.
routing.targets[].modelstringyesName of an existing direct model that can receive routed traffic.
routing.targets[].weightintegernoDefault: 1. Sets the rotation share under round_robin, the share of the hash ring under consistent_hash, and the denominator max(weight, 1) of the least_busy score. At runtime, 0 is treated as 1. failover, least_cost, and least_latency accept but ignore it.
routing.targets[].priorityintegernoDefault: 0. Splits eligible targets into tiers, with higher values preferred. A lower tier is tried after no higher-tier target remains available; use -1 for a backup tier.
routing.targets[].tagsarray of stringsnoTags used for per-request eligibility. If no target has tags, tag filtering is inactive and all targets remain eligible. Otherwise, a request carrying tags keeps targets with at least one match, then falls back to targets tagged default if none match. An untagged request prefers default targets and otherwise leaves all targets eligible.
routing.strategyenumnoround_robin (smooth weighted round-robin), consistent_hash, failover (default), least_cost, least_latency, or least_busy. Positional strategies pick a starting target per priority tier and walk forward on failure; metric strategies rank targets best-first within each tier.
routing.retriesintegernoDefault retry attempts on each target before failing over. A target model's retries overrides it. If neither is set, AISIX moves to the next eligible target without retrying and applies the deployment-wide default only to the last target.
routing.max_fallbacksintegernoMaximum later targets attempted after the initial target fails. Default: all later targets. 0 disables failover.
routing.retry_on_429booleannoWhether an upstream 429 participates in retries and failover. Default false.
routing.fallback_on_statusesarray of integersnoAdditional 4xx status codes treated as retryable, for providers that use them for transient conditions, such as [408, 409]. 5xx codes are already retryable.
routing.when_all_unavailableenumnofail (default): return 503 when health and cooldown state rule out every target. try_anyway: attempt every target in declaration order regardless.
routing.hash_onarraynoconsistent_hash only: the ordered hash-key source chain, first non-empty value winning. Each entry is {type, name?} with type one of header, cookie (both named by name), api_key, or client_ip. Default: the x-aisix-routing-key header, then the caller's API key.

See Multi-Target Routing and Failover for configuration, routing behavior, and a runnable failure test.

Ensemble Models​

An ensemble entry fans each request out to every panel member concurrently, then has a judge model synthesize one answer:

FieldTypeRequiredDescription
ensemble.panelarrayyesPanel members, minimum one. panel[].model names a direct model; optional panel[].temperature and panel[].seed override sampling per member; panel[].weight is accepted and currently ignored.
ensemble.judgeobjectyesjudge.model names the direct model that performs synthesis; optional judge.synthesis_prompt overrides the built-in synthesis prompt.
ensemble.min_responsesintegernoMinimum successful panel responses required before synthesis. Default: the smaller of 2 and the panel size. Clamped to the panel size, floored at 1.
ensemble.timeout_msinteger (ms)noPer-call deadline for each panel member and the judge call. 0 or absent disables it.

See Ensemble Models for behavior and response shape.

Semantic Routers​

A semantic entry embeds the request's latest user text, scores it against each route's example embeddings, and dispatches to the best route above the threshold. When no route clears the threshold, it dispatches to default.

FieldTypeRequiredDescription
semantic.embedding_modelstringconditionalName of an embedding-capable direct model (one carrying an embedding block). Required unless semantic.classifier is set.
semantic.routesarrayyesRoutes, minimum one. Each route requires name (recorded in the access log's semantic_route field, and surfaced in the x-aisix-route response header when proxy.expose_debug_headers is true), target (the name of a direct model or a model group), and examples (at least one example utterance; embedded on the first request that needs them and cached); optional description (documentation only) and threshold (overrides match.threshold for this route).
semantic.defaultstringyesDirect model or model group that receives requests matching no route.
semantic.matchobjectconditionalRequired unless semantic.classifier is set. Shared matching parameters: threshold (required, 0.0–1.0, higher is stricter), distance_metric (cosine, the only supported value), and aggregation (max, the only supported value; a route scores by its best-matching example).
semantic.embedding_timeout_msinteger (ms)noDeadline for the embedding call. 0 or absent disables it.
semantic.on_embedding_failureenum or objectnoWhat to do when the embedding call fails: default (route to the default model; this is the default behavior), fail (reject with 503), or { target: "<alias>" } (route to a specific direct model or model group).
semantic.classifierobjectnoSelects the route with a TypeSafe jev decision model instead of embeddings. When set, the router must not set embedding_model, embedding_timeout_ms, on_embedding_failure, or match, and its routes take a required description and no examples or threshold. See Semantic Routing with TypeSafe Jev.
semantic.classifier.model_idstringnoid of the direct model the classifier calls for its decisions, on a typesafe provider key. When set, the classifier's provider_key_id and model are not read. See Configure a Jev Router.
semantic.session_affinityobjectnoKeeps a session on the route its first matched request took: enabled (default false) and ttl_seconds (default 3600, 60–604800), how long a pin lasts after the last request that used it. Absent, every request is classified. See Pin a Session to Its Route.

See Semantic Routing for behavior and tuning.

The complete example below shows how the four model shapes relate. The three direct models are reusable targets; the remaining entries compose them into a session-pinned router, an ensemble, and a semantic router.

resources.yaml
_format_version: "2"

provider_keys:
- id: 06475d5a-8aea-457e-856d-55d34d7cafbb
display_name: openai-main
provider: openai
api_key: ${OPENAI_API_KEY}

models:
- id: ccd6c189-04bb-44a9-bd0a-1545a04504e9
display_name: gpt-4o
provider: openai
model_name: gpt-4o
provider_key_id: 06475d5a-8aea-457e-856d-55d34d7cafbb
timeout: 30000
rate_limit:
rpm: 100
tpm: 100000
cost:
input_per_1k: 0.0025
output_per_1k: 0.01
- id: 9f46bd07-eaae-4c3e-a1ae-61b420c32f10
display_name: gpt-4o-mini
provider: openai
model_name: gpt-4o-mini
provider_key_id: 06475d5a-8aea-457e-856d-55d34d7cafbb
- id: 43d4a2fa-448c-4cd1-844d-6fb18a240f89
display_name: text-embed
provider: openai
model_name: text-embedding-3-small
provider_key_id: 06475d5a-8aea-457e-856d-55d34d7cafbb
embedding:
dimensions: 1536
- id: 5183df2e-1711-4a45-915f-2671dcd3fb34
display_name: balanced
routing:
strategy: consistent_hash
targets:
- model: gpt-4o
weight: 90
- model: gpt-4o-mini
weight: 10
retries: 1
retry_on_429: true
- id: 737e8e4e-8846-4bb3-89da-f788076a7e47
display_name: council
ensemble:
panel:
- model: gpt-4o
- model: gpt-4o-mini
temperature: 0.2
judge:
model: gpt-4o
min_responses: 2
timeout_ms: 45000
- id: f090a30f-1528-4a66-972a-4890f95ec274
display_name: smart-router
semantic:
embedding_model: text-embed
routes:
- name: coding
target: gpt-4o
examples:
- "Write a Python function that parses CSV"
- "Debug this stack trace"
threshold: 0.8
default: gpt-4o-mini
match:
threshold: 0.75
on_embedding_failure: default

Caller API Keys​

A caller API key entry authenticates the applications that call the gateway. The file never holds the plaintext key: the entry carries its SHA-256 digest in key_hash, as described in Caller API Key Hashes.

FieldTypeRequiredDescription
display_namestringnoName of the caller API key.
key_hashstringyesSHA-256 digest of the plaintext key, as 64 lowercase hexadecimal characters. Supply it as ${VAR}.
allowed_modelsarray of stringsnoModels this key may use. Entries are single-* globs: "*" grants every model, "team-a/*" grants matching names, and an entry without * matches the model with that display_name. Read only when allowed_model_ids is absent. Omitting both fields, or giving an empty array, grants the key no model at all — model access is always granted explicitly.
allowed_model_idsarray of stringsnoModels this key may use, by id. When present, including as an empty array, it is authoritative and allowed_models is not read.
allow_all_modelsbooleannoGrants every model defined in the file, of every kind, including models added later. When true, allowed_model_ids and allowed_models are not read. It covers models only: allowed_agents, allowed_routes, and mcp_access still govern agents, passthrough routes, and MCP tools. Default false.
rate_limitobjectnoPer-key limits with the same sub-fields as a model's rate_limit: rps, rpm, rph, rpd, tpm, tpd, concurrency.
mcp_rate_limitsobjectnoPer-MCP-server request and concurrency limits for this key. Keys are registered MCP server names; see below.
mcp_accessobjectnoMCP tools this key may call: an allow list (required) and an optional deny list of <server>__<tool> names, matched as single-* globs — "github__*" covers every tool on one server. Omitting the block means no MCP tool access here; see below.
allowed_agentsarray of stringsnoA2A agents this key may reach, by registered name, matched as single-* globs. Omitted, null, or empty means no A2A agent access.
allowed_routesarray of stringsnoPassthrough routes this key may use, by route name, matched as single-* globs. Omitted, null, or empty means no passthrough route access.
jwt_subjectstringnoExternal identity selected from a verified JWT. Set it together with jwt_provider.
jwt_providerstringnoName of the oidc_providers entry allowed to assert jwt_subject. Required when jwt_subject is set.
expires_atstringnoRFC 3339 timestamp after which the key stops authenticating with 401. Omitted means the key never expires. A malformed timestamp rejects the entry at load rather than silently never expiring.
disabledbooleannoAdministratively disable the key: requests are rejected with 401 until it is enabled again. Default false.
team_idstringnoTeam attribution, matched verbatim by rate_limit_policies with scope: team.
user_idstringnoOwning member attribution, matched verbatim by member-scope policies.
user_namestringnoReadable owner name for telemetry labels only.

MCP Tool Access and Limits​

Grant MCP tool access with mcp_access. In AISIX Enterprise and AISIX Cloud, the block is one layer of a three-layer ACL, intersected with the environment and team access policies stored as mcp_policies. A resources file loads mcp_policies entries the same way; without them, the block is the key's only layer, and a key without one reaches no MCP tool. allow is required — send ["*"] for a key that should narrow nothing and rely on deny alone, or [] for one that may call nothing.

Use mcp_rate_limits to give one caller key a separate limit for each registered MCP server. Each server entry supports the following fields:

FieldLimit
rpsRequests per second.
rpmRequests per minute.
rphRequests per hour.
rpdRequests per day.
concurrencyMaximum in-flight tool calls.
window_typefixed (default) or sliding. How rpm, rph, and rpd count. Requires gateway 1.10.0 or later.

These limits apply to tools/call requests alongside the key's general rate_limit; initialization and tool-list requests are not counted.

This example gives one caller access to a model and every tool exposed by the github MCP server. The general rate_limit applies alongside the tool limits, while mcp_rate_limits.github adds a tighter limit for that server's tool calls.

resources.yaml
_format_version: "2"

provider_keys:
- id: 06475d5a-8aea-457e-856d-55d34d7cafbb
display_name: openai-main
provider: openai
api_key: ${OPENAI_API_KEY}

models:
- id: ccd6c189-04bb-44a9-bd0a-1545a04504e9
display_name: gpt-4o
provider: openai
model_name: gpt-4o
provider_key_id: 06475d5a-8aea-457e-856d-55d34d7cafbb

mcp_servers:
- id: 631940a7-bdb5-4d67-9ffd-74798b91df52
name: github
type: mcp
url: https://api.example.com/mcp

api_keys:
# MY_APP_KEY_SHA256 holds the SHA-256 digest of the caller key;
# the plaintext never appears in the file.
- id: 961a73a4-00c3-4379-a4af-99a8bd9dd7ec
display_name: my-app
key_hash: ${MY_APP_KEY_SHA256}
allowed_models: ["gpt-4o"]
mcp_access:
allow: ["github__*"]
rate_limit:
rpm: 60
concurrency: 5
mcp_rate_limits:
github:
rpm: 30
concurrency: 2

OIDC Providers​

An oidc_providers entry defines how the gateway verifies JWT tokens from an external token issuer. A verified identity maps to the caller API key whose jwt_provider and jwt_subject fields match the provider and token.

FieldTypeRequiredDescription
namestringyesProvider name. Caller API keys and claim mappings reference the provider by this name through jwt_provider.
issuerstringyes*Expected JWT iss claim, compared exactly. A configured issuer must be distinct among enabled providers. Required for JWKS verification and optional when hmac_secret is set; an issuer-less shared-secret provider does not check iss.
audiencesarray of stringsyes*Accepted JWT aud values. JWKS verification requires at least one, and the token must contain a match. With hmac_secret, omit the field or use an empty list to skip audience validation.
jwks_uristringnoJWKS endpoint used to fetch signing keys. When omitted, AISIX resolves it from <issuer>/.well-known/openid-configuration. Must be absent when hmac_secret is set.
hmac_secretstringnoShared secret for HMAC-signed tokens. Setting it switches the entry to HMAC verification: tokens are accepted only under HS256, HS384, or HS512, no signing keys are fetched, and issuer and audiences become optional. Its UTF-8 bytes are the HMAC key as-is — nothing is base64-decoded or derived — and it must be at least 32 bytes long. Supply it as ${VAR}. Default: unset, meaning JWKS verification.
identity_claimstringnoClaim whose string value selects a caller API key's jwt_subject. The whole string is first read as one claim name, then dots traverse nested objects. Default: sub.
required_scopesarray of stringsnoScopes that must all appear in the token's scope claim. The claim may be a space-delimited string or an array. Default: no required scopes.
bound_claimsobjectnoAdditional claim requirements that must all pass. Each key is first read as one claim name, then dots traverse nested claims. Each value is a string or a nonempty array; a string claim must equal an accepted value, and an array claim must contain one.
tag_claimsobjectnoCost attribution tags read from the verified token on each request, as tag key to claim path. Per tag key, a value read this way takes precedence over the caller API key, its team, and its member. Keys match ^[a-z][a-z0-9_]{0,62}$, paths are non-empty, and at most 32 entries are allowed. See How a Claim Becomes a Tag Value.
leeway_secsintegernoClock-skew allowance from 0 to 300 seconds for exp and nbf. Default: 0.
loginobjectnoOAuth client the gateway signs users in with, for MCP clients configured with only a URL: client_id (required), client_secret (supply it as ${VAR}), and scopes. Needs an issuer and no hmac_secret, and only one enabled entry can have it. See Interactive MCP Sign-In.
enabledbooleannoWhether the provider participates in authentication. Default: true.

Keep credential-like query parameters, such as access_token or client_secret, out of issuer and jwks_uri.

URL user information is not a protected secret

User information in these URLs (user:password@) is accepted and used as written, and gateway logs can include the issuer. Prefer credential-free HTTPS endpoints or network-level access controls.

An entry without hmac_secret is verified against a JWKS: it requires issuer and audiences, accepts asymmetric JWT signing algorithms, and rejects HMAC-signed tokens. See JWT Authentication for supported algorithms, request behavior, and key rotation.

AISIX rejects an entry that sets both jwks_uri and hmac_secret, one without hmac_secret that lacks an issuer or at least one audience, and an hmac_secret shorter than 32 bytes.

The following configuration trusts the corp-keycloak issuer and maps the JWT subject agent-billing-01 to the billing-agent caller entry.

Every caller entry still requires key_hash, even when JWT authentication is enabled. Set BILLING_AGENT_KEY_SHA256 in the gateway process environment before loading this example. The empty allowed_models list denies model access; add model aliases when this identity should call model endpoints.

resources.yaml
_format_version: "2"

oidc_providers:
- id: f1aac41c-d83d-41ef-b2d3-abae0b774fbe
name: corp-keycloak
issuer: https://sso.example.com/realms/agents
audiences: ["aisix-gateway"]
required_scopes: ["ai.access"]
bound_claims:
department: ai-lab

api_keys:
- id: 733cfd25-85c2-45cb-a502-734de9b9bd97
display_name: billing-agent
key_hash: ${BILLING_AGENT_KEY_SHA256}
allowed_models: []
jwt_subject: agent-billing-01
jwt_provider: corp-keycloak

This entry instead trusts an issuer that signs with a shared secret. JWT_HMAC_SECRET holds the secret in the gateway process environment, so the plaintext stays out of the file. The entry pins no issuer and no audiences, so those claims are not checked; add them when the issuer sets them and you want them enforced.

resources.yaml (OIDC provider)
oidc_providers:
- id: 7a6ec1e8-3a10-4c31-8463-19f6c122c46f
name: partner-hmac
hmac_secret: ${JWT_HMAC_SECRET}
required_scopes: ["ai.access"]

Give each issuer-less shared-secret entry its own secret. Two that share one secret both verify the same token, so whichever sorts first by name always wins.

MCP Authentication Settings​

The optional mcp_auth_settings collection controls how clients authenticate at /mcp and /mcp/{server}. It is a per-environment singleton, so keep at most one entry. The loader accepts a second entry, but the gateway then keeps both OAuth discovery and anonymous access off until only one entry remains, rather than choosing between them. The entry carries two independent settings: resource_url enables OAuth discovery when an OIDC provider is also enabled, while anonymous opens selected MCP entries to callers from trusted networks that present no credential.

FieldTypeRequiredDescription
resource_urlstringnoCanonical public URL of the gateway's /mcp endpoint. OAuth discovery activates when the value parses as an absolute http or https URL, has no query or fragment, and its path ends with /mcp. Use a percent-encoded path without empty, . or .. segments so a front gateway does not normalize it differently from the resource URL AISIX publishes. A prefix before /mcp, as in /team-a/mcp, is for a gateway in front of AISIX that strips it before forwarding; see Run Behind a Path-Prefix Gateway. The URL is published as written on an unauthenticated endpoint, user information included, so do not put credentials in it. The gateway does not compare it with a token's aud; see OAuth Sign-In for what audiences must list.
anonymousobjectnoAnonymous-access settings. When omitted, every MCP request must present a valid gateway API key or trusted OAuth access token.
anonymous.enabledbooleannoWhether anonymous access is active. Default: true. Set it to false to retain the settings while closing anonymous access.
anonymous.api_key_idstringyes*id of the api_keys entry that anonymous requests run as. The key's MCP grant, limits, guardrails, and usage attribution apply normally. Required when anonymous is set.
anonymous.source_cidrsarray of stringsyes*Non-empty list of client source CIDRs allowed to enter anonymously. AISIX matches the resolved client address from its real-IP configuration, not an untrusted caller-supplied header. Required when anonymous is set.
anonymous.serversarray of stringsyes*Non-empty list of MCP server names anonymous callers may reach. The list is also a ceiling on the principal's access through the aggregated /mcp endpoint. Required when anonymous is set.
anonymous.aggregate_entrybooleannoWhether the aggregated /mcp endpoint also serves anonymous callers. Default: false. Enabling it suppresses the 401 that otherwise starts OAuth discovery for a client without credentials.

This example enables OAuth discovery and opens the docs server anonymously to one trusted network. It names the anonymous-mcp key by its id in anonymous.api_key_id:

resources.yaml
_format_version: "2"

oidc_providers:
- id: 5a46d289-7c60-48f0-8a3b-4c32045efdea
name: corp-sso
issuer: https://sso.example.com/realms/agents
audiences:
- https://gateway.example.com/mcp
required_scopes:
- mcp:tools

api_keys:
- id: 4e651924-0b3e-4bcc-a782-0c4ed895171e
display_name: anonymous-mcp
key_hash: ${ANONYMOUS_MCP_KEY_SHA256}
allowed_models: []
mcp_access:
allow:
- docs__*

mcp_servers:
- id: 4a9f320a-6f52-48bc-b137-7a43fa4d86e1
name: docs
type: mcp
url: https://docs.example.com/mcp

mcp_auth_settings:
- id: 294d3ba9-93df-4477-b637-18c8a834cb0b
resource_url: https://gateway.example.com/mcp
anonymous:
api_key_id: 4e651924-0b3e-4bcc-a782-0c4ed895171e
source_cidrs:
- 10.0.0.0/8
servers:
- docs
aggregate_entry: false

Set ANONYMOUS_MCP_KEY_SHA256 in the gateway process environment. For the authentication workflows and security implications, see Client Authentication.

Claim Mappings​

A claim mapping resolves the verified claims of a JWT to an existing caller API key when no key binds the token's subject directly. Enabled mappings for the matched provider are evaluated in priority order (lower first, ties broken by name); the first mapping whose conditions all hold selects the key, and a token matching no mapping is rejected. See JWT Claim Mappings for evaluation semantics.

FieldTypeRequiredDescription
namestringyesMapping name. Also the evaluation tie-break for equal priorities.
jwt_providerstringyesName of the oidc_providers entry whose tokens this mapping applies to.
priorityintegernoEvaluation order among the provider's mappings; lower values are evaluated first. Default: 0.
matcharray of objectsyesClaim conditions that must all hold. Each carries claim (read as one claim name first, then dots traverse nested objects), op (exact for a string claim, contains for an array claim; non-string array items are ignored), and values (accepted alternatives). The list must contain at least one condition.
resolve.api_key_idstringyesid of the caller API key that matching requests run as.
enabledbooleannoWhether the mapping participates in evaluation. Default: true.

An empty match list rejects the entry. The loader does not check that the provider and the key exist; see References.

resources.yaml
_format_version: "2"

oidc_providers:
- id: f1aac41c-d83d-41ef-b2d3-abae0b774fbe
name: corp-keycloak
issuer: https://sso.example.com/realms/agents
audiences: ["aisix-gateway"]

api_keys:
- id: d597a758-39d4-4d3f-bb1a-31800c47dcd3
display_name: finance-policy-key
key_hash: ${FINANCE_POLICY_KEY_SHA256}
allowed_models: []

claim_mappings:
- id: 262a8c5b-b3b8-4fdc-b147-4c8af398ed86
name: finance-dept
jwt_provider: corp-keycloak
priority: 100
match:
- claim: department
op: exact
values: ["finance"]
resolve:
api_key_id: d597a758-39d4-4d3f-bb1a-31800c47dcd3

Guardrails​

A guardrail entry screens request or response content. It runs only where a guardrail attachment puts it — a guardrail nothing attaches loads, is counted, and inspects no traffic. The kind field identifies the guardrail type and determines which additional fields the entry accepts. These fields sit directly on the entry; there is no nested config object. A field the selected kind does not define is ignored and reported as partially compatible.

These fields apply to every guardrail kind unless noted:

FieldTypeRequiredDescription
namestringyesGuardrail name. Surfaces in metric labels and error reasons.
kindenumyesGuardrail type. See the kinds table below.
enabledbooleannofalse stages the rule without running it. Default true.
hook_pointenumnoWhere the rule runs: input (request payload, before the upstream call), output (upstream response), or both (default).
input_messagesenumnoMessage window available to the input check. all (default) makes the whole request available; latest_turn keeps only the messages after the last assistant message and excludes system and developer messages. A guardrail kind may read only selected roles inside that window. Input check only; the output check always reads the whole response. See Choose the Input Message Window.
directionstringnoCompatibility field for attachment-based configuration. It does not select where a resources-file guardrail runs; hook_point controls execution. Omit it from new resources files.
enforcement_modestringnoblock (default) applies matching verdicts; monitor allows content unchanged and records what the guardrail would have blocked or masked. See Enforcement Modes.
fail_openbooleannoInput-side behavior when a check cannot complete, for every kind. true allows the request and records a bypass; false (default) refuses it in block mode. In monitor mode, a backend failure is served and recorded as would_block, while gateway-raised unreadable-content handling still follows this policy. For keyword and pii, this field also governs output because those kinds do not accept output_fail_open. See When a Guardrail Cannot Complete Its Check.
output_fail_openbooleannoOutput-side failure policy for every kind except keyword and pii. true allows the response and records a bypass; false (default) refuses it in block mode. Held-back stream failures can still refuse regardless of this setting.
timeout_msintegernoDeadline for each backend call the guardrail makes, from sending the request through reading the full response body, not for the whole check; there is no overall deadline, so a check that makes several calls can take several times this value. openai_moderation and lakera make one call per check. presidio makes one analyzer call per text segment, in sequence, plus one anonymizer call for each segment it masks. azure_content_safety and azure_content_safety_text_moderation split text into chunks of at most 10,000 characters, and aliyun_text_moderation and aliyun_ai_guardrail into chunks of at most 2,000 characters; each chunk is its own call, the calls run in sequence, and the number of chunks is not capped. For semantic, it bounds each embedding request: one for example texts not yet cached, then one for all the request's screened texts. For custom, it limits the whole hook invocation, including every call the script makes. Default: 5000. keyword, pii, and bedrock do not use it; Bedrock uses latency_mode instead.
created_atstringnoRFC 3339 timestamp. When present, guardrails evaluate oldest first; entries without it sort last.

The selected kind determines which additional fields the entry accepts:

kindRequired fieldsNotable options
keywordpatterns: array of {kind: literal | regex, value} blocklist patterns, evaluated in-process. An empty list loads but matches nothing.None
semanticembedding_model; deny_threshold whenever deny_examples is non-empty, and allow_threshold whenever allow_examples is non-emptyAt least one non-empty deny_examples or allow_examples list is needed for screening. If both are empty, the guardrail loads but remains inactive. Neither threshold has a default — cosine scores are not comparable across embedding models, so set the matching threshold whenever you list examples. The read schema requires it too: an entry that lists examples without the matching threshold is rejected. Measure yours as described in Calibrate Semantic Screening Guardrails. Other options: text_source (user_messages default, or all_messages), max_screened_texts (default 8), timeout_ms, max_buffer_bytes, on_buffer_exceeded, output_fail_open. Candidate messages from one hook are embedded in one batch.
customscript: a non-empty ES moduleExport checkInput, checkOutput, or both to screen those hooks; a hook that is not exported is skipped. Other options: secrets, timeout_ms (default 5000 for the whole invocation), max_memory_bytes (default 16777216), stream_processing_mode (window default, or buffer_full), window_size, window_overlap_size, max_buffer_bytes, on_buffer_exceeded, output_fail_open.
piiNonedetectors (built-in detector list: email, china_mobile, china_id_card, bank_card, us_ssn, ip_address, api_key, jwt, private_key, each with optional per-detector action), custom_patterns (operator regexes with name, regex, and an optional per-pattern action and replacement), default_action (mask default, or block). Masked spans become [<DETECTOR>_REDACTED] unless a pattern sets replacement, which is used literally — $1 is not expanded — and replaces only capture group 1 when the regex declares one (see PII Redaction). The guardrail's own refusals and log lines do not contain matched values; see What the Gateway Records for the other text that can.
presidioanalyzer_url, anonymizer_url: base URLs of customer-run Presidio containers.entities (Presidio entity types with optional per-entity action), default_action, operator (replace default, mask, hash, redact), language (default en), score_threshold.
openai_moderationapi_keymodel (default omni-moderation-latest), category_thresholds (per-category score map; empty defers to the provider's flagged decision), endpoint override. Detection-only; never rewrites content.
lakeraapi_keyproject_id, endpoint override for regional or self-hosted deployments.
azure_content_safetyendpoint, api_keyAzure Prompt Shield on the Cognitive Services endpoint.
azure_content_safety_text_moderationendpoint, api_keycategories (default all four of Hate, Sexual, SelfHarm, Violence), severity_threshold (default 2), severity_threshold_by_category, output_type, blocklist_names, halt_on_blocklist_hit, text_source (concatenate_user_content default, or concatenate_all_content), and streaming controls below. text_source affects the input hook only.
aliyun_text_moderationregion, access_key_id, access_key_secretendpoint override, risk_level_threshold (low, medium, high; default high), streaming controls below.
aliyun_ai_guardrailregion, access_key_id, access_key_secretendpoint override, service_level (pro default, or basic), streaming controls below. The selected service tier must be activated in Alibaba Cloud.
bedrockguardrail_id, guardrail_version, region, aws_credentials ({kind: static, access_key_id, secret_access_key, session_token?}, {kind: api_key, api_key}, or {kind: default_chain}; static and default_chain also take role_arn, external_id, and role_session_name; see Choose the Guardrail Credentials), latency_mode ({kind: serial} or {kind: timed, timeout_ms: 100–5000})None

The selectable streaming kinds are Azure Text Moderation, Alibaba Cloud Content Moderation, Alibaba Cloud AI Guardrails, and custom. They support windowed or full-buffer processing. Semantic screening always buffers the complete output because it needs the whole text for comparison.

FieldApplies toBehavior
stream_processing_modeSelectable streaming kindswindow incrementally releases a sliding window and is the default. buffer_full holds the complete response before release.
window_sizeSelectable streaming kindsSets the sliding-window size.
window_overlap_sizeSelectable streaming kindsSets the overlap between consecutive windows.
max_buffer_bytesPII, Lakera, Presidio, semantic, and selectable streaming kinds in buffer_full mode. Selectable streaming kinds in window mode also use it wherever output is held whole (the whole stream on /v1/messages and /v1/responses, and streamed tool-call arguments on /v1/chat/completions) and no output guardrail in the chain uses buffer_full.Maximum bytes of model-generated content held back for inspection: assistant text, reasoning, and tool-call arguments. SSE and JSON framing is not counted. The raw bytes held are separately capped at 128 times this value. Crossing either cap applies on_buffer_exceeded. Default 262144.
on_buffer_exceededThe same buffering kindsfail_closed rejects when the buffer limit is exceeded and is the default. fail_open releases the content unscanned and records the bypass reason output_buffer_exceeded.

Provider credentials (api_key, access_key_secret, aws_credentials.secret_access_key, aws_credentials.session_token, aws_credentials.api_key) and custom-script secrets values are sensitive, so supply them as ${VAR}. See the guardrail guides for per-kind behavior.

The example combines a local input check with remote moderation. block-secrets rejects matching request text before an upstream call, while content-moderation uses the OpenAI Moderation API at the default both hook point for requests and responses.

resources.yaml
_format_version: "2"

guardrails:
# In-process keyword blocklist on the request side only.
- id: a9174a5c-c7b3-424a-a327-ee3d6b0848cf
name: block-secrets
kind: keyword
hook_point: input
patterns:
- kind: literal
value: internal-project-codename
- kind: regex
value: '\bAKIA[0-9A-Z]{16}\b'

# Remote moderation; blocks when a listed category reaches its threshold.
- id: 5d0ff04c-2955-4841-9a8c-1f3e29849f6b
name: content-moderation
kind: openai_moderation
api_key: ${OPENAI_API_KEY}
category_thresholds:
violence: 0.5

Guardrail Attachments​

An attachment binds one guardrail to the traffic it inspects. A guardrail with no attachment loads normally, is counted in the resource total, and inspects nothing — the gateway logs a warning naming it once, and aisix validate lists it while still exiting 0. That is a valid state: an attachment names its target by ID, and the target may have been removed from the file.

FieldTypeRequiredDescription
guardrail_idstringyesid of the guardrail this attaches.
scope_typestringyesOne of env, model, mcp_server, api_key, team, passthrough_route.
scope_idstringconditionalid of the scoped resource. Omit it for scope_type: env; required for every other scope.
priorityintegeryesHigher wins when several attachments select the same guardrail for one request.
enabledbooleannoDefaults to true. A disabled attachment scopes nothing, but still counts as attaching the guardrail, so the guardrail is not reported as unattached.

scope_id is the id of the model, MCP server, caller API key, or passthrough route the attachment scopes to. scope_type: team has no collection in the file, so its scope_id is the team ID that a caller API key declares in team_id.

Update guardrails and guardrail_attachments, creating each top-level collection once if it is absent. Preserve unrelated entries and collections, and do not create a second copy of either top-level key.

resources.yaml (guardrail and attachments)
guardrails:
- id: 566ddb83-02a2-4a15-8579-ed5084b637cc
name: no-secrets
kind: keyword
patterns:
- kind: literal
value: supersecret-banned-token

guardrail_attachments:
# Inspects every request this gateway handles.
- id: ecb9567a-012e-41e6-9499-55e3c9bd57fd
guardrail_id: 566ddb83-02a2-4a15-8579-ed5084b637cc
scope_type: env
priority: 100
# …or only the traffic addressed to one model.
- id: c5ed55f1-7fc5-493c-a67a-8b3df68048b7
guardrail_id: 566ddb83-02a2-4a15-8579-ed5084b637cc
scope_type: model
scope_id: ccd6c189-04bb-44a9-bd0a-1545a04504e9
priority: 100

Both attachments above select the same guardrail, so a request to gpt-4o runs it once: the highest-priority match wins and duplicates are dropped.

MCP Servers​

An MCP server entry exposes tools to MCP clients as <name>__<tool>. It can connect to an upstream MCP server or generate tools from an inline OpenAPI document. In both cases, the gateway holds the upstream credential; it is never forwarded from or exposed to the calling client.

FieldTypeRequiredDescription
namestringyesServer name, and the namespace prefix for the server's tools. Must not contain the reserved separator __, and must not contain * — a registered server name is never a pattern. The former spelling display_name is not read: an entry that still uses it has no name and is rejected.
typeenumnomcp (default) connects to a real MCP server. openapi generates tools from an OpenAPI document and sends their calls as regular HTTP requests.
urlstringyesFor type: mcp, the upstream MCP endpoint. For type: openapi, the REST API base URL used for generated tool calls.
specobjectyes*Inline OpenAPI 3.x document, required for type: openapi and ignored for type: mcp. In a resources file, write the document as a nested YAML mapping.
transportenumnostreamable_http, the only supported transport for type: mcp and the default.
protocol_versionenumnoMCP protocol revision used for the upstream session, for type: mcp only. Omit it unless the server requires the stateless 2026-07-28 revision: the default initialize handshake negotiates the revision automatically and also works with 2026-07-28 servers that stay backward compatible. Quote the value so YAML keeps it a string.
auth_typeenumnoHow the gateway authenticates upstream. none is the default. bearer sends secret as Authorization: Bearer, and api_key sends secret as an API key header. oauth2 uses the client credentials grant and caches the token until shortly before expiry. oauth_delegate relays the caller's own Authorization when the caller sent its gateway key in x-aisix-api-key, and takes no credential fields. oauth2_token_exchange exchanges the caller's verified JWT at token_url; see Entra On-Behalf-Of Token Exchange. oauth2_authorization_code has each user sign in, for type: mcp only; see Interactive MCP Sign-In.
api_key_headerstringnoHeader used when type: openapi and auth_type: api_key. Default x-api-key. A real MCP server always uses x-api-key for API key authentication.
forward_client_headersarray of stringsnoInbound client headers relayed to this server, as exact names or single-* globs such as x-trace-*, matched case-insensitively. Empty (the default) forwards nothing. Applies to both type: mcp and type: openapi, so a REST API exposed as tools receives them on every tool call. A credential slot and traceparent / tracestate are relayed only when a pattern names them exactly. A relayed credential takes the slot auth_type would otherwise fill, never joining it, including the header api_key_header names — which a glob does reach whenever it is renamed to something outside that list. host, hop-by-hop headers, x-aisix-*, the body and negotiation headers the gateway re-serializes, set-cookie, anthropic-version, x-stainless-*, and the MCP session slots (mcp-session-id, mcp-protocol-version, last-event-id) are never relayed. See Upstream Request Headers.
secretstringnoThe bearer token, API key, or OAuth client secret, per auth_type. Required for bearer, api_key, oauth2, and oauth2_token_exchange. Supply it as ${VAR}.
client_idstringnoOAuth client identifier. Required with auth_type: oauth2 or oauth2_token_exchange. Optional with oauth2_authorization_code, where the gateway otherwise registers itself as a public client.
token_urlstringnoOAuth token endpoint where the gateway obtains the upstream access token. Required with auth_type: oauth2 or oauth2_token_exchange. Optional with oauth2_authorization_code, where it is otherwise discovered from the upstream.
authorization_urlstringnoOAuth authorization endpoint users are sent to, with auth_type: oauth2_authorization_code. Discovered from the upstream when omitted.
registration_urlstringnoOAuth dynamic client registration endpoint, with auth_type: oauth2_authorization_code and no client_id. Discovered from the upstream when omitted.
scopesarray of stringsnoOAuth scopes, joined with spaces into the token request. Optional with oauth2 and oauth2_authorization_code; at least one is required with oauth2_token_exchange.
token_exchange_profileenumnoExchange protocol for auth_type: oauth2_token_exchange, and required with it. entra_obo, the Microsoft Entra ID On-Behalf-Of flow, is the only value.
timeout_msintegernoDeadline per upstream operation (session setup, tool listing, tool calls). Minimum 1. Default: 30,000 ms.
enabledbooleannofalse removes the server's tools from listings and calls. Default true.

Caller access to tools is granted per key through api_keys[].mcp_access. See the MCP Gateway Overview for the caller connection flow.

This entry exposes a remote MCP server as the github tool namespace and authenticates upstream with a bearer token from the environment:

resources.yaml
_format_version: "2"

mcp_servers:
- id: 631940a7-bdb5-4d67-9ffd-74798b91df52
name: github
type: mcp
url: https://api.example.com/mcp
auth_type: bearer
secret: ${GITHUB_MCP_TOKEN}

OpenAPI-Backed Servers​

For type: openapi, supported HTTP operations become MCP tools. AISIX uses operationId as the tool name when present and otherwise derives a name from the HTTP method and path. The resources file carries the document directly under spec, as etcd stores it. The AISIX Cloud Admin API write fields spec_content and spec_url are not stored fields: the loader ignores them, and an entry without spec is rejected.

Here, the listItems operation becomes an MCP tool in the inventory namespace. Tool calls go to the configured REST API with the interpolated API key in X-Inventory-Key.

resources.yaml
_format_version: "2"

mcp_servers:
- id: 10d4985c-567a-4034-915d-a82ea8611ffd
name: inventory
type: openapi
url: https://inventory.example.com/api
auth_type: api_key
api_key_header: X-Inventory-Key
secret: ${INVENTORY_API_KEY}
spec:
openapi: 3.0.0
info:
title: Inventory API
version: 1.0.0
paths:
/items:
get:
operationId: listItems
responses:
"200":
description: Items returned successfully

A2A Agents​

An A2A agent entry registers an upstream agent that the gateway exposes to callers under /a2a/<name>, serving its agent card with URLs rewritten to the gateway. As with MCP servers, the upstream credential stays in the gateway.

FieldTypeRequiredDescription
namestringyesAgent name, and the caller-facing path segment. The former spelling display_name is not read: an entry that still uses it has no name and is rejected.
urlstringyesThe upstream agent's base URL.
protocol_versionenumnoA2A wire format: "1.0" (default) or "0.3". Quote the value so YAML keeps it a string.
auth_typeenumnonone (default), bearer, or api_key, with the same semantics as MCP servers.
secretstringnoThe upstream credential, per auth_type. Supply it as ${VAR}.
forward_client_headersarray of stringsnoInbound client headers relayed to this agent, as exact names or single-* globs such as x-trace-*, matched case-insensitively. Empty (the default) forwards nothing. Applies to the agent-card fetch at /a2a/<name>/.well-known/agent-card.json as well as to every JSON-RPC method served at /a2a/<name>, so the agent receives them on message/send, message/stream, and every task operation alike. A credential slot and traceparent / tracestate are relayed only when a pattern names them exactly. A relayed credential takes the slot auth_type would otherwise fill — authorization for bearer, x-api-key for api_key — never joining it. host, hop-by-hop headers, x-aisix-*, the body and negotiation headers the gateway re-serializes, set-cookie, anthropic-version, x-stainless-*, and a2a-version are never relayed. See Upstream Request Headers.
timeout_msintegernoDeadline per upstream operation, including agent-card fetches. On a streaming method (message/stream, tasks/resubscribe) it bounds opening the stream, not its duration, so a long-running task is not cut off. Minimum 1. Default: 30,000 ms.
enabledbooleannofalse stops serving the agent. Default true.

Caller access is granted per key through api_keys[].allowed_agents. See Set Up Agent Gateway for a complete caller connection flow.

This entry publishes an upstream agent at /a2a/invoice-processor and supplies its bearer token from the environment:

resources.yaml
_format_version: "2"

a2a_agents:
- id: 56671479-1687-4b88-9abc-c3a1bacdb3cb
name: invoice-processor
url: https://agents.example.com/a2a
auth_type: bearer
secret: ${INVOICE_AGENT_TOKEN}

Passthrough Routes​

A passthrough route relays matched HTTP traffic to a provider endpoint without AISIX normalizing the body, while still applying caller authentication, route grants, guardrails, rate limits, and telemetry. The body envelope (chat, completions, Responses API, or opaque) is detected per request; there is nothing to configure. SSE responses relay incrementally unless an output guardrail holds frames for inspection. Passthrough Routes explains the matching, authentication, credential, and detection model; this table covers the file form.

The following partial block illustrates one passthrough route. It assumes that the openai-prod provider key is already defined in the complete resources file:

resources.yaml (passthrough route)
passthrough_routes:
- id: 14a51cc3-9204-48ac-af39-e005bd27fa71
name: openai-raw
path_prefix: /passthrough/openai
target_url: https://api.openai.com
provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95
FieldTypeRequiredDescription
namestringyesRoute name. The former spelling display_name is not read: an entry that still uses it has no name and is rejected. Caller keys grant access to this name through allowed_routes.
path_prefixstringconditionalURL path prefix the route claims, such as /passthrough/openai. At least one of path_prefix and hosts is required. A route without hosts must not claim a reserved gateway namespace (/v1, /mcp, /a2a, /admin, /livez, /readyz, /metrics) — the gateway's own endpoints would shadow it; a route with hosts may, because host-matched requests are dispatched ahead of those endpoints. On a target_url route the prefix is a mount point and is stripped before forwarding; on a preserve_host route it only selects which requests the route claims, and the complete path is relayed.
hostsarray of stringsconditionalInbound host values the route claims, matched before path routing. The inbound host is the request URI authority when present, as in an absolute-form request from another proxy, and otherwise the Host header; a port is ignored. Entries are exact hosts or a single leading *. wildcard that keeps at least two literal labels (*.example.com, never *.com).
target_urlstringconditionalUpstream base URL the matched request is relayed to. Exactly one of target_url and preserve_host: true is required.
preserve_hostbooleanconditionalDerive the target as https://<matched host> instead of a fixed target_url. Requires hosts. Default false.
auth_modeenumnoHow the gateway authenticates the caller: gateway_key (standard Authorization caller key), header_key (caller key read from auth_header_name, leaving Authorization untouched), or anonymous (no credential; the route runs as anonymous_key_id). Default gateway_key.
auth_header_namestringconditionalLowercase header carrying the gateway key. Required for header_key, rejected on any other auth_mode. authorization, proxy-authorization, cookie, set-cookie, and x-api-key are rejected. Stripped before forwarding unless forward_client_headers names it in full; a glob does not reach it.
anonymous_key_idstringconditionalid of the caller API key whose identity, limits, and attribution anonymous traffic runs under. Required for anonymous mode (together with source_cidrs), rejected on any other.
source_cidrsarray of stringsconditionalClient CIDR allowlist. Required for anonymous mode; optional otherwise. A source outside the list is rejected with 403 and error.code: ip_restricted.
credential_modeenumnoUpstream credential handling: inject (remove every credential slot and send the referenced provider key's credential; requires provider_key_id) or forward_client (relay the caller's upstream credential after authentication-mode and fixed header stripping; provider_key_id is forbidden). In forward_client mode with gateway_key, AISIX strips authorization and x-api-key unless the gateway key arrived in x-aisix-api-key; use that header, header_key, or anonymous when the upstream credential uses either slot. Default inject.
provider_key_idstringconditionalid of the provider key whose credential is injected upstream. Required for inject, forbidden for forward_client.
identity_headerstringnoLowercase request header whose value is recorded as the usage event's client_identity and stripped before forwarding, unless forward_client_headers names it in full; a glob does not reach it. authorization, proxy-authorization, cookie, set-cookie, and x-api-key are rejected.
forward_client_headersarray of stringsnoInbound client headers relayed to the upstream even when this route would otherwise strip them, as exact names or single-* globs such as x-trace-*, matched case-insensitively. Empty (the default) overrides no stripping. A route relays the caller's headers by default, so this field only matters for the ones it removes: every credential slot and the provider key's strip_headers under credential_mode: inject, and the slot the gateway consumed to authenticate the caller under forward_client. On an inject route, naming the slot the route injects into (x-api-key for an Anthropic provider key, authorization for any other) puts the caller's own credential on the upstream request in place of the injected one, and naming any other slot sends it beside the injected one. A credential slot the route removes and traceparent / tracestate come back only when a pattern names them exactly, and so do this route's own auth_header_name and identity_header. For every other name the route strips a glob is enough, including a strip_headers entry — though three of that list's four defaults are credential slots needing their own entry, leaving set-cookie the only default a glob restores. host, content-length, hop-by-hop headers, and x-aisix-* are stripped whatever the patterns say. See Upstream Request Headers.
timeout_msintegernoUpstream timeout in milliseconds for the response-header phase and non-streaming body reads. For SSE, it bounds the wait for the first raw upstream body chunk and each gap between raw chunks, not the total lifetime of a healthy relay or the time required to assemble a complete SSE frame. When omitted, upstream.stream_timeout_ms applies and falls back to upstream.timeout_ms.
enabledbooleannoDisable the route without deleting it; a disabled route stops matching. Default true.

Cache Policies​

A cache policy caches eligible non-streaming chat-completions responses for matching requests. Other endpoint families and streaming responses are not cached. The proxy uses the first enabled policy that matches each request. See Response Caching for key matching and verification.

FieldTypeRequiredDescription
namestringyesPolicy name. 1–120 characters. Surfaces in metric labels and cache headers.
enabledbooleannofalse stages the policy without applying it. Default true.
backendenumnomemory (default) or redis. The redis backend requires the gateway's static cache.redis configuration; without it, matching requests are not cached.
ttl_secondsintegernoEntry time-to-live, 1–604,800 seconds (7 days). Default 3600.
applies_tostringnoEligibility selector: all (default), model:<alias> (requests targeting that model alias, compared before router fan-out), or api_key:<id> (requests authenticated by the caller API key with that resource ID).
scopeenumnoSharing boundary for cached entries, applied to both matching layers: api_key (default — entries are private to the caller API key that stored them) or env (every caller in the environment shares the entries).
purge_generationintegernoInvalidation counter, default 0. Increasing it invalidates every entry the policy stored under earlier values, across both matching layers and every gateway instance.
semanticobjectnoEnables embedding-similarity matching on top of the exact layer. See the sub-table below.

The control plane manages purge_generation through the purge operation. In a resources file, keep it monotonically increasing and carry the current value through every update. Lowering or omitting it can make older exact-cache entries reachable until their TTL expires.

semantic fields:

FieldTypeRequiredDescription
embedding_modelstringyesdisplay_name of a model entry in this file that carries an embedding block. Its dimensions value fixes the vector size for the policy's entries.
thresholdnumberyesMinimum cosine similarity, 0–1, for a stored entry to be served. Higher is stricter; below ~0.9 the wrong-answer risk rises sharply.
max_entriesintegernoEntry cap on the memory backend, 1–10,000, default 1000; oldest evicted first. Shared backends bound growth by TTL and ignore this.
embedding_timeout_msintegernoPer-call embedding deadline. On timeout the request proceeds upstream uncached. 0 or absent disables the dedicated deadline.

Only requests whose messages are entirely text participate in similarity matching. On backend: redis, the semantic layer requires Redis 8+ (vector search), RESP2, and single or sentinel mode. Without these requirements, the policy serves exact matches only and logs a warning. See Semantic Caching.

applies_to values are matched at request time, not resolved at load. For api_key, use the caller API key entry's id. A model alias that matches nothing simply never caches. A semantic.embedding_model that names no embedding model disables the semantic layer with a warning while exact caching continues.

caution

An unrecognized applies_to prefix is treated as all. A mistyped prefix therefore broadens caching instead of disabling the policy.

The following complete example caches non-streaming responses for the gpt-4o alias in memory for 10 minutes:

resources.yaml
_format_version: "2"

provider_keys:
- id: 83eba07c-0ad3-4b81-b760-247f2d978e95
display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}

models:
- id: ccd6c189-04bb-44a9-bd0a-1545a04504e9
display_name: gpt-4o
provider: openai
model_name: gpt-4o-2024-11-20
provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95

cache_policies:
- id: 8ac3306c-39bd-4462-b05f-705757b7dc58
name: gpt-4o-cache
backend: memory
ttl_seconds: 600
applies_to: "model:gpt-4o"

Observability Exporters​

An observability exporter delivers request telemetry to an external system. The kind field selects the backend, and that kind's fields sit directly on the entry. A field the selected kind does not define, including a plaintext credential field, is ignored and reported as partially compatible.

Every exporter kind accepts these shared fields:

FieldTypeRequiredDescription
namestringyesExporter name. 1–120 characters.
kindenumyesotlp_http, aliyun_sls, datadog, or object_store.
enabledbooleannoDisabled exporters stay configured but receive no telemetry. Default true.

The selected kind then adds its backend-specific fields:

kindRequired fieldsOptional fields
otlp_httpendpoint: full OTLP/HTTP traces URL including the receiver path, such as https://api.honeycomb.io/v1/traces. Use https:// or http:// with any host.headers (static headers per export request; put API keys in ${VAR} values), sample_rate (0.0–1.0; when absent, no emitted request trace is sampled out), content_mode, content_max_bytes.
aliyun_slsendpoint (regional *.aliyuncs.com host, no scheme), project, logstore, credential_refcontent_mode, content_max_bytes.
datadogsite (a known Datadog site such as datadoghq.com or datadoghq.eu), service, credential_refddsource (default aisix-ai-gateway), tags (rendered into ddtags), content_mode, content_max_bytes.
object_storeprovider (s3, gcs, or azure_blob), bucket, prefixregion (S3 signature scope), endpoint (backend override. For s3, an S3-compatible host such as MinIO, OSS, or R2. For gcs, a Cloud Storage XML API base URL, such as a private endpoint. It must serve the XML API that uploads use, and it takes precedence over gcs_base_url in the service-account JSON. For azure_blob, the Blob endpoint. https:// or http:// with any host. An exporter that combines it with auth_mode: cloud_identity loads but never uploads; the gateway reports a permanent delivery error for it), compression (gzip default, or none), auth_mode, credential_ref.

For otlp_http, aliyun_sls, and datadog, content_mode controls whether exported records omit prompt and response content (metadata_only, the default) or include it (full). content_max_bytes limits each captured content field in full mode to 1–1,048,576 bytes and defaults to 131,072. The object_store kind accepts neither field.

See Observability Exporters for delivery and content-capture behavior.

Remote credentials never live directly in an exporter resource. In the variable names below, <REF> is the exporter's credential_ref converted to uppercase with non-alphanumeric characters replaced by underscores—for example, datadog-prod becomes DATADOG_PROD.

ExporterCredential source
OTLP/HTTPPut API keys in interpolated headers values.
Alibaba Cloud SLSA credential reference named <REF> resolves SLS_CRED_<REF>_AK_ID and SLS_CRED_<REF>_AK_SECRET.
DatadogA credential reference named <REF> resolves DD_CRED_<REF>_API_KEY.
Object storeA credential reference named <REF> resolves the applicable OBJSTORE_CRED_<REF>_* variables. For S3 and GCS, cloud_identity uses the host's attached identity instead and does not require a credential reference.

The example compares all three credential-loading patterns: direct interpolation in an OTLP header, a named Datadog credential reference, and attached cloud identity for S3. The numbered notes below the YAML explain what the highlighted fields resolve to.

resources.yaml
_format_version: "2"

observability_exporters:
- id: 9bedbe6d-f6b9-4739-86c6-1e282caf0827
name: honeycomb-prod
kind: otlp_http
endpoint: https://api.honeycomb.io/v1/traces
headers:
x-honeycomb-team: ${HONEYCOMB_API_KEY}
sample_rate: 0.25

- id: a1846087-1975-4032-beaa-42411f9f35f1
name: datadog-prod
kind: datadog
site: datadoghq.com
credential_ref: datadog-prod
service: ai-gateway
tags: ["team:platform", "tier:prod"]

- id: acc4f701-ea4e-4bb3-8e06-86d916d6aad6
name: s3-events
kind: object_store
provider: s3
bucket: acme-aisix-events
prefix: ai-gateway
region: us-east-1
auth_mode: cloud_identity

❶ Standard resource interpolation supplies the Honeycomb API key from HONEYCOMB_API_KEY.

❷ The datadog-prod reference resolves the API key from DD_CRED_DATADOG_PROD_API_KEY; the credential never appears in the resources file.

❸ cloud_identity uses the host's attached cloud identity instead of static keys. This mode supports S3 and GCS exporters.

Rate Limit Policies​

A rate limit policy caps requests or tokens independently of the inline rate_limit blocks on models and caller API keys. Use the conditional form for policies that match several request attributes or split counters by dimension. Use the classic form for one subject and one fixed window. An entry must use exactly one form; an entry that mixes their fields is rejected. See Rate-Limit Policies for configuration paths and verification.

Conditional Form​

Use the conditional form for new policies. It matches requests with a condition tree, can split counters by dimensions, and supports request, token, and concurrency limits.

FieldTypeRequiredDescription
namestringyesPolicy name.
conditionsarraynoCondition nodes the request must satisfy; top-level nodes all apply (AND), and an empty or omitted list matches every request. Each node is either a condition (dimension, operator, optional negate, value) or a group (logic: and | or, optional negate, children). Nesting is capped at 3 levels and 16 conditions per policy. See the node fields below.
group_byarraynoBucket-split dimensions, any subset of team, member, api_key, model, provider. Each distinct value combination counts in an independent bucket with the same limits; empty or omitted means one shared bucket. A matched request lacking one of these dimensions is not subject to the policy.
limitsobjectyesAt least one of rps, rpm, rph, rpd, tpm, tpd, concurrency (all minimum 1), with the same shape and semantics as the inline rate_limit blocks, including the optional window_type.
actionenumnoOver-limit behavior; only reject (HTTP 429, the default) exists today.
schedulesarraynoRecurring suspension windows, identical to the classic form described below.

A conditions node can be a condition or a group. A condition accepts these fields:

FieldTypeRequiredDescription
dimensionenumyesteam, member, api_key, model, model_name, or provider. For api_key and model, values are entry IDs. team/member values match the caller API key's team_id/user_id verbatim. model and model_name match the dispatched model and — on a request routed through a model group, semantic router, or ensemble — the addressed parent as well, so a group's name selects every request routed through it and a member's name selects that member whether called directly or through a group; negate excludes both. provider matches the dispatched model's provider ID.
operatorenumyes==, ~= (not equal), in, ~~ (regex), or ~* (case-insensitive regex): lua-resty-expr tokens. The regex operators apply to model_name and provider only; patterns are capped at 256 characters and must compile.
negatebooleannoInverts the condition by applying the lua-resty-expr ! prefix. The combination of negate and in reads "not in." A request that does not carry the dimension matches neither the condition nor its negation.
valuestring or arrayyesOne string for the scalar operators; 1–64 strings for in.

For nested Boolean logic, use a group node:

FieldTypeRequiredDescription
logicenumyesand or or, which determines how children combine.
negatebooleannoInverts the group result (!AND / !OR).
childrenarrayyesNested nodes (conditions or further groups), at least one.

Classic Form​

The classic form remains fully supported for policies that apply to one subject.

FieldTypeRequiredDescription
scopeenumyesThe subject type: api_key, model, team (one shared bucket for the whole team), member, or team_member (the team's limit, but an independent counter per member).
scope_refstringyesThe specific subject. For scope: api_key or scope: model, use the target entry's id. For team, member, and team_member, use a team or user ID matched verbatim against the caller API key's team_id or user_id.
windowenumyessecond, minute, hour, or day.
max_requestsintegerno*Requests allowed per window, minimum 1. At least one of max_requests and max_tokens is required.
max_tokensintegerno*Tokens allowed per window, minimum 1. Token caps are enforced on minute and day windows; on second and hour windows the cap is accepted but not applied. Pair max_tokens with a minute or day window. See Manage Classic Single-Scope Policies.
schedulesarraynoRecurring wall-clock windows during which the policy is suspended (not enforced). Enforcement resumes automatically when a window closes, on the same counters. See the entry fields below and Suspend a Policy on a Schedule.

Each schedules entry selects its days either weekly (days_of_week) or by explicit dates (dates). Use exactly one of the two.

FieldTypeRequiredDescription
timezonestringyesIANA timezone the entry's wall-clock fields are interpreted in, for example Asia/Shanghai.
days_of_weekarrayno*Weekly recurrence: any of mon, tue, wed, thu, fri, sat, sun. Mutually exclusive with dates.
datesarrayno*Explicit YYYY-MM-DD dates in timezone, for holidays and other irregular days. Mutually exclusive with days_of_week.
start_timestringyesWindow start, HH:MM wall clock, inclusive.
end_timestringyesWindow end, HH:MM wall clock, exclusive; 24:00 means end of day. An end before the start crosses midnight, and the window belongs to its start day. Equal times are rejected by the AISIX Cloud Admin API and never match in the resources file. For example, days_of_week: [fri] with 22:00 to 09:00 covers Friday 22:00 through Saturday 09:00.

This example sets a 300-request-per-minute limit in both forms. The conditional policy creates a separate counter for each team across the gpt-4 model family; the classic policy creates one counter for the gpt-4o model alias.

resources.yaml
_format_version: "2"

provider_keys:
- id: 83eba07c-0ad3-4b81-b760-247f2d978e95
display_name: openai-prod
provider: openai
api_key: ${OPENAI_API_KEY}

models:
- id: ccd6c189-04bb-44a9-bd0a-1545a04504e9
display_name: gpt-4o
provider: openai
model_name: gpt-4o-2024-11-20
provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95

rate_limit_policies:
# Conditional form: the gpt-4 family shares one 300-RPM pool per team.
- id: c2897442-a00a-402c-825f-1bb16242e11b
name: gpt4-family-per-team
conditions:
- dimension: model_name
operator: "~~"
value: "^gpt-4"
group_by: [team]
limits:
rpm: 300
# Classic form (legacy): one subject per policy.
- id: 48af7a5c-79ff-4813-9a33-f4f5f5ace21f
name: cap-gpt4o
scope: model
scope_ref: ccd6c189-04bb-44a9-bd0a-1545a04504e9
window: minute
max_requests: 300
max_tokens: 100000