Apply the configuration, connect OpenCode to Kong, then send requests with and without the AI Consumer key and run a prompt from OpenCode.
The configuration creates an AI Model Provider with the organization’s OpenAI key, a Key Auth AI Auth Strategy, an AI Consumer with an API key, a global Pre-Function Policy that copies the Bearer token into the apikey header, and an AI Model on /coding-agents. 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}"
Generate the AI Consumer’s API key. OpenCode sends this key to Kong instead of an OpenAI key. The credential’s api_key field is write-only, so its value must come from an environment variable:
export CONSUMER_API_KEY="coding-agents-demo-$(openssl rand -hex 8)"
Select your provider. The tab exports CHAT_MODEL, the only model name that the AI Model accepts and the model that Kong requests from OpenAI, then applies the configuration. Provider credentials come from the prerequisites.
Export the model env var:
export CHAT_MODEL='gpt-4o-mini'
Apply the Kong configuration:
cat <<'EOF' > kong-recipe.yaml
_defaults:
kongctl:
namespace: coding-agents-opencode-recipe
ai_gateway_model_providers:
- ref: coding-agents-openai-provider
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: coding-agents-openai-provider
display_name: coding-agents-openai
type: openai
config:
auth:
type: basic
headers:
- name: Authorization
value: !secret {source: !env 'OPENAI_TOKEN'}
ai_gateway_auth_strategies:
- ref: coding-agents-key-auth
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: coding-agents-key-auth
display_name: coding-agents key auth
type: key-auth
config:
key_names:
- apikey
hide_credentials: true
ai_gateway_consumers:
- ref: coding-agents-consumer
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: coding-agents-consumer
display_name: coding-agents demo consumer
type: api-key
credentials:
- ref: coding-agents-credential
name: coding-agents-credential
display_name: coding-agents demo API key
type: api-key
api_key: !secret {source: !env 'CONSUMER_API_KEY'}
ai_gateway_policies:
- ref: coding-agents-bearer-to-apikey
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: coding-agents-bearer-to-apikey
display_name: coding-agents Bearer to apikey
type: pre-function
global: true
config:
rewrite:
- |
local auth = kong.request.get_header("Authorization")
if auth and string.sub(string.lower(auth), 1, 7) == "bearer " then
ngx.req.set_header("apikey", string.sub(auth, 8))
end
ai_gateway_models:
- ref: coding-agents-openai
ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
name: coding-agents-openai
display_name: coding-agents (OpenAI-compatible)
type: model
formats:
- type: openai
capabilities:
- generate
access:
auth_strategies:
- coding-agents-key-auth
config:
max_request_body_size: 16777216
response_streaming: allow
logging:
payloads: true
route:
paths:
- /coding-agents
protocols:
- http
- https
methods:
- POST
- GET
- OPTIONS
strip_path: true
model:
body_param: model
values:
- !env 'CHAT_MODEL'
targets:
- name: !env 'CHAT_MODEL'
provider: coding-agents-openai-provider
config:
type: openai
EOF
kongctl apply -f kong-recipe.yaml -o text --auto-approve --pat "${KONNECT_TOKEN}"
rm -f kong-recipe.yaml
Create opencode.json in your project directory with a custom provider named kong that uses OpenCode’s OpenAI-compatible package (OpenCode custom providers):
cat <<'EOF' > opencode.json
{
"$schema": "https://opencode.ai/config.json",
"providers": {
"kong": {
"name": "Kong AI Gateway",
"package": "@opencode/ai/providers/openai-compatible",
"settings": {
"baseURL": "http://localhost:8000/coding-agents",
"apiKey": "{env:CONSUMER_API_KEY}"
},
"models": {
"chat": {
"modelID": "{env:CHAT_MODEL}",
"name": "Kong chat model",
"limit": { "context": 128000, "output": 16384 }
}
}
}
}
}
EOF
The file sets these values:
settings.baseURL sends OpenCode’s requests to the AI Model. OpenCode adds /chat/completions to it.
settings.apiKey is the AI Consumer key. OpenCode replaces {env:CONSUMER_API_KEY} with the value of the environment variable, so the key stays out of the file.
models.chat.modelID is the model name that OpenCode sends, from CHAT_MODEL. The AI Model accepts only that name. In OpenCode, you select the model as kong/chat.
limit sets the context and output token limits of the model. The values fit gpt-4o-mini. If you use another CHAT_MODEL, set its limits (OpenCode models).
OpenCode merges the project opencode.json with your global configuration, and the project file wins where they conflict, so your other providers stay available (OpenCode config).
OpenCode resolves {env:...} references in the environment of its background server (OpenCode providers). If the OpenCode background service already runs, stop it, so that the next OpenCode command starts it from the shell where CONSUMER_API_KEY and CHAT_MODEL are exported:
Call Chat Completions with the AI Consumer key as a Bearer token, the same way OpenCode does:
curl -sS -X POST "http://localhost:8000/coding-agents/chat/completions" \
-H "Authorization: Bearer ${CONSUMER_API_KEY}" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"${CHAT_MODEL}\",
\"messages\": [{\"role\": \"user\", \"content\": \"Reply with exactly: smoke-ok\"}]
}"
The response is an OpenAI Chat Completions object, with different IDs and token counts:
{
"id": "chatcmpl-...",
"object": "chat.completion",
"model": "gpt-4o-mini-2024-07-18",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "smoke-ok"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 14,
"completion_tokens": 3,
"total_tokens": 17
}
}
Send the same request without the Authorization header:
curl -sS -o /dev/null -w '%{http_code}\n' -X POST "http://localhost:8000/coding-agents/chat/completions" \
-H "Content-Type: application/json" \
-d "{\"model\": \"${CHAT_MODEL}\", \"messages\": [{\"role\": \"user\", \"content\": \"hi\"}]}"
Kong rejects the request before it reaches OpenAI:
Run a one-shot prompt with the kong/chat model from the project directory (OpenCode models):
opencode run --model kong/chat "Reply with exactly: opencode-ok"
OpenCode prints opencode-ok.
The requests and the OpenCode prompt confirm the following:
|
Behavior
|
Evidence
|
|
AI Consumer authentication with a Bearer token
|
The request with Authorization: Bearer and the AI Consumer key returns a completion. The Pre-Function Policy copied the token into apikey, and the Key Auth AI Auth Strategy matched it to coding-agents-consumer.
|
|
Authentication before any upstream call
|
The request without a key gets 401. Kong never contacted OpenAI.
|
|
OpenCode through Kong
|
opencode run with kong/chat prints opencode-ok. OpenCode sent the CHAT_MODEL name, which the AI Model accepts.
|
|
Provider credentials stay in Kong
|
OpenCode only held the AI Consumer key. The AI Model Provider added the OpenAI key to each upstream request.
|
To review the created entities, and per-consumer usage, open the coding-agents-opencode-recipe AI Gateway in Konnect. For traffic across all your AI Gateways, use the Observability menu.