GitHub Copilot BYOK Custom Endpoint

Minimum Version
AI Gateway - 2.0
Incompatible with
on-prem

Overview

Put Kong AI Gateway between GitHub Copilot chat in VS Code and your LLM provider, so that each developer uses their own revocable API key and the provider key stays in AI Gateway. You’ll set up:

  • A custom endpoint model in VS Code that sends Copilot chat and agent requests to AI Gateway
  • An API key and a token budget for each developer
  • A model alias that decouples the model name in VS Code from the upstream model
  • A Konnect dashboard for Copilot usage by developer

This cookbook covers Copilot chat and agent requests. Inline suggestions (code completions) don’t use custom endpoint models, so they don’t go through AI Gateway (VS Code documentation).

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. The two -e settings raise the data plane’s request body buffer and limit to 16 MB, so the large request bodies that Copilot sends (conversation history, tool definitions, file contents) stay in memory instead of being buffered to disk:

    export KONNECT_CONTROL_PLANE_NAME='github-copilot-byok-recipe'
    curl -Ls https://get.konghq.com/ai | \
      bash -s -- -k $KONNECT_TOKEN \
        -e KONG_NGINX_HTTP_CLIENT_BODY_BUFFER_SIZE=16m \
        -e KONG_NGINX_HTTP_CLIENT_MAX_BODY_SIZE=16m

    This provisions an AI Gateway named github-copilot-byok-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 adds a custom endpoint model to GitHub Copilot chat in VS Code. VS Code calls this feature bring your own language model key (BYOK).

  1. Install VS Code and set up GitHub Copilot from the VS Code setup guide.
  2. If you use Copilot Business or Copilot Enterprise, ask your organization administrator to enable the Bring Your Own Language Model Key in VS Code policy in the Copilot policy settings on GitHub.com. Without this policy, you can’t add your own models (GitHub documentation).

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

With bring your own key (BYOK) in VS Code, each developer configures a provider API key in their own editor, which causes the following problems:

Problem

Solution

Each developer holds a copy of the provider API key, and VS Code sends requests directly to the provider. A leaked key means rotating it on every machine. The AI Model Provider keeps the provider credentials in Kong. Each developer holds only their own AI Consumer key, which you revoke without touching the others.
GitHub reports BYOK usage from client telemetry only, so platform teams can’t see reliable usage and cost for each developer. The Key Auth AI Auth Strategy maps each key to an AI Consumer. Konnect shows tokens and cost for each AI Consumer, and the cookbook’s dashboard groups them by developer.
Nothing limits how many tokens one developer spends. Agent sessions with large workspace context use up the budget fast. The AI Rate Limiting Advanced Policy gives each AI Consumer a token budget and returns 429 when the budget runs out.
VS Code sends the key as Authorization: Bearer, and the request body can carry parameters that a model doesn’t support, for example temperature for the newest OpenAI models. A global Pre-Function Policy copies the Bearer token to the apikey header before authentication and removes temperature from the request body.
Each developer’s chatLanguageModels.json names the upstream model, so changing the model means editing every developer’s settings. The AI Model answers to an alias. You change the upstream model in Kong, and developers keep the same model ID in VS Code.

Try it out

Apply the configuration, create the usage dashboard, add Kong as a custom endpoint model in VS Code, then use Copilot chat to test authentication, the model alias, and the token budget.

Apply the Kong configuration

The configuration creates an AI Model Provider with your provider’s credentials, a global Pre-Function Policy, a Key Auth AI Auth Strategy, two AI Consumers (copilot-developer-alice and copilot-developer-bob) with API keys, an AI Rate Limiting Advanced Policy, and an AI Model on /github-copilot. 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 an API key for each of the two developers. Each developer enters their key in VS Code. The credential’s api_key field is write-only, so its value must come from an environment variable:

export COPILOT_KEY_ALICE="$(openssl rand -hex 24)"
export COPILOT_KEY_BOB="$(openssl rand -hex 24)"

Export the model alias. VS Code sends this value as the model field, and the AI Model answers only to this value:

export COPILOT_MODEL_ALIAS='kong-copilot'

Select your provider. Each tab exports CHAT_MODEL, the upstream model that Kong sends to the provider, then applies the configuration. Provider credentials come from the prerequisites.

Create the Copilot Usage dashboard

The dashboard shows cost, token usage, request volume, model mix, usage for each developer (AI Consumer), and latency for Copilot traffic. It’s an organization-level resource, so the command reuses a dashboard with the github-copilot-byok-recipe label if one exists.

Create the dashboard definition:

cat <<'EOF' > copilot-usage-dashboard.json
{
  "name": "Copilot Usage",
  "definition": {
    "tiles": [
      {
        "id": "c0f1ee01-0000-4000-8000-000000000001",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 1 }, "position": { "col": 0, "row": 0 } },
        "definition": {
          "chart": { "type": "single_value", "chart_title": "Total cost ($)" },
          "query": {
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["cost"],
            "datasource": "llm_usage",
            "dimensions": []
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000002",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 1 }, "position": { "col": 2, "row": 0 } },
        "definition": {
          "chart": { "type": "single_value", "chart_title": "Total tokens" },
          "query": {
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["total_tokens"],
            "datasource": "llm_usage",
            "dimensions": []
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000003",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 1 }, "position": { "col": 4, "row": 0 } },
        "definition": {
          "chart": { "type": "single_value", "chart_title": "Total Copilot requests" },
          "query": {
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["ai_request_count"],
            "datasource": "llm_usage",
            "dimensions": []
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000004",
        "type": "chart",
        "layout": { "size": { "cols": 3, "rows": 2 }, "position": { "col": 0, "row": 1 } },
        "definition": {
          "chart": { "type": "top_n", "chart_title": "Top Copilot models by usage" },
          "query": {
            "limit": 10,
            "filters": [],
            "metrics": ["total_tokens", "ai_request_count"],
            "datasource": "llm_usage",
            "dimensions": ["ai_request_model"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000005",
        "type": "chart",
        "layout": { "size": { "cols": 3, "rows": 2 }, "position": { "col": 3, "row": 1 } },
        "definition": {
          "chart": { "type": "timeseries_line", "stacked": false, "chart_title": "Model usage trend (top 5)" },
          "query": {
            "limit": 5,
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["total_tokens"],
            "datasource": "llm_usage",
            "dimensions": ["ai_request_model", "time"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000006",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 2 }, "position": { "col": 0, "row": 3 } },
        "definition": {
          "chart": { "type": "donut", "chart_title": "Copilot health check" },
          "query": {
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["ai_request_count"],
            "datasource": "llm_usage",
            "dimensions": ["status_code_grouped"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000007",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 2 }, "position": { "col": 2, "row": 3 } },
        "definition": {
          "chart": { "type": "donut", "chart_title": "Copilot provider usage" },
          "query": {
            "filters": [
              { "field": "ai_provider", "operator": "not_empty" },
              { "field": "ai_provider", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["ai_request_count"],
            "datasource": "llm_usage",
            "dimensions": ["ai_provider"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000008",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 2 }, "position": { "col": 4, "row": 3 } },
        "definition": {
          "chart": { "type": "timeseries_bar", "stacked": true, "chart_title": "LLM latency (avg)" },
          "query": {
            "filters": [
              { "field": "ai_request_model", "operator": "not_empty" },
              { "field": "ai_request_model", "value": ["UNSPECIFIED"], "operator": "not_in" }
            ],
            "metrics": ["llm_latency_average"],
            "datasource": "llm_usage",
            "dimensions": ["ai_request_model", "time"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-000000000009",
        "type": "chart",
        "layout": { "size": { "cols": 3, "rows": 2 }, "position": { "col": 0, "row": 9 } },
        "definition": {
          "chart": { "type": "horizontal_bar", "stacked": true, "chart_title": "Copilot usage by developer (requests)" },
          "query": {
            "filters": [
              { "field": "consumer", "operator": "not_empty" }
            ],
            "metrics": ["ai_request_count"],
            "datasource": "llm_usage",
            "dimensions": ["consumer"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-00000000000a",
        "type": "chart",
        "layout": { "size": { "cols": 3, "rows": 2 }, "position": { "col": 3, "row": 9 } },
        "definition": {
          "chart": { "type": "vertical_bar", "stacked": true, "chart_title": "Copilot usage by developer (tokens)" },
          "query": {
            "filters": [
              { "field": "consumer", "operator": "not_empty" }
            ],
            "metrics": ["total_tokens"],
            "datasource": "llm_usage",
            "dimensions": ["consumer"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-00000000000b",
        "type": "chart",
        "layout": { "size": { "cols": 2, "rows": 2 }, "position": { "col": 0, "row": 11 } },
        "definition": {
          "chart": { "type": "vertical_bar", "stacked": true, "chart_title": "AI security report (401 / 403 / 429)" },
          "query": {
            "filters": [
              { "field": "status_code", "value": ["401", "403", "429"], "operator": "in" }
            ],
            "metrics": ["request_count"],
            "datasource": "api_usage",
            "dimensions": ["status_code", "consumer"]
          }
        }
      },
      {
        "id": "c0f1ee01-0000-4000-8000-00000000000c",
        "type": "chart",
        "layout": { "size": { "cols": 3, "rows": 2 }, "position": { "col": 2, "row": 11 } },
        "definition": {
          "chart": { "type": "timeseries_bar", "stacked": true, "chart_title": "Monthly spend trends" },
          "query": {
            "limit": 10,
            "filters": [],
            "metrics": ["cost"],
            "datasource": "llm_usage",
            "dimensions": ["ai_request_model", "time"],
            "time_range": { "type": "relative", "time_range": "30d" },
            "granularity": "daily"
          }
        }
      }
    ],
    "template_id": "AI_GATEWAY"
  },
  "labels": {
    "recipe": "github-copilot-byok-recipe"
  }
}
EOF

Create the dashboard in Konnect:

EXISTING_DASHBOARDS=$(kongctl api get "/v2/dashboards?filter%5Blabels.recipe%5D=github-copilot-byok-recipe" \
  --pat "${KONNECT_TOKEN}" -o json --jq '.data | length')

if [ "${EXISTING_DASHBOARDS}" -gt 0 ]; then
  echo "Copilot Usage dashboard already exists. Reusing."
else
  DASHBOARD_ID=$(kongctl api post /v2/dashboards \
    -f copilot-usage-dashboard.json \
    --pat "${KONNECT_TOKEN}" -o json --jq '.id' -r)
  echo "Created Copilot Usage dashboard (id: ${DASHBOARD_ID})."
fi

The dashboard shows LLM traffic for the whole organization. To show only this cookbook’s AI Gateway, add a filter in the Konnect dashboard editor.

Connect VS Code to Kong

VS Code sends requests for a custom endpoint model to any URL that speaks the OpenAI Chat Completions API. VS Code keeps the API key in its secret storage and sends it as Authorization: Bearer <key>.

Print Alice’s key, so that you can paste it into VS Code:

printf '%s\n' "$COPILOT_KEY_ALICE"

Add the custom endpoint model in VS Code:

  1. In the Chat view, open the model picker and select Manage Language Models (gear icon). You can also run Chat: Manage Language Models from the Command Palette.
  2. Select Add Models, then select Custom Endpoint.
  3. Enter Kong as the group name.
  4. Enter a display name, and paste Alice’s key as the API key.
  5. Select Chat Completions as the API type.

VS Code opens chatLanguageModels.json. Update the model entry to match the following example, and keep the apiKey value that VS Code wrote, because it references the key in secret storage:

[
  {
    "name": "Kong",
    "vendor": "customendpoint",
    "apiKey": "${input:kongApiKey}",
    "apiType": "chat-completions",
    "models": [
      {
        "id": "kong-copilot",
        "name": "Kong Copilot",
        "url": "http://localhost:8000/github-copilot/chat/completions",
        "toolCalling": true,
        "vision": false,
        "maxInputTokens": 128000,
        "maxOutputTokens": 16000
      }
    ]
  }
]

The model fields have the following roles:

Field

Purpose

id The model identifier that VS Code sends in the model field. It must equal COPILOT_MODEL_ALIAS.
url The full endpoint URL. VS Code uses a URL that ends in /chat/completions as it is.
toolCalling Set to true. VS Code shows a model in agent mode only if it supports tool calling.
maxInputTokens and maxOutputTokens Together they define the context window that VS Code uses. Set them from your upstream model’s documentation.

Save the file. If the model doesn’t appear in the model picker, restart VS Code.

Ask Copilot a question

Select Kong Copilot in the Chat view’s model picker and send a prompt, for example:

Explain what an API gateway does in one sentence.

The answer streams into the Chat view. Kong copied the Bearer token to apikey, authenticated Alice’s AI Consumer, matched the kong-copilot alias, and sent the request upstream with the provider credentials. If Copilot shows a 401 error, the key didn’t reach Kong. Update the API key from the gear icon next to the Kong provider in the Language Models editor, and paste the key again.

Hit the model alias boundary

The AI Model answers only to the alias. In chatLanguageModels.json, change id to another value, for example gpt-4o, save the file, and send a prompt. Kong finds no AI Model for that name and rejects the request before any provider call. On runtime 2.3.1, the status is 500 after about 12 seconds, with failed the initial dns/balancer resolve for 'ai-gateway.upstream.local' in the body.

Change id back to kong-copilot, and requests succeed again.

Hit the rate limit

Each AI Consumer can use 50,000 tokens in a 60-second sliding window. Agent requests that carry workspace context are large, so a few prompts in quick succession use up the budget. For example, ask Copilot to summarize several files in your repository. When Alice’s budget runs out, Copilot shows an error with the status:

429 Too Many Requests

Bob’s AI Consumer has identifier: consumer on the same AI Rate Limiting Advanced Policy. Select the gear icon next to the Kong provider in the Language Models editor, replace the API key with the value of COPILOT_KEY_BOB, and send a prompt. In a test on runtime 2.3.1 from one machine, Alice and Bob shared one token counter, so Bob’s request was also limited. This cookbook hasn’t confirmed separate budgets for developers on different machines.

Check the results

The Copilot sessions confirm the following:

Behavior

Evidence

Per-developer authentication Copilot answers with Alice’s key and with Bob’s key. Neither developer holds the provider key.
Bearer token accepted VS Code sends Authorization: Bearer, and the Key Auth AI Auth Strategy still authenticates the request, because the global Pre-Function Policy copied the token to apikey first.
Model alias Requests with id: kong-copilot succeed. Another id gets an error before any provider call.
Token budget Alice gets 429 Too Many Requests after about 50,000 tokens in a minute. Whether Bob still has his own budget depends on how Kong separates the counters (see the identifier: consumer row in How it works).
Usage for each developer The Copilot Usage dashboard shows requests and tokens for copilot-developer-alice and copilot-developer-bob.

To review the created entities and per-consumer usage, open the github-copilot-byok-recipe AI Gateway in Konnect. For traffic across all your AI Gateways, use the Observability menu. The Copilot Usage dashboard is in Observability > Dashboards.

How it works

VS Code sends each chat or agent request to Kong with the developer’s key as a Bearer token. A global Pre-Function Policy copies the token to the apikey header, the Key Auth AI Auth Strategy identifies the AI Consumer, the AI Model matches the alias, the AI Rate Limiting Advanced Policy checks the developer’s token budget, and Kong forwards the request with the provider credentials.

sequenceDiagram
    participant VS as VS Code
    participant K as Kong AI Gateway
    participant L as LLM Provider

    VS->>K: POST /github-copilot/chat/completions (Authorization Bearer key, model kong-copilot)
    activate K
    K->>K: Global Pre-Function Policy copies the Bearer token to apikey and removes temperature
    K->>K: Key Auth AI Auth Strategy identifies the AI Consumer (else 401)
    K->>K: AI Model matches the alias in the model field
    K->>K: AI Rate Limiting Advanced Policy checks the token budget (else 429)
    K->>L: Request with the provider credentials and the upstream model
    activate L
    L-->>K: Response
    deactivate L
    K-->>VS: OpenAI-format response
    deactivate K

Pre-Function Policy

The Pre-Function Policy runs Lua code from its config.access list in the access phase. It’s global, because a global Pre-Function Policy runs before authentication, while one listed on the AI Model runs after it (sandboxing). The Key Auth AI Auth Strategy reads the apikey header, so the header must exist before authentication runs.

The following settings configure the Pre-Function Policy:

Setting

Purpose

global: true Runs the policy for each request on the AI Gateway, before authentication. If one AI Gateway has several global Pre-Function Policies, only the one with the highest ID takes effect.
ngx.req.set_header("apikey", ...) Copies the token from an Authorization: Bearer header into the apikey header that the Key Auth AI Auth Strategy reads.
kong.service.request.set_raw_body(...) Removes temperature from the JSON body, so the provider uses its default. The newest OpenAI models expect Chat Completions requests without temperature (OpenAI migration guide). This cookbook hasn’t confirmed against a live AI Gateway that the AI Model forwards the changed body.

The policy uses only functions and modules that the Lua sandbox allows (cjson.safe, ngx.req.set_header, kong.request.get_raw_body, and kong.service.request.set_raw_body).

Key Auth AI Auth Strategy and AI Consumers

Authentication is an AI Auth Strategy, not an AI Policy. The Key Auth AI Auth Strategy matches the apikey header to an AI Consumer credential and rejects unknown keys with 401 before any provider call. The AI Consumer is the identity that the rate limit and analytics use.

The following settings configure the Key Auth AI Auth Strategy and the AI Consumers:

Setting

Purpose

key_names: [apikey] The header that Kong reads the key from. The Pre-Function Policy fills it from the Bearer token.
hide_credentials: true Kong removes the apikey header before it forwards the request, so the provider never sees a developer’s key.
ai_gateway_consumers[].credentials One AI Consumer for each developer, with an api-key credential. The api_key field is write-only, so it reads COPILOT_KEY_ALICE and COPILOT_KEY_BOB with !secret.

Kong adds X-Consumer-Username and related headers to the upstream request, not to the response. Usage for each AI Consumer appears in Konnect analytics.

AI Model Provider and AI Model

The AI Model Provider holds the provider credentials. The AI Model github-copilot-byok-model accepts OpenAI-format requests on /github-copilot, answers to one alias, and routes to one target that references the AI Model Provider. VS Code sends the alias, and Kong sends the target’s upstream model to the provider.

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.
formats: [{type: openai}] The AI Model accepts OpenAI Chat Completions requests, which is the API type that the VS Code model uses. Kong translates the request for providers with another native format, for example Bedrock.
access.auth_strategies Each request must have a valid AI Consumer key.
policies Attaches the AI Rate Limiting Advanced Policy to the AI Model. The Pre-Function Policy isn’t listed, because it’s global.
config.route.model Kong reads the model field of the request body (body_param: model) and matches it against COPILOT_MODEL_ALIAS. An AI Model accepts one value.
targets[].name The upstream model, from CHAT_MODEL. Change it and re-apply to switch models without changing VS Code settings.
targets[].config The provider type and provider-specific target fields, for example Azure’s deployment_id and api_version, or Bedrock’s region.
targets[].config.input_cost and output_cost The cost for 1 million input and output tokens, which Konnect uses for cost tracking. The values 0.25 and 2.00 are examples. Replace them with your provider’s pricing for the model.
config.max_request_body_size: 10485760 Accepts request bodies up to 10 MB, instead of the 8 MB default. Copilot requests carry conversation history, tool definitions, and file contents.
config.response_streaming: allow Kong passes streamed responses to VS Code, which shows the answer as it arrives.
config.logging.payloads: true Kong logs request and response payloads for audits. The default is false.

AI Rate Limiting Advanced Policy

The AI Rate Limiting Advanced Policy counts prompt and completion tokens, the unit that drives LLM cost. Each AI Consumer gets 50,000 tokens in a 60-second sliding window. When an AI Consumer uses up the budget, Kong returns 429 Too Many Requests until the window allows requests again.

The following settings configure the AI Rate Limiting Advanced Policy:

Setting

Purpose

config.policies[].limits The token limit and the window size in seconds: 50000 and 60.
identifier: consumer Counts usage for each AI Consumer. In a test on runtime 2.3.1, two AI Consumers that called from the same machine shared one counter. This cookbook hasn’t confirmed separate budgets for developers on different machines.
window_type: sliding A sliding window, for smoother limits than the fixed window.
tokens_count_strategy: total_tokens Counts prompt and completion tokens. Other values count only prompt tokens, only completion tokens, or cost.
strategy: local Keeps the counters in memory on each data plane node. For several nodes, use redis so that the nodes share the counters.

The 60-second window lets a few prompts use up the budget in this cookbook. In production, most teams use daily or monthly budgets, for example limits: [{limit: 5000000, window_size: 2592000}]. Store the provider credentials and the AI Consumer keys in AI Vaults instead of environment variables.

Response headers

Kong adds the following rate limit headers to each response:

Header

Description

X-AI-RateLimit-Limit-minute-policy-1 The token limit for the 60-second window of the first entry in config.policies.
X-AI-RateLimit-Remaining-minute-policy-1 The tokens left in the current window. Kong rejects a request whose prompt is larger than this value with 429.
X-AI-RateLimit-Reset The seconds until the quota is restored.
X-AI-RateLimit-Retry-After On a 429 response, the seconds until the AI Consumer can send requests again. There is no plain Retry-After header.

Variations and next steps

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

Variation

How

Switch the upstream model Change CHAT_MODEL and re-apply the configuration from Apply the Kong configuration. Developers keep the kong-copilot model ID in VS Code.
Send the apikey header from VS Code Add "requestHeaders": {"apikey": "${apiKey}"} to the model in chatLanguageModels.json. VS Code then sends the key in apikey instead of Authorization (custom authentication headers), and the Pre-Function Policy only removes temperature.
Change the token budget Change limits in the AI Rate Limiting Advanced Policy, for example limits: [{limit: 5000000, window_size: 2592000}] for 5 million tokens a month. Add several limits entries to set a burst limit and a sustained limit in the same policy.
Share rate limit counters Set strategy: redis and point the policy at a shared Redis instance, so that all data plane nodes use the same counters.
Add a developer Add an ai_gateway_consumers entry with its own credential and re-apply. The AI Model and the policies don’t change.
Use single sign-on Replace the Key Auth AI Auth Strategy with an OpenID Connect AI Auth Strategy, as in the Claude Code SSO cookbook.
Redact sensitive data Attach an AI PII Sanitizer Policy to the AI Model, so that personal data in prompts doesn’t reach the provider.
Support other OpenAI-format clients Point any client that speaks the OpenAI Chat Completions API at /github-copilot with its own AI Consumer key. See the Basic LLM Routing cookbook.

Cleanup

The recipe’s kongctl namespace scoped all resources, so this teardown removes only this recipe’s configuration.

The Copilot Usage dashboard is an organization-level resource that outlives the AI Gateway. Delete it first:

DASHBOARD_IDS=$(kongctl api get "/v2/dashboards?filter%5Blabels.recipe%5D=github-copilot-byok-recipe" \
  --pat "${KONNECT_TOKEN}" -o json --jq '.data[].id' -r)

if [ -z "${DASHBOARD_IDS}" ]; then
  echo "No Copilot Usage dashboard found. Skipping."
else
  for id in ${DASHBOARD_IDS}; do
    if kongctl api delete "/v2/dashboards/${id}" --pat "${KONNECT_TOKEN}"; then
      echo "Deleted Copilot Usage dashboard ${id}."
    else
      echo "Failed to delete dashboard ${id}."
    fi
  done
fi

Tear down the local data plane and delete the AI Gateway from Konnect:

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

Remove the dashboard definition:

rm -f copilot-usage-dashboard.json

In VS Code, delete the Kong entry from chatLanguageModels.json, so that Copilot stops showing a model whose endpoint no longer exists.

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!