AI Tool Integration: OpenCode

Minimum Version
AI Gateway - 2.0
Incompatible with
on-prem

Overview

Put Kong AI Gateway between OpenCode and OpenAI, so that the organization’s OpenAI key stays in Kong and each developer authenticates with their own key that you can revoke. You’ll set up:

  • An OpenCode custom provider that sends an AI Consumer key to Kong
  • A global Pre-Function Policy that lets the Key Auth AI Auth Strategy read the key from a Bearer token
  • An AI Model that accepts one model name, so the team uses the model that the organization chose

Prerequisites

This tutorial uses Kong Konnect. The AI Gateway quickstart script provisions a recipe-scoped AI Gateway and local data plane.

  1. Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
  2. Export your token. You reuse the same token later for kongctl commands:

    export KONNECT_TOKEN='YOUR_KONNECT_PAT'
  3. Set the recipe-scoped AI Gateway name and run the quickstart script:

    export KONNECT_CONTROL_PLANE_NAME='coding-agents-opencode-recipe'
    curl -Ls https://get.konghq.com/ai | bash -s -- -k $KONNECT_TOKEN

    This provisions an AI Gateway named coding-agents-opencode-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.

This tutorial uses kongctl to manage AI Gateway configuration.

  1. Install kongctl from the kongctl documentation.
  2. Verify it’s installed:

    kongctl version

This tutorial uses OpenCode 2, a terminal coding agent.

  1. Install OpenCode with the install script, or with another method from the OpenCode documentation:

    curl -fsSL https://opencode.ai/v2/install | bash

Pick the provider you want to route to and export its credentials. The provider’s tab in Apply the Kong configuration reads these variables.

What this cookbook solves

Most teams let each developer connect OpenCode directly to a provider with a shared API key, which causes the following problems:

Problem

Solution

Each developer connects a provider in OpenCode with their own copy of the key (OpenCode providers), so each laptop holds a credential that bills the organization’s account, and a leaked key works anywhere. The AI Model Provider keeps the OpenAI key in Kong. Each developer holds only an AI Consumer key, and Kong sends the OpenAI key upstream.
With one shared key, the provider bill is one line item. Nobody can tell which developer sent which request, and removing one developer’s access means rotating the key for everyone. The Key Auth AI Auth Strategy authenticates each developer as an AI Consumer. Kong rejects a missing or unknown key with 401 before any upstream call, and deleting one credential removes one developer’s access.
OpenAI-compatible clients send the API key as Authorization: Bearer <key>, so a gateway in front of them has to accept that header without client changes. A global Pre-Function Policy copies the Bearer token into the apikey header before authentication, so OpenCode needs only a base URL and an API key.
The model choice lives in each developer’s config files, so the team has no single place to pin the model or to add limits. The AI Model accepts one model name, CHAT_MODEL, and is the one place to add AI Policies for each OpenCode request.

Try it out

Apply the configuration, connect OpenCode to Kong, then send requests with and without the AI Consumer key and run a prompt from OpenCode.

Apply the Kong configuration

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.

Connect OpenCode to Kong

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:

opencode service stop

Send a request through the AI Model

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 a request without the AI Consumer key

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:

401

Run a prompt from OpenCode

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.

Check the results

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.

How it works

OpenCode sends each request to Kong with the AI Consumer key in the Authorization header. Kong copies the Bearer token into the apikey header, authenticates the AI Consumer, selects the AI Model that matches the model name, and forwards the request to OpenAI with the organization’s key.

sequenceDiagram
    participant OC as OpenCode
    participant K as Kong AI Gateway
    participant O as OpenAI

    OC->>K: POST /coding-agents/chat/completions (Authorization: Bearer AI Consumer key)
    activate K
    K->>K: Global Pre-Function Policy copies the Bearer token into apikey
    K->>K: Key Auth AI Auth Strategy validates apikey (else 401)
    K->>K: Select the AI Model whose model value matches the request
    K->>K: AI Model Provider adds the organization's OpenAI key
    K->>O: Chat Completions request
    activate O
    O-->>K: Response, streamed when requested
    deactivate O
    K-->>OC: OpenAI-format response
    deactivate K

Pre-Function Policy

The Key Auth AI Auth Strategy reads the AI Consumer key from the apikey header and compares the whole header value, so it can’t read a key from Authorization: Bearer <key>. The Pre-Function Policy runs Lua code that copies the token into apikey before authentication. It’s global, because a policy attached to an AI Model runs only after authentication succeeds, while a global policy with a higher priority than the AI Auth Strategy runs before it (AI Policy scopes and authentication).

The following settings configure the Pre-Function Policy:

Setting

Purpose

global: true Applies the policy to all traffic on the AI Gateway, so it runs before the Key Auth AI Auth Strategy. Each AI Model on this AI Gateway that uses a Key Auth AI Auth Strategy with the apikey header also accepts Bearer tokens.
config.rewrite Runs the Lua code in the rewrite phase. The Pre-Function Policy reference lists the other phases.
Lua code Compares the first seven characters of Authorization with bearer , without regard to case, and sets apikey to the rest of the value. A request without a Bearer token passes unchanged, and the Key Auth AI Auth Strategy rejects it. kong.request.get_header and ngx.req.set_header are in the strict sandbox allowlist.

Key Auth AI Auth Strategy and AI Consumer

Authentication is an AI Auth Strategy, not an AI Policy. The Key Auth AI Auth Strategy reads the apikey header that the Pre-Function Policy set 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 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, which the Pre-Function Policy fills from the Bearer token.
hide_credentials: true Kong removes the key before it forwards the request. OpenAI 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.

Kong adds X-Consumer-Username and related headers to the upstream request, not to the response. Per-consumer usage appears in Konnect analytics.

AI Model Provider and AI Model

The AI Model Provider holds the organization’s OpenAI key. The AI Model exposes /coding-agents, accepts OpenAI-format requests whose model field equals CHAT_MODEL, and has one target that uses the AI Model Provider.

The following settings configure the AI Model Provider and the AI Model:

Setting

Purpose

config.auth (AI Model Provider) The Authorization header with the OpenAI key, from OPENAI_TOKEN with its Bearer prefix. Kong adds it to each upstream request, and it takes precedence over the client’s Authorization header.
formats: [{type: openai}] The AI Model accepts OpenAI Chat Completions requests, the format that OpenCode’s OpenAI-compatible package sends.
capabilities: [generate] The AI Model serves /chat/completions and /completions.
config.route.model Kong reads the model field of the request body (body_param: model) and selects this AI Model only if the value equals CHAT_MODEL. An AI Model accepts one value.
targets[].name The model that Kong requests from OpenAI, also CHAT_MODEL. Set it to another model to change what OpenAI serves without changing developer configuration.
config.route.paths and strip_path: true OpenCode adds /chat/completions to baseURL. Kong matches /coding-agents and removes it before it forwards the request.
config.route.methods OpenCode sends requests with POST. The AI Model also accepts GET and OPTIONS on the same path.
config.route.protocols: [http, https] Accepts HTTP, so OpenCode can call the local data plane at http://localhost:8000.
config.max_request_body_size: 16777216 Accepts request bodies up to 16 MB, instead of the 8 MB default. Coding agent requests carry the conversation, tool definitions, and file contents.
config.response_streaming: allow Kong passes streamed responses to OpenCode, which shows tokens as they arrive.
config.logging.payloads: true Kong logs request and response payloads. OpenCode requests contain source code, so set it to false if you only need usage metrics. The default is false.

Production credentials: This cookbook stores the AI Consumer’s API key and the OpenAI key 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.

Variations and next steps

You can change or extend this configuration in the following ways:

Variation

How

Give each developer their own key Add an AI Consumer and credential for each developer, and have each developer export their key as CONSUMER_API_KEY. opencode.json stays the same for everyone. The AI Model and AI Model Provider don’t change.
Restrict OpenCode to the gateway Settings alone can’t stop developers from adding other providers. Use policies in OpenCode’s managed configuration to enforce the kong provider.
Offer more models Add one AI Model for each model name on the same /coding-agents path, each with its own config.route.model.values, and add each model to models in opencode.json. See the Basic LLM routing cookbook for two AI Models on one path.
Add per-consumer token limits Attach the AI Rate Limiting Advanced Policy to give each AI Consumer its own token budget.
Connect other coding agents The Qwen Code and Cursor cookbooks use the same kind of AI Model. Codex uses the Responses API instead, see the Codex cookbook.

Cleanup

Delete the OpenCode configuration file from your project directory:

rm -f opencode.json

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:

export KONNECT_CONTROL_PLANE_NAME='coding-agents-opencode-recipe' && curl -Ls https://get.konghq.com/ai | bash -s -- -d -k $KONNECT_TOKEN

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!