Route OpenAI-format chat requests to any supported LLM provider through Kong AI Gateway, with AI Consumer authentication and per-request model selection. You’ll set up:
A /basic-llm-routing endpoint that accepts only requests with a valid AI Consumer API key
Two model aliases, fast and smart, that clients select with the model field
Provider credentials that stay in AI Gateway instead of in client code
This provisions an AI Gateway named basic-llm-routing-recipe, a local data plane connected to it, and prints export lines for the rest of the session vars, including AI_GATEWAY_ID. Paste those into your shell when prompted.
Azure binds each deployment to one model, and the deployment ID selects the upstream model (Azure OpenAI REST API reference). To route two aliases to two models, you need two deployments.
Deploy two models in the resource, for example gpt-4o-mini for the fast alias and gpt-4o for the smart alias.
Export your credentials. AZURE_DEPLOYMENT_ID_1 is the deployment for fast, and AZURE_DEPLOYMENT_ID_2 is the deployment for smart. Use the current API version from the Azure OpenAI REST API reference:
Most teams call LLM providers directly from application code, with a copy of the provider API key in each service, which causes the following problems:
Problem
Solution
Each service holds a copy of the provider API key. A leaked key affects every team that uses the provider, and rotating it needs coordinated redeploys.
The AI Model Provider keeps the provider credentials in Kong and adds them to each upstream request. Clients only hold an AI Consumer key.
Without an authentication layer in front of the provider, nothing attributes usage to an app or revokes access for one misbehaving app.
The Key Auth AI Auth Strategy maps each API key to an AI Consumer and rejects unknown keys with 401 before any upstream call.
Each provider has its own authentication (Authorization: Bearer, x-api-key, SigV4 signing, api-key) and its own request and response format, so switching providers means rewriting client code.
The AI Model accepts OpenAI-format requests. Kong translates each request to the provider’s native format and the response back.
Model IDs are hardcoded in application code, so swapping or upgrading a model needs coordinated redeploys.
Two AI Models answer to the aliases fast and smart on one path. You change the upstream model in Kong, and clients keep sending the same alias.
The configuration creates an AI Model Provider with your provider’s credentials, a Key Auth AI Auth Strategy, an AI Consumer with a demo API key, and two AI Models (fast and smart) that route to the AI Model Provider. A kongctl namespace scopes every resource, so you can remove this configuration without affecting anything else on the same AI Gateway. See the kongctl documentation for more on namespaces.
Adopt the quickstart AI Gateway into a kongctl namespace so that kongctl can manage it. Adoption adds the KONGCTL-namespace label to the AI Gateway:
Export the demo AI Consumer’s API key. The credential’s api_key field is write-only, so its value must come from an environment variable, even for a fixed demo key:
export CONSUMER_API_KEY='demo-api-key'
Copied!
Select your provider. Each tab exports CHAT_MODEL_1, the upstream model for the fast alias, and CHAT_MODEL_2, the upstream model for the smart alias, then applies the configuration. Provider credentials come from the prerequisites.
Kong records these model names in the X-Kong-LLM-Model header, but the deployment IDs from the AI Credentials prerequisite select the upstream model. Set each name to the model in the matching deployment:
The script sends the same prompt with model: fast and with model: smart, then sends one request with an invalid API key. In the output, look for the upstream model on each [ROUTED TO] line and the 401 for the invalid key.
The demo passes the API key in default_headers because the OpenAI SDK always sends api_key as an Authorization: Bearer header. To let clients use api_key directly, add a global Pre-Function Policy (global: true) that copies the Bearer token to the apikey header. A global Pre-Function Policy runs before authentication, while one attached to the AI Model runs after it.
Create the demo script:
cat <<'EOF' > demo.py"""Basic LLM routing demo for Kong AI Gateway.Shows three things: 1. Two requests with the same prompt and different model aliases (fast, smart) reach different upstream models. The X-Kong-LLM-Model response header names the upstream model. 2. Kong authenticates each request with the apikey header. 3. A request with an invalid key gets 401 from Kong before any upstream call.Expected output: one [ROUTED TO] line for each alias, with a different upstreammodel on each, then a [BLOCKED] 401 line for the invalid key.Run: python demo.py (set PROXY_URL if the data plane is not at http://localhost:8000)."""import osimport sysimport timefrom openai import APIStatusError, OpenAIPROXY_URL = os.getenv("PROXY_URL", "http://localhost:8000")API_KEY = os.getenv("CONSUMER_API_KEY", "demo-api-key")PROMPT = "What is the capital of France?"# ANSI color codes. Disabled when stdout isn't a TTY or NO_COLOR is set._USE_COLOR = sys.stdout.isatty() and "NO_COLOR" not in os.environdef _c(code: str, s: str) -> str: return f"\033[{code}m{s}\033[0m" if _USE_COLOR else sBOLD = lambda s: _c("1", s)DIM = lambda s: _c("2", s)GREEN = lambda s: _c("32", s)CYAN = lambda s: _c("36", s)RED = lambda s: _c("31", s)def make_client(api_key: str) -> OpenAI: """Construct an OpenAI client that sends the given API key in the apikey header.""" return OpenAI( base_url=f"{PROXY_URL}/basic-llm-routing", api_key="unused", # required by the SDK; Kong reads the apikey header instead default_headers={"apikey": api_key}, )def call(client: OpenAI, model_alias: str) -> None: """Send one chat request and print the model Kong routed it to.""" print(f"\n{BOLD('[REQUEST]')} model={model_alias!r} prompt={PROMPT!r}") start_ms = round(time.time() * 1000) try: raw = client.chat.completions.with_raw_response.create( model=model_alias, messages=[{"role": "user", "content": PROMPT}], ) except APIStatusError as e: elapsed_ms = round(time.time() * 1000) - start_ms print(f"{RED(BOLD('[BLOCKED]'))} {RED(BOLD(str(e.status_code)))} {e.message} ({elapsed_ms}ms)") return elapsed_ms = round(time.time() * 1000) - start_ms completion = raw.parse() upstream_latency = raw.headers.get("x-kong-upstream-latency", ".") proxy_latency = raw.headers.get("x-kong-proxy-latency", ".") upstream_model = raw.headers.get("x-kong-llm-model", ".") answer = completion.choices[0].message.content print(f"[RESPONSE] {DIM(answer)}") print(f"{GREEN(BOLD('[ROUTED TO]'))} alias={model_alias!r} -> upstream model={CYAN(BOLD(upstream_model))}") print(f"[LATENCY] {DIM(f'upstream={upstream_latency}ms proxy={proxy_latency}ms total={elapsed_ms}ms')}")def section(title: str) -> None: bar = "=" * 70 print(f"\n{bar}\n{BOLD(title)}\n{bar}")def main() -> None: section("1. Same client, same prompt, two model aliases") client = make_client(API_KEY) call(client, "fast") call(client, "smart") section("2. Invalid API key. Kong rejects before reaching the upstream provider") bad_key = "not-a-real-key" print(f"\nTrying apikey={bad_key!r}") bad_client = make_client(bad_key) call(bad_client, "fast") section("Done.")if __name__ == "__main__": try: main() except KeyboardInterrupt: sys.exit(130)EOF
Copied!
Run it:
python demo.py
Copied!
Example output with the OpenAI tab’s models:
======================================================================1. Same client, same prompt, two model aliases======================================================================[REQUEST] model='fast' prompt='What is the capital of France?'[RESPONSE] The capital of France is Paris.[ROUTED TO] alias='fast' -> upstream model=openai/gpt-4o-mini[LATENCY] upstream=1311ms proxy=12ms total=1488ms[REQUEST] model='smart' prompt='What is the capital of France?'[RESPONSE] The capital of France is Paris.[ROUTED TO] alias='smart' -> upstream model=openai/gpt-4o[LATENCY] upstream=1071ms proxy=4ms total=1083ms======================================================================2. Invalid API key. Kong rejects before reaching the upstream provider======================================================================Trying apikey='not-a-real-key'[REQUEST] model='fast' prompt='What is the capital of France?'[BLOCKED] 401 Error code: 401 - Unauthorized (30ms)======================================================================Done.======================================================================
The [ROUTED TO] lines show openai/gpt-4o-mini for fast and openai/gpt-4o for smart, from the X-Kong-LLM-Model header. Both requests used the same path and the same body, except for the model field.
AI Consumer authentication
The requests with demo-api-key succeed. Kong matched the key to the basic-llm-routing-consumer AI Consumer.
Authentication before any upstream call
The invalid key gets 401 in about 30 ms, well below the upstream latency. Kong never contacted the provider.
Provider credentials stay in Kong
The client only held the AI Consumer key. The AI Model Provider added the provider credentials to each upstream request.
To review the created entities, and per-consumer usage, open the basic-llm-routing-recipe AI Gateway in Konnect. For traffic across all your AI Gateways, use the Observability menu.
Kong authenticates each request with the Key Auth AI Auth Strategy, selects the AI Model whose alias matches the model field, and sends the request upstream with the AI Model Provider’s credentials.
sequenceDiagram
participant C as Client
participant K as Kong AI Gateway
participant L as LLM Provider
C->>K: POST /basic-llm-routing (apikey header, model fast or smart)
activate K
K->>K: Key Auth AI Auth Strategy validates apikey (else 401)
K->>K: Select the AI Model that matches the model alias
K->>K: AI Model Provider adds provider credentials
K->>L: Request in the provider's native format
activate L
L-->>K: Native response
deactivate L
K-->>C: OpenAI-format response with X-Kong-LLM-Model
deactivate K
Authentication is an AI Auth Strategy, not an AI Policy. The Key Auth AI Auth Strategy reads the apikey header and matches the key against the AI Consumer credentials. On a match, Kong attaches the AI Consumer to the request. The AI Consumer is the identity that rate limits, ACLs, and analytics use. Both AI Models reference this AI Auth Strategy in access.auth_strategies, so one key works for both aliases.
The following settings configure the Key Auth AI Auth Strategy and the AI Consumer:
Setting
Purpose
key_names: [apikey]
Kong reads the key from the apikey header. Key Auth compares the whole header value, so it can’t read a key from an Authorization: Bearer header. The note in Run the demo shows the workaround.
hide_credentials: true
Kong removes the key before it forwards the request. The provider never sees the AI Consumer key.
credentials[].api_key
The AI Consumer’s key. The field is write-only, so it takes a !secret reference to CONSUMER_API_KEY, even for a demo value.
Kong adds X-Consumer-Username and related headers to the upstream request, not to the response. Per-consumer usage appears in Konnect analytics.
The AI Model Provider holds the credentials for one provider account. The two AI Models, basic-llm-routing-fast and basic-llm-routing-smart, share the /basic-llm-routing path. Each AI Model answers to one alias in the model field and has one target that uses the AI Model Provider. An AI Model accepts only one alias, so each alias needs its own AI Model.
The following settings configure the AI Model Provider and the AI Models:
Setting
Purpose
config.auth (AI Model Provider)
The provider credentials. Kong adds them to each upstream request. The fields depend on the provider tab.
formats: [{type: openai}]
The AI Model accepts OpenAI-format requests. Kong translates each request to the provider’s native format and the response back to OpenAI format.
capabilities: [generate]
The AI Model serves chat completions.
config.route.model
Kong reads the model field of the request body (body_param: model) and selects the AI Model whose values entry matches: fast or smart.
targets[].name
The upstream model, from CHAT_MODEL_1 or CHAT_MODEL_2. Change it and re-apply to swap models without changing clients.
targets[].config
The provider type and provider-specific target fields, for example Bedrock’s region or Azure’s deployment_id and api_version.
config.route.protocols: [http, https]
Accepts HTTP, so you can call the local data plane at http://localhost:8000.
config.route.strip_path: true
Kong removes /basic-llm-routing from the path before it forwards the request.
config.max_request_body_size: 10485760
Accepts request bodies up to 10 MB, instead of the 8 MB default, for long conversation contexts.
config.response_streaming: allow
Clients can request streamed responses, for interactive chat.
config.logging.payloads: true
Kong logs request and response payloads. The default is false.
Production credentials: This cookbook stores the AI Consumer’s API key and the provider credentials in environment variables for simplicity. In production, use AI Vaults to reference them from a secret manager, for example AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager, or Azure Key Vault.
You can change or extend this configuration in the following ways:
Variation
How
Swap models
Change CHAT_MODEL_1 or CHAT_MODEL_2 and re-apply. Clients keep sending fast and smart. Keep each alias in the same model class, because a large change in model behavior affects every client of that alias.
Switch providers
Select a different provider tab in Apply the Kong configuration and re-apply. Clients keep the same endpoint, apikey header, and aliases.
Allow anonymous requests
Set anonymous on the Key Auth AI Auth Strategy to an AI Consumer ID. Kong then sends requests without a valid key through that AI Consumer, with its own restricted policies, instead of rejecting them with 401. This suits public or free-tier endpoints. Run kongctl explain ai_gateway_auth_strategies --extended for all options.
Use a native provider format
Set formats to a provider’s native format (for example, anthropic) to pass requests through without translation. A native format works only with providers that accept it. See the AI Model reference for the supported formats.
Route by header, path, or load balancing
Route with config.route.headers, with one AI Model for each path, or across several targets on one AI Model with config.balancer. See the AI Model reference for the balancer algorithms.
Replace the Key Auth AI Auth Strategy with an OpenID Connect AI Auth Strategy and map JWT claims to AI Consumers. The AI Models and AI Model Provider don’t change. See the Claude Code SSO cookbook for an example with Okta.
The recipe’s kongctl namespace scoped all resources, so this teardown removes only this recipe’s configuration. Tear down the local data plane and delete the AI Gateway from Konnect: