DIRECTORY_ID=$(curl -X POST "https://us.api.konghq.com/v2/directories" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $KONNECT_TOKEN"\
-H "Content-Type: application/json" \
--json '{
"name": "kong-identity-directory",
"description": "Directory for this tutorial",
"allow_all_control_planes": true
}' | jq -r ".id"
)Set up Kong Identity attribution for AI Cost Management
Upload your organization’s structure, then create an openid-connect AI Auth Strategy with principals.enabled set to true and attach it to the AI Model. The first authenticated request creates a matching principal automatically, and the usage event’s subject is recorded as principal/PRINCIPAL_UUID.
Prerequisites
AI Gateway running
This is a Konnect tutorial and requires a Konnect personal access token.
-
Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
-
Export your token to an environment variable:
export KONNECT_TOKEN='YOUR_KONNECT_PAT' -
Run the AI Gateway quickstart script to automatically provision a control plane and data plane in Kong Konnect, and configure your environment:
curl -Ls https://get.konghq.com/ai | bash -s -- -k $KONNECT_TOKEN \ -e KONG_CUSTOM_PLUGIN_STREAMING_ENABLED=on
This sets up a AI Gateway control plane named ai-quickstart, provisions a local data plane, and prints out the following environment variables export:
export AI_GATEWAY_ID=your-gateway-id
export KONNECT_TOKEN=$KONNECT_TOKEN
export KONNECT_CONTROL_PLANE_NAME=ai-quickstart
export KONNECT_CONTROL_PLANE_URL=https://us.api.konghq.com
export KONNECT_PROXY_URL='http://localhost:8000'Copy and paste these into your terminal to configure your session.
Want a fully-hosted AI Gateway? See AI Gateway 2.0 on Dedicated Cloud Gateways.
kongctl v1.29.0+
This tutorial uses kongctl to manage Konnect resources programmatically. We recommend keeping kongctl up to date with the latest version (1.29.0).
- Install kongctl from developer.konghq.com/kongctl.
-
Verify the installation:
kongctl version
OpenAI
- Create an OpenAI account.
- Get an API key.
- Export the API key as a variable:
export OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>" export OPENAI_AUTH_HEADER="Bearer $OPENAI_API_KEY"
Kong Identity directory
A directory is a regional collection of principals. A Konnect organization supports only one Kong Identity directory. Create a directory for the tutorial, or look up your existing one.
Kong Identity auth server and client
You need a Kong Identity auth server and client application to authenticate requests.
A client requests a token under an OAuth2 scope.
Configure one using the /v1/auth-servers/$AUTH_SERVER_ID/scopes endpoint, so the client and the AI Auth Strategy can both be granted it:
SCOPE_ID=$(curl -X POST "https://us.api.konghq.com/v1/auth-servers/$AUTH_SERVER_ID/scopes" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $KONNECT_TOKEN" \
--json '{
"name": "ai-cost-management-access",
"description": "Scope for AI Cost Management attribution clients",
"default": false,
"include_in_metadata": false,
"enabled": true
}' | jq -r ".id"
)A client’s secret is only returned once, at creation, so this guide creates a new client rather than reusing one whose secret you might not have saved.
Create a client using the /v1/auth-servers/$AUTH_SERVER_ID/clients endpoint:
_response=$(curl -X POST "https://us.api.konghq.com/v1/auth-servers/$AUTH_SERVER_ID/clients" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $KONNECT_TOKEN" \
--json '{
"name": "ai-cost-management-kong-identity-client",
"allow_all_scopes": false,
"allow_scopes": [
"'$SCOPE_ID'"
],
"access_token_duration": 300,
"grant_types": [
"client_credentials"
],
"response_types": [
"token"
],
"redirect_uris": [],
"login_uri": ""
}')Export the env variables:
export CLIENT_ID=$(echo "$_response" | jq -r ".id")
export CLIENT_SECRET=$(echo "$_response" | jq -r ".client_secret")Kong Identity attribution links each AI request to a Kong Identity principal.
Every usage event’s subject resolves to principal/PRINCIPAL_UUID.
The AI Cost Management dashboard, explorer, and events debugger show the event by the principal’s display name.
AI Cost Management attributes usage in two independent tracks: the subject and tags, which record context like project or team through a separate mechanism. This guide covers subject attribution only. See Tags and headers for the other track.
This guide attributes usage to a principal built from Kong Identity’s own auth server.
- For a principal built from your own OIDC provider instead, see Set up OIDC attribution.
- For a full walkthrough that also covers budgets, pricing, and tag attribution, see Get started with AI Cost Management.
Add a trusted IdP
A trusted IdP is the OIDC issuer Konnect verifies tokens against, and the place you turn on automatic user provisioning for that issuer. Kong Identity’s own auth server is a valid issuer, so add it as a trusted IdP:
- In the Konnect sidebar, click Access Management.
- Click Identity Providers.
- Click Add trusted IdP.
- In the Name field, enter a label for this IdP, for example
Kong Identity. - In the Issuer URL field, enter your issuer URL (run
echo $ISSUER_URLto print the value you exported earlier). - Enable Automatic user provisioning.
- Click Add IdP.
A client credentials token includes only a
subclaim, so this guide skips claim mapping. For an interactive sign-in flow, your provider’s token can include richer claims.
Upload an org structure (Optional)
AI Cost Management matches each automatically provisioned principal against your organization’s reporting structure. Upload an org chart if you want spend to roll up to a cost center, user, or team. If you skip this step, the principal is still created and the usage event still gets a subject, just without that reporting data.
The org structure file must be in CSV format and a maximum of 10 MB. Choose whether to use an export from your HR system (HRIS) or a sample file:
The
kongctl importcommand is available starting in kongctl 1.27.0.
Apply the CSV to the default Kong Identity directory:
kongctl import identity org-chart \
--pat "$KONNECT_TOKEN" \
--file org-structure.csv \
--execute \
--report-output-dir ./import-reportsYou can set --dry-run instead of --execute to preview the import without changing any existing users or teams.
See Org chart in AI Cost Management for the full column reference and import behavior.
Set a budget
A budget in AI Cost Management tracks spend against a limit and alerts you as spend grows.
Create a monthly budget with a $100 limit:
BUDGET_ID=$(curl -X POST "https://us.api.konghq.com/v1/ai-cost-management/budgets" \
--no-progress-meter --fail-with-body \
-H "Authorization: Bearer $KONNECT_TOKEN" \
--json '{
"name": "monthly-org-budget",
"effect": "limit",
"scope": {
"filters": []
},
"limit": {
"value": "100",
"currency": "USD"
},
"window": {
"type": "fixed",
"interval": "P1M",
"anchored_at": "2026-01-01T00:00:00+00:00[UTC]"
}
}' | jq -r ".id"
)The scope.filters empty array means this budget covers all organization-wide usage.
Create an AI Model Provider, AI Auth Strategy, and AI Model
Create an AI Model Provider to connect AI Gateway to OpenAI, an openid-connect AI Auth Strategy that verifies bearer tokens against your Kong Identity issuer and enables principal lookup, and an AI Model that references both.
When a request arrives, AI Gateway verifies the bearer token and looks up the principal whose identity matches the token’s sub claim, then records it as the event’s subject.
If no principal matches yet, Kong Identity creates one from the token, using the trusted IdP and automatic user provisioning you just set up.
kongctl apply -f - --auto-approve --pat "$KONNECT_TOKEN" << 'EOF'
ai_gateway_model_providers:
- ref: openai-provider
ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
name: openai-provider
display_name: "OpenAI"
type: openai
config:
auth:
type: basic
headers:
- name: Authorization
value: !secret {source: !env OPENAI_AUTH_HEADER}
ai_gateway_auth_strategies:
- ref: kong-identity-oidc
ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
name: kong-identity-oidc
display_name: "Kong Identity OIDC"
type: openid-connect
config:
issuer: !env ISSUER_URL
auth_methods:
- bearer
principals:
enabled: true
scopes:
- ai-cost-management-access
cache_tokens_salt: kong-identity-attribution-cache-salt
ai_gateway_models:
- ref: openai-chat
ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
name: openai-chat
display_name: "OpenAI Chat"
type: model
formats:
- type: openai
capabilities:
- generate
config:
route:
paths:
- /v1
model:
body_param: model
values:
- openai-chat
targets:
- name: gpt-5.4-nano
provider: !ref openai-provider#name
config:
type: openai
access:
auth_strategies:
- !ref kong-identity-oidc#name
policies: []
EOFThe target doesn’t set input_cost or output_cost, so AI Cost Management falls back to the model’s list price from the price catalog.
Send a request
Get an access token from your Kong Identity issuer, then send a chat completion to generate a usage event. The auth strategy verifies the token and resolves it to a principal, creating one automatically from the token if none matches yet.
Request an access token using the client credentials grant:
ACCESS_TOKEN=$(curl -X POST "$ISSUER_URL/oauth/token" \
--no-progress-meter --fail-with-body \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=$CLIENT_ID" \
-d "client_secret=$CLIENT_SECRET" \
-d "scope=ai-cost-management-access" | jq -r ".access_token"
)Use the access token to send a chat completion, which generates the usage event:
curl -X POST "$KONNECT_PROXY_URL/v1/chat/completions" \
--no-progress-meter --fail-with-body \
-H "Content-Type: application/json"\
-H "Authorization: Bearer $ACCESS_TOKEN" \
--json '{
"model": "openai-chat",
"messages": [
{
"role": "user",
"content": "What is an API gateway?"
}
]
}'Validate
The events API returns the usage events for your organization, sorted by newest first.
Find the event your request generated. If your org has other traffic, check that time matches when you sent the request:
curl -s "$KONNECT_CONTROL_PLANE_URL/v1/ai-cost-management/events" \
-H "Authorization: Bearer $KONNECT_TOKEN" \
| jq '.data[0] | {time, subject, context: .data.context, cost: .data.reported_cost}'The event should look like this:
{
"time": "2026-11-12T19:02:02.695Z",
"subject": "principal/01a1c15c-310d-79a6-acde-85f746946396",
"context": {
"provider": "openai",
"model": "gpt-5.4-nano-2026-03-17",
"model_id": "5382d282-c9d3-4c96-910e-76af70e3c883",
"request_mode": "oneshot"
},
"cost": {
"value": "0.000016",
"currency": "USD"
}
}Check the following in the response:
subjectshows your principal asprincipal/PRINCIPAL_UUID.cost.valueis greater than0, using the model’s list price from the price catalog.
If cost.value is 0 or subject is absent, see Troubleshoot missing or wrong data.
You can also check this in the Konnect UI:
- In the sidebar, click Cost Management.
- Click Dashboard to see your request reflected in overall spend.
- Click Explorer to see spend, requests, or tokens over time for this model.
- Click Events debugger to find the individual event and open its full details.
What’s next
You can now:
- Set a price override to replace the model’s list price with your own negotiated rate.
- Explore spend by user, model, or provider in the analytics views.
- Add email or Slack alerts to the budget. See Notification channels.
Cleanup
Clean up AI Gateway resources
To clean up all AI Gateway resources created in this guide, run:
curl -Ls https://get.konghq.com/ai | bash -s -- -dDelete the trusted IdP
In the Konnect sidebar, click Access Management, then click Identity Providers, and delete the trusted IdP you created.
Delete the budget
Delete the budget you created:
curl -X DELETE "$KONNECT_CONTROL_PLANE_URL/v1/ai-cost-management/budgets/$BUDGET_ID" \
-H "Authorization: Bearer $KONNECT_TOKEN"FAQs
Is it possible to add users manually instead of relying on automatic user provisioning?
Yes.
Create a principal in the Kong Identity directory, then link it to your client so AI Gateway can match the token’s sub claim to it, using POST /v2/directories/{directoryId}/principals and POST /v2/directories/{directoryId}/principals/{principalId}/identities.
See Principals for details.