Kong authenticates each request, checks the budget of the AI Consumer’s tier, compresses long prompts, and looks up the semantic cache. On a cache miss, the AI Model’s semantic balancer picks a target, and Kong forwards the request with the AI Model Provider’s credentials.
sequenceDiagram
participant C as Client
participant K as Kong AI Gateway
participant LC as LLMLingua Compressor
participant L as LLM Provider
C->>K: POST /llm-cost-optimization (apikey header, prompt)
activate K
K->>K: Key Auth AI Auth Strategy validates apikey (else 401)
K->>K: AI Rate Limiting Advanced Policy checks the tier budget (else 429)
K->>LC: AI Prompt Compressor Policy sends long prompts
activate LC
LC-->>K: Compressed prompt
deactivate LC
K->>K: AI Semantic Cache Policy searches Redis for a similar prompt
alt Cache hit
K-->>C: Cached response with X-Cache-Status Hit
else Cache miss
K->>K: Semantic balancer picks the cheap or the capable target
K->>L: Request with provider credentials
activate L
L-->>K: Response with token usage
deactivate L
K->>K: AI Rate Limiting Advanced Policy records the request cost
K-->>C: OpenAI-format response with X-Kong-LLM-Model
end
deactivate KThe AI Policies run in their built-in priority order: the AI Rate Limiting Advanced Policy (905), the AI Prompt Compressor Policy (769), then the AI Semantic Cache Policy (765). Thus Kong compresses a prompt before the cache lookup, also when the lookup is a hit. Compression keeps the meaning of the prompt, so similar prompts still match in the cache. This cookbook hasn’t confirmed against a live AI Gateway whether the semantic balancer picks the target before or after the cache lookup.
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. The recipe has two AI Consumers, llm-cost-optimization-standard-consumer and llm-cost-optimization-premium-consumer, so the key that the client sends selects the tier.
The following settings configure the Key Auth AI Auth Strategy and the AI Consumers:
|
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
|
Each AI Consumer’s key. The field is write-only, so it takes a !secret reference to STANDARD_API_KEY or PREMIUM_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.
Each AI Consumer Group, llm-cost-optimization-standard-tier and llm-cost-optimization-premium-tier, has one AI Consumer and lists its own AI Rate Limiting Advanced Policy in policies. The policy counts the dollar cost of each request, so a budget lasts longer on the cheap model than on the capable one. When a tier uses up its budget, Kong returns 429 Too Many Requests until the window allows requests again.
The following settings configure the AI Consumer Groups and the AI Rate Limiting Advanced Policies:
|
Setting
|
Purpose
|
ai_gateway_consumer_groups[].consumers
|
Adds each AI Consumer to its tier.
|
ai_gateway_consumer_groups[].policies
|
Attaches the tier’s AI Rate Limiting Advanced Policy to each request from the AI Consumer Group. This attachment hasn’t been confirmed against a live AI Gateway.
|
identifier: consumer-group
|
Counts usage for each AI Consumer Group, so the AI Consumers of a tier share one budget. The policy must be attached to an AI Consumer Group.
|
tokens_count_strategy: cost
|
Counts the cost of each request, from its token usage and the input_cost and output_cost of the target that served it. See Model cost management for the calculation. In a test on runtime 2.3.1, the policy deducted the request’s total tokens instead of its cost, so the $1 budget ran out after the first request. Check the deduction on your runtime before you rely on these budgets.
|
config.policies[].limits
|
The budget and the window size in seconds: 1 dollar in 3600 seconds for the standard tier, 5 for the premium tier. The demo uses small budgets so the change is visible.
|
window_type: sliding
|
Weighs the current window against the previous one, which smooths spending at window boundaries.
|
strategy: local
|
Keeps the counters in memory on each data plane node. For several nodes, use redis so that the nodes share the counters.
|
Kong deducts the cost of a request on the next request, so the request that uses up the budget always completes. Each response has X-AI-RateLimit-Limit-<window>-<label> and X-AI-RateLimit-Remaining-<window>-<label> headers. The label is policy-1 because the policy entry has no match conditions.
The AI Prompt Compressor Policy sends long prompts to the LLMLingua compressor service, which removes low-value tokens and keeps the meaning. The provider then bills only the compressed tokens. Short prompts pass through unchanged.
The following settings configure the AI Prompt Compressor Policy:
|
Setting
|
Purpose
|
compressor_url
|
The address of the compressor service, from COMPRESSOR_URL.
|
compressor_type: rate
|
Reads each range’s value as the share of the prompt to keep. target_token reads it as a token count instead.
|
compression_ranges
|
Compresses prompts of 100 tokens or more and keeps 60% of them (value: 0.6). Add ranges to compress long prompts more than medium ones.
|
stop_on_error: false
|
Forwards the uncompressed prompt when the compressor service fails, so an outage doesn’t block requests.
|
The AI Semantic Cache Policy embeds the latest message and searches Redis for a cached prompt within the distance threshold. On a hit, Kong returns the cached response with X-Cache-Status: Hit and doesn’t call the LLM. On a miss, Kong caches the new response. The cache doesn’t separate responses by AI Consumer, so a response cached for one tier can answer a similar prompt from the other tier.
The following settings configure the AI Semantic Cache Policy:
|
Setting
|
Purpose
|
embeddings.auth and embeddings.model
|
The embeddings credentials and model, from the AI Credentials prerequisite and EMBEDDINGS_MODEL. The policy calls the provider directly and doesn’t use the AI Model Provider, so each provider tab has its own auth fields.
|
vectordb.dimensions
|
The vector size of the embeddings model: 1536 for text-embedding-3-small, 1024 for amazon.titan-embed-text-v2:0. If you change EMBEDDINGS_MODEL, change this value.
|
vectordb.threshold: 0.3
|
The maximum cosine distance for a cache hit. Lower values are stricter. See Embedding-based similarity matching.
|
cache_ttl: 300
|
Keeps cached responses for 300 seconds.
|
message_countback: 1
|
Embeds only the latest message. Raise it when earlier messages change the expected answer.
|
stop_on_failure: false
|
Sends the request to the LLM when Redis or the embeddings call fails, instead of failing the request.
|
The AI Model Provider holds the provider credentials. The llm-cost-optimization-model AI Model has two targets and a semantic balancer. The balancer embeds the prompt and compares it with each target’s semantic_description. The capable target answers prompts close to its description, and the CATCHALL target answers everything else.
The following settings configure the AI Model Provider and the AI Model:
|
Setting
|
Purpose
|
config.auth (AI Model Provider)
|
The provider credentials. Kong adds them to each upstream request. The fields depend on the provider tab.
|
config.balancer.algorithm: semantic
|
Picks the target by meaning. The client’s model field doesn’t select the target. See the AI Model reference for the other balancer algorithms.
|
config.balancer.embeddings
|
The embeddings model for routing. It references the AI Model Provider by name and uses its credentials.
|
config.balancer.vectordb.ssl: false and port: 6379
|
The balancer connects to Redis without TLS on port 6379. The balancer’s Redis connection uses TLS by default, which a local Redis Stack doesn’t accept, so the balancer would never start and every request would fail with 500.
|
config.balancer.vectordb.threshold
|
The maximum cosine distance between a prompt and a target description: 0.75 for text-embedding-3-small, 0.85 for amazon.titan-embed-text-v2:0. Retune it when you change the embeddings model.
|
config.route.model
|
The AI Model answers to the alias auto in the body’s model field (body_param: model). The demo sends auto, and the semantic balancer chooses the target. Without a selector, an AI Model accepts only its own name as model.
|
targets[].semantic_description
|
CATCHALL on the cheap target makes it the fallback. The capable target’s description is “Software architecture, system design, and complex code generation.” A short, specific phrase routes more precisely than a long one.
|
targets[].config.input_cost and output_cost
|
Prices per 1 million tokens, which the AI Rate Limiting Advanced Policy uses. The values are examples for each tab’s default models. Replace them with the current OpenAI or Amazon Bedrock prices.
|
policies
|
The AI Semantic Cache and AI Prompt Compressor Policies. The AI Rate Limiting Advanced Policies attach to the AI Consumer Groups instead.
|
config.route.protocols: [http, https]
|
Accepts HTTP, so you can call the local data plane at http://localhost:8000.
|
config.max_request_body_size: 10485760
|
Accepts request bodies up to 10 MB, instead of the 8 MB default, for long prompts.
|
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 Consumers’ API keys 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.
Kong adds the following response headers:
|
Header
|
Description
|
X-Kong-LLM-Model
|
The upstream model that served the request, with the provider name as a prefix, for example openai/gpt-4o-mini. The demo output shows no model on a cache hit.
|
X-Cache-Status
|
Hit when the AI Semantic Cache Policy returned a cached response, Miss when Kong called the LLM.
|
X-AI-RateLimit-Limit-<window>-<label>
|
The tier’s budget for a window of <window> seconds.
|
X-AI-RateLimit-Remaining-<window>-<label>
|
The budget left in the window, after the cost of earlier requests.
|
X-Kong-Upstream-Latency
|
Time in milliseconds that Kong waited for the provider to respond.
|
X-Kong-Proxy-Latency
|
Time in milliseconds that Kong spent processing the request, including the compression and embeddings calls.
|