Apply the configuration, then run a demo script that sends a chat request, a streamed chat request, an embeddings request, and one request with an invalid API key.
The configuration creates an AI Model Provider with your Mistral credentials, a Key Auth AI Auth Strategy, an AI Consumer with a demo API key, and two AI Models on /mistral: one for chat (mistral-chat) and one for embeddings (mistral-embeddings). 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:
kongctl adopt ai-gateway "${KONNECT_CONTROL_PLANE_NAME}" \
--namespace "${KONNECT_CONTROL_PLANE_NAME}" \
--pat "${KONNECT_TOKEN}"
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'
The tab exports CHAT_MODEL, the upstream model for the mistral-chat alias, and EMBEDDINGS_MODEL, the upstream model for the mistral-embeddings alias, then applies the configuration. The Mistral credentials come from the prerequisites. Pick models that your Mistral plan includes (Mistral models).
Export the model env vars:
export CHAT_MODEL='mistral-small-latest'
export EMBEDDINGS_MODEL='mistral-embed'
Apply the Kong configuration:
cat <<'EOF' > kong-recipe.yaml
_defaults:
kongctl:
namespace: mistral-ai-with-kong-ai-gateway-recipe
ai_gateway_model_providers:
- ref: mistral-ai-with-kong-ai-gateway-provider
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: mistral-ai-with-kong-ai-gateway-provider
display_name: mistral-ai-with-kong-ai-gateway
type: mistral
config:
auth:
type: basic
headers:
- name: Authorization
value: !secret {source: !env 'MISTRAL_TOKEN'}
ai_gateway_auth_strategies:
- ref: mistral-ai-with-kong-ai-gateway-auth
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: mistral-ai-with-kong-ai-gateway-auth
display_name: mistral-ai-with-kong-ai-gateway key auth
type: key-auth
config:
key_names:
- apikey
key_in_header: true
key_in_query: false
key_in_body: false
hide_credentials: true
ai_gateway_consumers:
- ref: mistral-ai-with-kong-ai-gateway-consumer
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: rag-service
display_name: RAG service
type: api-key
credentials:
- ref: mistral-ai-with-kong-ai-gateway-consumer-key
name: rag-service-key
display_name: RAG service key
type: api-key
api_key: !secret {source: !env 'CONSUMER_API_KEY'}
ai_gateway_models:
- ref: mistral-ai-with-kong-ai-gateway-chat
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: mistral-ai-with-kong-ai-gateway-chat
display_name: mistral-ai-with-kong-ai-gateway (chat)
type: model
formats:
- type: openai
capabilities:
- generate
access:
auth_strategies:
- mistral-ai-with-kong-ai-gateway-auth
policies: []
config:
max_request_body_size: 10485760
response_streaming: allow
logging:
payloads: true
route:
paths:
- /mistral
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
model:
body_param: model
values:
- mistral-chat
targets:
- name: !env 'CHAT_MODEL'
provider: mistral-ai-with-kong-ai-gateway-provider
config:
format: openai
type: mistral
- ref: mistral-ai-with-kong-ai-gateway-embeddings
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: mistral-ai-with-kong-ai-gateway-embeddings
display_name: mistral-ai-with-kong-ai-gateway (embeddings)
type: model
formats:
- type: openai
capabilities:
- embeddings
access:
auth_strategies:
- mistral-ai-with-kong-ai-gateway-auth
policies: []
config:
max_request_body_size: 10485760
response_streaming: deny
logging:
payloads: true
route:
paths:
- /mistral
protocols:
- http
- https
methods:
- POST
- OPTIONS
strip_path: true
model:
body_param: model
values:
- mistral-embeddings
targets:
- name: !env 'EMBEDDINGS_MODEL'
provider: mistral-ai-with-kong-ai-gateway-provider
config:
format: openai
type: mistral
EOF
kongctl apply -f kong-recipe.yaml -o text --auto-approve --pat "${KONNECT_TOKEN}"
rm -f kong-recipe.yaml
The script sends a chat request with model: mistral-chat, the same request streamed, an embeddings request with model: mistral-embeddings, and one chat request with an invalid API key. In the output, look for the upstream model on each [ROUTED TO] line, the chunk count on the [STREAMED] 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
"""Mistral chat and embeddings through Kong AI Gateway.
Demonstrates that a single Kong endpoint fronts two Mistral capabilities while the
Mistral API key stays on the AI Model Provider, never in this script:
1. Chat completion via the `mistral-chat` alias, showing the upstream model Kong
resolved it to in the X-Kong-LLM-Model response header.
2. The same endpoint streamed, proving response_streaming: allow.
3. Embeddings via the `mistral-embeddings` alias on the same base path.
4. A call with an invalid key, proving the key-auth AI Auth Strategy rejects it
before any Mistral quota is spent.
Run:
export PROXY_URL="$KONNECT_PROXY_URL"
export CONSUMER_API_KEY='demo-api-key'
python demo.py
"""
import os
import sys
import time
from openai import APIStatusError, OpenAI
PROXY_URL = os.getenv("PROXY_URL", "http://localhost:8000")
API_KEY = os.getenv("CONSUMER_API_KEY", "demo-api-key")
# Client-facing aliases declared in each AI Model's config.route.model.values.
# Kong resolves these to the upstream Mistral model names.
CHAT_MODEL = "mistral-chat"
EMBEDDINGS_MODEL = "mistral-embeddings"
# 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.environ
def _c(code: str, s: str) -> str:
return f"\033[{code}m{s}\033[0m" if _USE_COLOR else s
def BOLD(s: str) -> str:
return _c("1", s)
def DIM(s: str) -> str:
return _c("2", s)
def GREEN(s: str) -> str:
return _c("32", s)
def CYAN(s: str) -> str:
return _c("36", s)
def RED(s: str) -> str:
return _c("31", s)
def make_client(api_key: str) -> OpenAI:
"""Kong reads the apikey header; the OpenAI SDK reserves api_key for Authorization."""
return OpenAI(
base_url=f"{PROXY_URL}/mistral",
api_key="unused",
default_headers={"apikey": api_key},
)
def section(title: str) -> None:
bar = "=" * 70
print(f"\n{bar}\n{BOLD(title)}\n{bar}")
def chat(client: OpenAI, prompt: str) -> None:
print(f"\n{BOLD('[REQUEST]')} model={CHAT_MODEL!r} prompt={prompt!r}")
start_ms = round(time.time() * 1000)
try:
raw = client.chat.completions.with_raw_response.create(
model=CHAT_MODEL,
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()
usage = completion.usage
upstream_model = raw.headers.get("x-kong-llm-model", ".")
upstream_latency = raw.headers.get("x-kong-upstream-latency", ".")
proxy_latency = raw.headers.get("x-kong-proxy-latency", ".")
print(f"[RESPONSE] {DIM(completion.choices[0].message.content)}")
print(f"{GREEN(BOLD('[ROUTED TO]'))} alias={CHAT_MODEL!r} -> upstream model={CYAN(BOLD(upstream_model))}")
print(f"[TOKENS] {DIM(f'prompt={usage.prompt_tokens} completion={usage.completion_tokens} total={usage.total_tokens}')}")
print(f"[LATENCY] {DIM(f'upstream={upstream_latency}ms proxy={proxy_latency}ms total={elapsed_ms}ms')}")
def stream(client: OpenAI, prompt: str) -> None:
print(f"\n{BOLD('[REQUEST]')} model={CHAT_MODEL!r} stream=True prompt={prompt!r}")
start_ms = round(time.time() * 1000)
first_token_ms = None
chunks = 0
text = []
for chunk in client.chat.completions.create(
model=CHAT_MODEL,
messages=[{"role": "user", "content": prompt}],
stream=True,
):
piece = chunk.choices[0].delta.content
if piece:
if first_token_ms is None:
first_token_ms = round(time.time() * 1000) - start_ms
chunks += 1
text.append(piece)
elapsed_ms = round(time.time() * 1000) - start_ms
print(f"[RESPONSE] {DIM(''.join(text))}")
print(f"{GREEN(BOLD('[STREAMED]'))} {chunks} chunks {DIM(f'first token={first_token_ms}ms total={elapsed_ms}ms')}")
def embed(client: OpenAI, texts) -> None:
print(f"\n{BOLD('[REQUEST]')} model={EMBEDDINGS_MODEL!r} inputs={len(texts)}")
start_ms = round(time.time() * 1000)
raw = client.embeddings.with_raw_response.create(model=EMBEDDINGS_MODEL, input=texts)
elapsed_ms = round(time.time() * 1000) - start_ms
result = raw.parse()
upstream_model = raw.headers.get("x-kong-llm-model", ".")
print(f"[RESPONSE] {DIM(f'{len(result.data)} vectors of {len(result.data[0].embedding)} dimensions')}")
print(f"{GREEN(BOLD('[ROUTED TO]'))} alias={EMBEDDINGS_MODEL!r} -> upstream model={CYAN(BOLD(upstream_model))}")
print(f"[TOKENS] {DIM(f'prompt={result.usage.prompt_tokens} total={result.usage.total_tokens}')}")
print(f"[LATENCY] {DIM(f'total={elapsed_ms}ms')}")
def main() -> None:
client = make_client(API_KEY)
section("1. Chat, in OpenAI format, answered by Mistral")
chat(client, "In one sentence, what is an API gateway?")
section("2. The same endpoint, streamed")
stream(client, "Name three French cities, comma separated.")
section("3. Embeddings, same credential, same base path")
embed(client, [
"Kong AI Gateway sits between clients and Mistral.",
"The AI Model Provider holds the Mistral API key.",
])
bad_key = "not-a-real-key"
section("4. Revoked or unknown key. Kong rejects before calling Mistral")
print(f"{DIM(f'attempting with apikey={bad_key!r}')}")
chat(make_client(bad_key), "In one sentence, what is an API gateway?")
section("Done.")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
EOF
Run it:
Example output:
======================================================================
1. Chat, in OpenAI format, answered by Mistral
======================================================================
[REQUEST] model='mistral-chat' prompt='In one sentence, what is an API gateway?'
[RESPONSE] An **API gateway** is a server that acts as an intermediary between clients and backend services, routing requests, aggregating responses, and enforcing policies like authentication, rate limiting, and load balancing.
[ROUTED TO] alias='mistral-chat' -> upstream model=mistral/mistral-small-latest
[TOKENS] prompt=25 completion=41 total=66
[LATENCY] upstream=881ms proxy=6ms total=1171ms
======================================================================
2. The same endpoint, streamed
======================================================================
[REQUEST] model='mistral-chat' stream=True prompt='Name three French cities, comma separated.'
[RESPONSE] Paris, Lyon, Marseille
[STREAMED] 3 chunks first token=395ms total=424ms
======================================================================
3. Embeddings, same credential, same base path
======================================================================
[REQUEST] model='mistral-embeddings' inputs=2
[RESPONSE] 2 vectors of 1024 dimensions
[ROUTED TO] alias='mistral-embeddings' -> upstream model=mistral/mistral-embed
[TOKENS] prompt=27 total=27
[LATENCY] total=1167ms
======================================================================
4. Revoked or unknown key. Kong rejects before calling Mistral
======================================================================
attempting with apikey='not-a-real-key'
[REQUEST] model='mistral-chat' prompt='In one sentence, what is an API gateway?'
[BLOCKED] 401 Error code: 401 - Unauthorized (6ms)
======================================================================
Done.
======================================================================
The output confirms the following:
|
Behavior
|
Evidence
|
|
Alias routing for chat
|
The [ROUTED TO] line shows mistral/mistral-small-latest for mistral-chat, from the X-Kong-LLM-Model header. The client sent only the alias.
|
|
Streaming
|
The [STREAMED] line shows several chunks for the same alias on the same path, because the chat AI Model allows streamed responses.
|
|
Embeddings on the same path
|
The embeddings request used the same base URL and key. The [ROUTED TO] line shows mistral/mistral-embed, and the response has 1024-dimension vectors.
|
|
Authentication before any upstream call
|
The invalid key gets 401 in a few milliseconds, far less than the upstream latency of the chat request. Kong never contacted Mistral.
|
|
Mistral key stays in Kong
|
The script only held the AI Consumer key. The AI Model Provider added the Mistral key to each upstream request.
|
To review the created entities, and per-consumer usage, open the mistral-ai-with-kong-ai-gateway-recipe AI Gateway in Konnect. For traffic across all your AI Gateways, use the Observability menu.