- Resources
Cookbooks
Use Mistral with Kong AI Gateway
Use Mistral with Kong AI Gateway
Access Mistral models through Kong AI Gateway using the Mistral Python SDK.
An AI gateway sits between your applications and the model providers they call. Applications send their requests to the gateway instead of to the provider, and the gateway forwards them. Because all model traffic passes through one place, the gateway can hold the provider API keys, record token usage, and apply policies such as rate limits without changes to application code.
Kong AI Gateway is an AI gateway from Kong, which also makes Kong Gateway for API traffic. You configure it in Kong Konnect, Kong's hosted control plane. Data plane nodes that you run, for example in Docker on your machine, handle the requests. Mistral is one of the model providers it supports, for chat completions and embeddings.
In this cookbook, you add Mistral to an AI Gateway as a provider and a model with kongctl. Then you point the Mistral Python SDK at the gateway's data plane and send chat requests, with and without streaming. Kong adds your Mistral API key to each request, so your client code doesn't hold it.
Your app (Mistral SDK) ==> Kong data plane ==> Mistral API
^
| configuration
Kong Konnect
Prerequisites
To complete this cookbook, you will need:
- Python 3.10 or later
- A Mistral account and API key
- A Kong Konnect account with an AI Gateway and a running data plane. The quickstart script in the prerequisites of Kong's AI Gateway getting started guide creates both and runs the data plane in Docker on your machine.
- kongctl, Kong's command-line tool for Konnect, logged in with kongctl login
Environment setup
This cookbook was tested with Kong AI Gateway 2.3, kongctl 1.15, and mistralai 3.7.0.
Install
Install the Mistral Python SDK:
%pip install "mistralai==3.7.0" --quiet
Required environment variables
To complete this cookbook, you'll need a Mistral API key. In Studio, navigate to the API keys section and create a new API key.
You'll also need two values from your AI Gateway:
- AI_GATEWAY_ID: the ID of your AI Gateway. The quickstart script prints it, and kongctl get ai-gateways lists it.
- KONNECT_PROXY_URL: the URL of your data plane. The quickstart data plane listens on http://localhost:8000, which the next cell uses if the variable isn't set.
Provide these values in one of two ways:
1.
Set them as environment variables before you start the notebook:
MISTRAL_API_KEY=your-mistral-api-key AI_GATEWAY_ID=your-ai-gateway-id KONNECT_PROXY_URL=http://localhost:80002.
Leave them unset and enter them when the next cell prompts you.
import getpass
import os
if not os.environ.get("MISTRAL_API_KEY"):
os.environ["MISTRAL_API_KEY"] = getpass.getpass("Mistral API key: ")
if not os.environ.get("AI_GATEWAY_ID"):
os.environ["AI_GATEWAY_ID"] = input("AI Gateway ID: ")
if not os.environ.get("KONNECT_PROXY_URL"):
os.environ["KONNECT_PROXY_URL"] = "http://localhost:8000"
Check the AI Gateway
Confirm that kongctl can reach your AI Gateway and that a data plane node is connected to it:
!kongctl get ai-gateway nodes --gateway-id $AI_GATEWAY_ID
The output has one row per data plane node connected to the gateway, with its version and status. If kongctl prints No resources found., start your data plane before you continue.
1. Add Mistral to the AI Gateway
Two entities connect the AI Gateway to Mistral:
- An AI Model Provider of type mistral stores your Mistral API key. Kong adds the key to each request it sends to the Mistral API.
- An AI Model is what your application calls. It sets the route path, the capability, and the Mistral model that requests go to.
Write both to a kongctl configuration file:
%%writefile mistral-kong.yaml
ai_gateway_model_providers:
- ref: mistral
ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
name: mistral
display_name: Mistral
type: mistral
config:
auth:
type: basic
headers:
- name: Authorization
value: !secret {source: !env MISTRAL_AUTH_HEADER}
ai_gateway_models:
- ref: mistral-small-latest
ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
name: mistral-small-latest
display_name: Mistral Small
type: model
formats:
- type: openai
capabilities:
- generate
config:
route:
paths:
- /v1
targets:
- name: mistral-small-latest
provider: mistral
config:
type: mistral
format: openai
In this file:
- ai_gateway: !lookup {id: !env AI_GATEWAY_ID} adds both entities to your existing AI Gateway.
- !secret {source: !env MISTRAL_AUTH_HEADER} reads the value of the Authorization header from an environment variable. kongctl sends it to Konnect and never reads it back.
- capabilities: [generate] with the /v1 path serves the model at /v1/chat/completions, the same path the Mistral SDK calls on https://api.mistral.ai.
- Mistral's chat completions API follows the OpenAI request format, so the AI Model's formats and the target's format are both openai.
- targets[].name is the Mistral model that Kong calls, and the AI Model's name is the value your application sends as model. Using mistral-small-latest for both keeps requests the same as direct calls to Mistral.
kongctl reads AI_GATEWAY_ID and MISTRAL_AUTH_HEADER from the environment. Build the header value from your API key, then apply the file:
import time
os.environ["MISTRAL_AUTH_HEADER"] = f"Bearer {os.environ['MISTRAL_API_KEY']}"
!kongctl apply -f mistral-kong.yaml --auto-approve
# Give the data plane time to receive the new configuration from Konnect.
time.sleep(15)
kongctl creates the provider before the model, because the model references it. The data plane gets the new configuration from Konnect a few seconds after kongctl finishes, which is what the sleep at the end of the cell waits for. If a request in the next step returns 404, the data plane doesn't have the configuration yet: wait a few seconds and run the cell again.
2. Send a chat request through Kong
Create a Mistral client that points at the data plane. server_url replaces the default https://api.mistral.ai, and the SDK adds /v1/chat/completions to it.
The client passes a placeholder instead of your API key. Kong replaces any Authorization header from the client with the key stored on the provider, so the request reaches Mistral with your key.
from mistralai.client import Mistral
client = Mistral(api_key="unused", server_url=os.environ["KONNECT_PROXY_URL"])
response = client.chat.complete(
model="mistral-small-latest",
messages=[{"role": "user", "content": "What is the best French cheese? Answer in one sentence."}],
)
print(response.choices[0].message.content)
print(f"Tokens: {response.usage.prompt_tokens} prompt, {response.usage.completion_tokens} completion")
The cell prints Mistral's answer and the token counts. The answer varies from run to run:
The best French cheese is often considered to be **Camembert de Normandie**, a creamy, rich, and aromatic soft cheese from Normandy.
Tokens: 27 prompt, 30 completion
The response is the same ChatCompletionResponse that a direct call returns. The model value has to match the name of an AI Model on the route. Otherwise, Kong returns a 500 error that mentions ai-gateway.upstream.local.
This AI Model accepts requests from any client that can reach the data plane. Before you expose the data plane to other machines, add an AI Auth Strategy so that each application has to send its own key.
3. Stream a response
Call chat.stream to receive the response in chunks. It uses the same route and model:
stream = client.chat.stream(
model="mistral-small-latest",
messages=[{"role": "user", "content": "Write a haiku about the Seine."}],
)
for chunk in stream:
print(chunk.data.choices[0].delta.content or "", end="")
The answer prints as the chunks arrive:
Silver Seine flows,
Paris whispers on its banks,
Moonlight on the waves.
Clean up
Delete the AI Model, then the AI Model Provider, and list the models that remain on your AI Gateway. The last command prints No resources found. once both are gone:
!kongctl api delete /v1/ai-gateways/$AI_GATEWAY_ID/models/mistral-small-latest
!kongctl api delete /v1/ai-gateways/$AI_GATEWAY_ID/model-providers/mistral
!kongctl get ai-gateway models --gateway-id $AI_GATEWAY_ID
If you created the AI Gateway and data plane with the quickstart script only for this cookbook, run the script with -d to remove both. KONNECT_TOKEN is the Konnect personal access token you used to create them:
curl -Ls https://get.konghq.com/ai | bash -s -- -d -k $KONNECT_TOKEN
Summary
In this cookbook, you sent chat requests to Mistral models through Kong AI Gateway with the Mistral Python SDK, after adding Mistral to the gateway with kongctl. The chat.complete and chat.stream calls are the same as direct calls to Mistral: only the client's server_url and API key change.
What you built:
- An AI Model Provider that stores your Mistral API key in Kong Konnect
- An AI Model that serves mistral-small-latest at /v1/chat/completions on your data plane
- A Mistral client that sends chat requests, with and without streaming, through the data plane
Mistral features used:
- Chat Completions API
- Mistral Python SDK
Other services:
- Kong AI Gateway, configured in Kong Konnect
- kongctl
See Kong's Mistral provider reference for embeddings and the other options the provider supports.