diff --git a/src/assets/images/ai-gateway/policies-block-policy.png b/src/assets/images/ai-gateway/policies-block-policy.png new file mode 100644 index 00000000000..6e8b0b141f5 Binary files /dev/null and b/src/assets/images/ai-gateway/policies-block-policy.png differ diff --git a/src/assets/images/ai-gateway/policies-create-policy.png b/src/assets/images/ai-gateway/policies-create-policy.png new file mode 100644 index 00000000000..3271b1b60e2 Binary files /dev/null and b/src/assets/images/ai-gateway/policies-create-policy.png differ diff --git a/src/assets/images/ai-gateway/policies-list.png b/src/assets/images/ai-gateway/policies-list.png new file mode 100644 index 00000000000..71b5820a062 Binary files /dev/null and b/src/assets/images/ai-gateway/policies-list.png differ diff --git a/src/assets/images/ai-gateway/policies-test.png b/src/assets/images/ai-gateway/policies-test.png new file mode 100644 index 00000000000..23ffb21ae3c Binary files /dev/null and b/src/assets/images/ai-gateway/policies-test.png differ diff --git a/src/content/changelog/ai-gateway/2026-12-02-policies.mdx b/src/content/changelog/ai-gateway/2026-12-02-policies.mdx new file mode 100644 index 00000000000..55fa59a474f --- /dev/null +++ b/src/content/changelog/ai-gateway/2026-12-02-policies.mdx @@ -0,0 +1,31 @@ +--- +title: Control spend and model access with AI Gateway policies +description: Set budgets and block or allow models on AI Gateway based on the verified identity of the caller, including IdP groups, email domains, and custom metadata. +date: 2026-12-02 +--- + +You can now control who can use which models and providers on your gateway, and how much each user or team can spend, with AI Gateway [policies](/ai-gateway/features/policies/). Policies use the verified identity of the caller from [Cloudflare Access](/ai-gateway/configuration/cloudflare-access/), such as the user's email or identity provider (IdP) groups, or values you pass in [custom metadata](/ai-gateway/observability/custom-metadata/). + +With policies, you can: + +- Give a team or an email domain a shared monthly budget. +- Cap spend for each individual user, including inside a shared team budget. +- Block an IdP group from expensive models, or allow it to use only specific models. + +Each policy targets an identity and a set of models or providers, then allows, blocks, or caps matching requests. Spend caps reset hourly, daily, weekly, or monthly on UTC boundaries. Use **Test policies** in the dashboard, or the simulate endpoint in the API, to check how your policies handle a request before it reaches real traffic. + +The following policy blocks members of the `contractors` IdP group from all Claude Opus models: + +```json +{ + "name": "Block contractors from Claude Opus", + "actor": "company:all", + "resource": { "model": "anthropic/claude-opus-*" }, + "condition": "\"contractors\" in cf.user.groups", + "action": { "type": "block" } +} +``` + +Policies replace [spend limits](/ai-gateway/features/spend-limits/), which are now deprecated. Existing spend limit rules continue to work. To move them to policies, refer to [Migrate from spend limits](/ai-gateway/features/policies/#migrate-from-spend-limits). + +For more details, refer to the [Policies documentation](/ai-gateway/features/policies/). diff --git a/src/content/docs/ai-gateway/configuration/cloudflare-access.mdx b/src/content/docs/ai-gateway/configuration/cloudflare-access.mdx index 86aae2c45b2..9011b09c6d6 100644 --- a/src/content/docs/ai-gateway/configuration/cloudflare-access.mdx +++ b/src/content/docs/ai-gateway/configuration/cloudflare-access.mdx @@ -18,6 +18,8 @@ When a request to a custom domain includes a valid Cloudflare Access JWT, AI Gat AI Gateway also adds the verified Access user ID to request metadata as [`cf.user_id`](/ai-gateway/observability/custom-metadata/#reserved-metadata). This value is the Access JWT `sub` claim, not the user's email address. You can then filter logs, analytics, and spend by the authenticated user. +The user ID, email, IdP groups, and custom claims from Access are also available to [policies](/ai-gateway/features/policies/), so you can set budgets and model access rules for each user or group. + Before AI Gateway forwards the request to the upstream provider, it removes Cloudflare-only credentials such as the Access JWT and AI Gateway authorization headers. Once a custom domain is protected by Access, every request to that domain must pass an Access policy. Requests that only include an AI Gateway token, without a valid Access token, are blocked by Access before they reach the gateway. Update existing integrations to authenticate through Access, or keep sending gateway-token traffic to the default `gateway.ai.cloudflare.com` endpoint, which is not protected by Access. diff --git a/src/content/docs/ai-gateway/features/index.mdx b/src/content/docs/ai-gateway/features/index.mdx index 085a6303fe2..55c55ff9616 100644 --- a/src/content/docs/ai-gateway/features/index.mdx +++ b/src/content/docs/ai-gateway/features/index.mdx @@ -30,16 +30,17 @@ Serve identical requests directly from Cloudflare's global cache, reducing laten - + -Set cost-based budgets that track cumulative dollar spend across requests. Scope limits by model, provider, or custom metadata dimensions like user, team, or application. +Control how much each user or group can spend, and which models and providers they can call. Policies use the verified identity of the caller from Cloudflare Access or [custom metadata](/ai-gateway/observability/custom-metadata/). Policies replace [spend limits](/ai-gateway/features/spend-limits/). **Key benefits:** -- Per-provider or per-model budgets -- Per-user or per-team budgets using [custom metadata](/ai-gateway/observability/custom-metadata/) -- Configurable time windows (daily, weekly, monthly) -- Automatic request blocking when budget is exceeded +- Shared budgets for teams or email domains +- Individual spend caps for each user +- Hourly, daily, weekly, or monthly budgets +- Block or allowlist models by IdP group, user, email domain, or custom metadata +- Test policies before they affect live traffic @@ -199,13 +200,13 @@ Override default pricing with your negotiated rates or custom cost models. Apply ## Feature Comparison by Use Case -| Use Case | Recommended Features | -| -------------------------- | --------------------------------------------------------------- | -| **Cost Optimization** | Caching, Auto Router, Spend Limits, Rate Limiting, Custom Costs | -| **High Availability** | Fallbacks using Dynamic Routing | -| **Security & Compliance** | Guardrails, DLP, Authentication, BYOK, Logging | -| **Performance Monitoring** | Analytics, Logging, Custom Metadata | -| **A/B Testing** | Dynamic Routing, Custom Metadata, Analytics | +| Use Case | Recommended Features | +| -------------------------- | ----------------------------------------------------------- | +| **Cost Optimization** | Caching, Auto Router, Policies, Rate Limiting, Custom Costs | +| **High Availability** | Fallbacks using Dynamic Routing | +| **Security & Compliance** | Guardrails, DLP, Authentication, BYOK, Logging | +| **Performance Monitoring** | Analytics, Logging, Custom Metadata | +| **A/B Testing** | Dynamic Routing, Custom Metadata, Analytics | ## Getting Started with Features diff --git a/src/content/docs/ai-gateway/features/policies.mdx b/src/content/docs/ai-gateway/features/policies.mdx new file mode 100644 index 00000000000..fe20d9eac58 --- /dev/null +++ b/src/content/docs/ai-gateway/features/policies.mdx @@ -0,0 +1,667 @@ +--- +pcx_content_type: configuration +title: Policies +description: Use identity-based policies to control which users can call which models and providers on your AI Gateway, and how much each user or team can spend. +sidebar: + order: 4 + badge: Beta +products: + - ai-gateway +--- + +import { CURL, DashButton, Steps } from "~/components"; + +Policies let you control **who** can use **which models and providers** on a gateway, and **how much they can spend**. AI Gateway evaluates each request against the identity of the caller, then allows it, blocks it with a `403`, or checks it against one or more spend limits. + +Use policies to: + +- Give a team or an email domain a shared monthly budget. +- Cap spend for each individual user. +- Block an identity provider (IdP) group from using expensive models. +- Allow only specific models for a group. + +Policies replace the [spend limits](/ai-gateway/features/spend-limits/) in gateway settings. In addition to everything spend limits can do with request metadata, policies can use the verified identity of the caller from [Cloudflare Access](/ai-gateway/configuration/cloudflare-access/), and can block or allow access to models. If you use spend limits today, [migrate to policies](#migrate-from-spend-limits). + +![Policies tab listing a company-wide spend cap, an email domain spend cap, and a policy that blocks Claude Opus models](~/assets/images/ai-gateway/policies-list.png) + +## How it works + +When a request arrives, AI Gateway: + +1. Reads the identity of the caller from a [Cloudflare Access](/ai-gateway/configuration/cloudflare-access/) JWT, the request country, and the [`cf-aig-metadata`](/ai-gateway/observability/custom-metadata/) header. +2. Evaluates every policy on the gateway against that identity and the model and provider of the request. +3. Allows the request, blocks it with a `403`, or checks the spend limits that apply. If any applicable limit is used up, AI Gateway rejects the request with a `429`. + +If a gateway has no policies, AI Gateway allows all requests. After you add the first policy, AI Gateway rejects any request that does not match at least one policy. + +:::caution[Your first policy turns on enforcement] + +When a gateway has at least one policy, requests that do not match any policy are blocked with a `403`. Before you add restrictive policies, add a policy that covers the traffic you want to allow. For example, add a spend cap that applies to **Everyone** on **All models and providers**. + +::: + +:::note[Cached responses skip spend caps] + +When AI Gateway serves a response from the [cache](/ai-gateway/features/caching/), it still rejects the request with a `403` if a block policy matches or no policy matches. It does not check spend caps, and the request does not count toward a budget. + +::: + +## Policy components + +Each policy has four parts: + +| Part | Description | +| ----------- | ----------------------------------------------------------------------------------------------------------------- | +| Who (actor) | The identity the policy targets. For spend caps, the actor also decides which budget bucket the request draws on. | +| Resources | The models or providers the policy covers. | +| Action | What happens when the policy matches: allow until capped, allow without a cap, or block. | +| Conditions | Optional [Common Expression Language (CEL)](https://cel.dev/) expression that narrows when the policy applies. | + +### Who + +The **Who** setting controls who the policy applies to. For spend caps, it also names the budget bucket that matching requests share. + +| Option | Applies to | Budget | +| -------------------------- | ----------------------------------------------------------- | -------------------------------------------- | +| **Everyone** | All requests to the gateway. | One budget shared by all requests. | +| **User** | A single user, identified by email address. | One budget for that user. | +| **Email domain ending in** | Users whose email ends in a domain, such as `@example.com`. | One budget shared by everyone in the domain. | +| **Actor bucket** | A custom actor string that you define. | Depends on the actor string. | + +Use **Actor bucket** for budgets the other options cannot express. An actor is a string that can contain identity fields inside braces. AI Gateway resolves those fields for each request: + +- `team:engineering` is a fixed string. All matching requests share one budget. +- `user:{cf.user.id}` resolves to each Access user ID. Each user gets their own budget. +- `user:{metadata.user_id}` resolves to the `user_id` value in `cf-aig-metadata`. Each value gets its own budget. + +If AI Gateway cannot resolve a field in the actor for a request, the policy does not apply to that request. + +### Resources + +The **Resources** setting limits a policy to specific models or providers: + +- **All models and providers** +- **Model** — one or more model IDs, such as `openai/gpt-5.5` +- **Provider** — one or more providers, such as `anthropic` +- **Model and provider** — specific models from a specific provider + +Model IDs support the `*` wildcard. For example, `openai/gpt-*` matches `openai/gpt-5.5` and `openai/gpt-5.5-mini`. A wildcard does not match across a `/` character. Provider names do not support wildcards. + +### Action + +| Action | Behavior | +| ----------------------- | ------------------------------------------------------------------------------------------ | +| **Allow until capped** | Allows matching requests until spend in the budget reaches the amount for the time window. | +| **Allow without a cap** | Allows matching requests with no spend limit. | +| **Block** | Rejects matching requests with a `403`. | + +Spend caps use a calendar-based time window aligned to UTC. When the window resets, the budget starts again from zero: + +| Time window | Resets | +| ----------- | -------------------------------------------- | +| Hourly | At the start of every hour. | +| Daily | Every day at 00:00 UTC. | +| Weekly | Every Monday at 00:00 UTC. | +| Monthly | On the first day of each month at 00:00 UTC. | + +### Conditions + +Conditions are optional. Use them to target requests by attributes that the **Who** setting does not cover, such as a user's IdP group, a custom metadata value, or the request country. + +In the dashboard, use the **Builder** tab to add conditions on these fields: + +- **Country** +- **User email** +- **User ID** +- **User groups** + +To write the expression directly, use the **Raw CEL** tab. A condition must return a boolean. + +Conditions and actor strings can only use the identity fields that Cloudflare Access provides, the request country, and custom metadata: + +| Field | Source | +| ------------------- | -------------------------------------------------------------------------------------- | +| `cf.user.id` | The `sub` claim of the Cloudflare Access JWT. | +| `cf.user.email` | The `email` claim of the Cloudflare Access JWT. Empty for service tokens. | +| `cf.user.groups` | The user's IdP group names and IDs. Refer to [IdP groups](#idp-groups). | +| `cf.common_name` | The `common_name` claim of the Cloudflare Access JWT, set for service tokens. | +| `cf.custom.` | A claim in the `custom` object of the Cloudflare Access JWT. | +| `cf.country` | The two-letter country code of the request. | +| `metadata.` | A key from the [`cf-aig-metadata`](/ai-gateway/observability/custom-metadata/) header. | + +The model and provider of the request are not available in conditions. Use [Resources](#resources) to match them. + +The following are examples of valid conditions: + +```txt +"contractors" in cf.user.groups +metadata.team == "contractors" +cf.user.email.endsWith("@example.com") +cf.country == "US" +metadata.environment == "production" +true +``` + +`cf.user.*` fields are only available when the request is authenticated with [Cloudflare Access](/ai-gateway/configuration/cloudflare-access/). If you do not use Access, pass identity values in `cf-aig-metadata` and reference them with `metadata.`. The `cf-aig-metadata` header must be a flat JSON object with up to five keys. AI Gateway ignores the header if it contains nested objects or arrays. + +### IdP groups + +`cf.user.groups` lists the groups that your identity provider reports to Cloudflare Access for the user. It contains both the name and the ID of each group, so a condition can match either: + +```txt +"contractors" in cf.user.groups +"7c9a2f6e-1b3d-4e5f-8a9b-0c1d2e3f4a5b" in cf.user.groups +``` + +Requests authenticated with a service token have no groups. If AI Gateway cannot load a user's groups, it rejects the request with a `503`. + +Your identity provider must send groups to Access. Refer to [identity providers](/cloudflare-one/integrations/identity-providers/) for the providers that support groups. + +## How policies are evaluated + +AI Gateway evaluates all policies for every request. The order in which you create policies does not matter. + +1. **Match.** A policy matches when its resource matches the request model and provider, and its condition is true. +2. **Block wins.** If any matching policy blocks the request, AI Gateway rejects it with a `403`. No other policy can override a block. +3. **Group by budget.** AI Gateway groups the remaining matching policies by their resolved actor and resource. Each group is one budget bucket. +4. **Resolve each bucket.** If a bucket contains an **Allow without a cap** policy, AI Gateway does not check spend for that bucket. If a bucket contains several spend caps with the same time window, the highest amount applies. +5. **Check every bucket.** The request must be under the limit in every bucket that applies. For example, a user can be subject to a company budget, a team budget, and a personal budget at the same time. If any budget is used up, AI Gateway rejects the request with a `429`. +6. **Deny by default.** If no policy matches the request, AI Gateway rejects it with a `403`. + +If a block policy references an identity field that is missing from the request, AI Gateway blocks the request when the resource matches. Other policies that reference a missing field do not apply to that request. + +## Create a policy + + + +1. In the Cloudflare dashboard, go to the **AI Gateway** page. + + + +2. Select your gateway. +3. Go to **Policies** and select **Add policy**. +4. Under **Who and what does this policy target?**, select who the policy applies to in **Who**, and the models or providers it covers in **Resources**. +5. Under **What should happen?**, select an action. For **Allow until capped**, enter an **Amount (USD)** and select a **Time window**. +6. (Optional) Under **Under what conditions?**, select **Add condition** to add a condition, or write an expression in **Raw CEL**. +7. Review the summary in **Preview**, then select **Create policy**. + + + +![Create a policy form with a monthly spend cap of 1,000 US dollars for everyone on all models and providers](~/assets/images/ai-gateway/policies-create-policy.png) + +The policy takes effect as soon as you create it. To change a policy, select the edit icon next to it. To remove a policy, select the delete icon. + +The following example blocks users in the `contractors` IdP group from all Claude Opus models: + +![Create a policy form that blocks the anthropic/claude-opus-* models when the user groups contain contractors](~/assets/images/ai-gateway/policies-block-policy.png) + +## Test policies + +Use **Test policies** on the **Policies** tab to check how your policies handle a request before real traffic reaches them. Testing does not send a request to a provider or record any spend. + + + +1. Under **Identity**, enter the identity fields to test. The fields shown depend on the fields your policies use. To test other attributes, such as metadata, select **JSON** and enter an identity object. +2. Under **Request**, enter a **Model**. AI Gateway fills in the **Provider** for known models. +3. Select **Test policies**. + + + +The result shows whether the request is allowed or blocked. + +![Test policies panel showing that a request from a user in the contractors group to anthropic/claude-opus-4-7 is blocked](~/assets/images/ai-gateway/policies-test.png) + +Test results do not account for spend already recorded against a budget. + +## Send identity with requests + +Policies need identity data on each request. You can provide it in two ways. + +### With Cloudflare Access + +Put your gateway behind [Cloudflare Access](/ai-gateway/configuration/cloudflare-access/). AI Gateway validates the Access JWT on each request and makes `cf.user.id`, `cf.user.email`, `cf.user.groups`, `cf.common_name`, and `cf.custom.*` available to policies. Clients cannot forge these values. + +### With custom metadata + +Pass identity values in the [`cf-aig-metadata`](/ai-gateway/observability/custom-metadata/) header, then reference them as `metadata.` in conditions and actors: + +```bash +curl https://gateway.ai.cloudflare.com/v1/$ACCOUNT_ID/$GATEWAY_ID/openai/chat/completions \ + --header "Authorization: Bearer $OPENAI_API_KEY" \ + --header "Content-Type: application/json" \ + --header 'cf-aig-metadata: {"user_id": "user-1234", "team": "research"}' \ + --data '{ + "model": "gpt-5.5", + "messages": [{"role": "user", "content": "What is Cloudflare?"}] + }' +``` + +:::note + +Your application sets the `cf-aig-metadata` header, so AI Gateway cannot verify it. Only rely on metadata for policies when requests come from a trusted backend. Use Cloudflare Access when you need verified user identity. + +::: + +## Responses when a policy rejects a request + +When a block policy matches, or no policy matches, AI Gateway returns a `403`: + +```json +{ + "success": false, + "error": { + "message": "Access denied by policy" + } +} +``` + +When a spend cap is reached, AI Gateway returns a `429`: + +```json +{ + "success": false, + "error": { + "message": "Spending limit exceeded", + "bucket": "", + "spent": 1000.42, + "limit": 1000 + } +} +``` + +## Manage policies with the API + +You can create and manage policies with the Cloudflare API. All endpoints are scoped to a gateway: + +```txt +https://api.cloudflare.com/client/v4/accounts/{account_id}/ai-gateway/gateways/{gateway_id}/policies +``` + +Authenticate with an [API token](/fundamentals/api/get-started/create-token/) that has AI Gateway edit permissions. + +### Policy object + +| Field | Type | Description | +| ------------ | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | `string` | Generated by AI Gateway. | +| `name` | `string` | A label for the policy. Also used to identify the policy in simulation requests. | +| `actor` | `string` | The budget bucket. Can contain identity fields in braces, such as `user:{cf.user.id}`. | +| `resource` | `string` or `object` | `"*"`, `{ "model": ... }`, `{ "provider": ... }`, or `{ "model": ..., "provider": ... }`. Values can be a string or an array of strings. | +| `condition` | `string` | A CEL expression. Use `"true"` to match every request. | +| `action` | `object` | Refer to [Action object](#action-object). | +| `created_at` | `number` | Unix timestamp in seconds. | +| `updated_at` | `number` | Unix timestamp in seconds. | + +### Action object + +The following action objects are supported: + +```jsonc +// Allow without a cap +{ "type": "no-limit" } + +// Block matching requests +{ "type": "block" } + +// Block every request except those that match the resource (allowlist) +{ "type": "block", "except": true } + +// Spend cap +{ "type": "limit", "amount": 1000, "period": "monthly", "technique": "named-interval" } +``` + +For a spend cap: + +- `amount` is in US dollars and must be greater than zero. +- `period` is `hourly`, `daily`, `weekly`, or `monthly`. Refer to [Action](#action) for when each period resets. +- `technique` must be `named-interval`. + +### Stage, test, and commit changes + +The API supports a staging workflow so you can test changes before they affect live traffic: + +1. **Stage.** Create or update a policy without `commit=true`. AI Gateway saves the change as a draft and does not enforce it. +2. **Simulate.** Call the simulate endpoint. It evaluates your live policies and staged drafts against a sample request. +3. **Commit.** Commit all drafts with the commit endpoint, or commit a single change by passing `commit=true`. + +Policies that you create in the dashboard take effect immediately. + +### List policies + + + +Add `?includeStaging=true` to include staged drafts. Drafts include `"staging": true`. + +```json +{ + "success": true, + "result": [ + { + "id": "d682e5be-1cbe-4328-b7ec-0976fc8644f5", + "name": "Everyone spend cap", + "actor": "company:all", + "resource": "*", + "condition": "true", + "action": { + "type": "limit", + "amount": 1000, + "period": "monthly", + "technique": "named-interval" + }, + "created_at": 1791244351, + "updated_at": 1791244351 + } + ] +} +``` + +### Create a policy + + + +Without `commit=true`, AI Gateway saves the policy as a draft. The response includes the generated `id` and whether the policy was committed: + +```json +{ + "success": true, + "result": { + "id": "1fbd5ff2-f94d-408d-aa43-dda6ebf9984a", + "name": "Block contractors from Claude Opus", + "actor": "company:all", + "resource": { "model": "anthropic/claude-opus-*" }, + "condition": "\"contractors\" in cf.user.groups", + "action": { "type": "block" }, + "created_at": 1791244512, + "updated_at": 1791244512 + }, + "committed": true +} +``` + +If the condition or actor contains a CEL syntax error, AI Gateway returns a `400` with details about the error. + +### Get a policy + + + +Add `?includeStaging=true` to return the staged draft of the policy if one exists. The response then includes `"uncommitted": true`. + +### Update a policy + +Send only the fields you want to change: + + + +Without `commit=true`, AI Gateway saves the change as a draft. You can only update a policy that has been committed. + +```json +{ "success": true, "committed": true } +``` + +### Delete a policy + + + +Deleting a policy also removes any staged draft of it. + +### Commit staged policies + + + +AI Gateway commits all staged drafts for the gateway: + +```json +{ + "success": true, + "result": { + "committed": 3, + "failed": 0, + "policies": [] + } +} +``` + +If any draft fails to commit, `success` is `false` and `result.errors` lists each failed `policyId` and its error. + +### Simulate a request + + + +- `identity` is the identity to test. Structure it the way your policies expect, with `cf` for Access fields and `metadata` for metadata fields. +- `model` and `provider` describe the request. +- `bucketUsage` is optional. It sets simulated spend for a budget, keyed by policy `name`. + +```json +{ + "success": true, + "result": { + "evaluation": { "decision": "check_limits", "buckets": [] }, + "enforcement": { + "allowed": false, + "reason": "limit_exceeded", + "bucket": "", + "spent": 1000, + "limit": 1000, + "policyName": "Everyone spend cap" + }, + "policiesEvaluated": 3 + } +} +``` + +`evaluation.decision` is `no-limit`, `block`, or `check_limits`. `enforcement.allowed` is `true`, or `false` with a `reason` of `blocked` or `limit_exceeded`. + +## Examples + +### Company budget and team budget + +A request from an engineer must pass both budgets: + +```json +[ + { + "name": "Company budget", + "actor": "company:example", + "resource": "*", + "condition": "true", + "action": { + "type": "limit", + "amount": 20000, + "period": "monthly", + "technique": "named-interval" + } + }, + { + "name": "Engineering budget", + "actor": "team:engineering", + "resource": "*", + "condition": "\"engineering\" in cf.user.groups", + "action": { + "type": "limit", + "amount": 10000, + "period": "monthly", + "technique": "named-interval" + } + } +] +``` + +### Individual caps inside a team budget + +The team shares one budget. The second policy stops any one person from using all of it: + +```json +[ + { + "name": "Finance budget", + "actor": "team:finance", + "resource": "*", + "condition": "\"finance\" in cf.user.groups", + "action": { + "type": "limit", + "amount": 10000, + "period": "monthly", + "technique": "named-interval" + } + }, + { + "name": "Finance per-user cap", + "actor": "user:{cf.user.email}", + "resource": "*", + "condition": "\"finance\" in cf.user.groups", + "action": { + "type": "limit", + "amount": 400, + "period": "monthly", + "technique": "named-interval" + } + } +] +``` + +### Higher cap for one user + +Both policies resolve to the same bucket for `alice@example.com`, so the higher amount applies to that user. Other members of the group keep the default cap: + +```json +[ + { + "name": "Research default", + "actor": "user:{cf.user.email}", + "resource": "*", + "condition": "\"research\" in cf.user.groups", + "action": { + "type": "limit", + "amount": 400, + "period": "monthly", + "technique": "named-interval" + } + }, + { + "name": "Alice override", + "actor": "user:{cf.user.email}", + "resource": "*", + "condition": "cf.user.email == \"alice@example.com\"", + "action": { + "type": "limit", + "amount": 600, + "period": "monthly", + "technique": "named-interval" + } + } +] +``` + +### Allow only specific models + +This policy blocks interns from every model except those listed. Interns still need an allow or spend cap policy that covers the listed models. Otherwise, the default deny blocks their requests: + +```json +{ + "name": "Interns allowlist", + "actor": "company:all", + "resource": { "model": ["openai/gpt-5.5-mini", "anthropic/claude-haiku-*"] }, + "condition": "\"interns\" in cf.user.groups", + "action": { "type": "block", "except": true } +} +``` + +## Migrate from spend limits + +Policies replace the spend limits configured in **Settings** > **Spend limits**. Both features are enforced while both are configured, so a request must pass your spend limit rules and your policies. + +The following table maps spend limit rules to policies: + +| Spend limit rule | Policy equivalent | +| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| No dimensions (one shared budget) | **Who**: **Everyone** | +| Metadata dimension, **Split by value** | **Who**: **Actor bucket** with the key in braces, such as `user:{metadata.user_id}` | +| `cf.user_id` metadata dimension, split by value | **Who**: **Actor bucket** set to `user:{cf.user.id}`, or **User** to cap one user by email | +| Metadata dimension, **Filter by value** | A condition, such as `metadata.environment == "production"` | +| Model or provider, **Filter by value** | **Resources**: **Model** or **Provider** | +| Model or provider, **Split by value** | One policy for each model or provider. A policy that lists several models shares one budget across them. | + +To migrate: + + + +1. Add a policy that covers all traffic you want to allow, such as a spend cap or **Allow without a cap** for **Everyone** on **All models and providers**. After you add the first policy, AI Gateway blocks any request that does not match a policy. +2. Recreate each spend limit rule as its policy equivalent from the mapping table. +3. Use [Test policies](#test-policies) to check that the policies allow and block the requests you expect. +4. Delete your spend limit rules in **Settings** > **Spend limits**. + + + +Policies differ from spend limits in the following ways: + +- **Calendar windows only.** Policies reset hourly, daily, weekly, or monthly on UTC boundaries. Refer to [Action](#action). +- **No dynamic route fallbacks.** A spend limit on a model inside a [dynamic route](/ai-gateway/features/routing/dynamic-routing/) can make the route fall back to another model. A policy rejects the whole request instead. + +## Limitations + +- **Cost is estimated.** Spend is based on the [cost AI Gateway calculates](/ai-gateway/observability/costs/) for each request, including any [custom cost](/ai-gateway/configuration/custom-costs/). Requests for models without known pricing do not count toward a budget. Refer to your provider dashboard for exact billing. +- **Budgets can be exceeded slightly.** AI Gateway records the cost of a request after it completes. Concurrent requests can push spend over the limit before enforcement catches up. +- **Cached responses skip spend caps.** Requests served from the [cache](/ai-gateway/features/caching/) are still subject to block policies, but are not checked against spend caps and do not count toward a budget. +- **No dynamic route fallbacks.** AI Gateway evaluates policies once per request, before a [dynamic route](/ai-gateway/features/routing/dynamic-routing/) runs. A policy that blocks or caps a request rejects the whole request instead of falling back to another model in the route. +- **Changes take time to propagate.** A new or updated policy can take up to 15 minutes to apply everywhere. +- **Failures allow traffic.** If AI Gateway cannot evaluate policies or read current spend, it allows the request. The exception is [IdP groups](#idp-groups): if AI Gateway cannot load a user's groups, it rejects the request with a `503`. +- **No remaining-budget headers.** Responses do not include headers that report remaining budget. diff --git a/src/content/docs/ai-gateway/features/routing/dynamic-routing/index.mdx b/src/content/docs/ai-gateway/features/routing/dynamic-routing/index.mdx index 009745cadf3..10f19cef426 100644 --- a/src/content/docs/ai-gateway/features/routing/dynamic-routing/index.mdx +++ b/src/content/docs/ai-gateway/features/routing/dynamic-routing/index.mdx @@ -39,6 +39,12 @@ while making it accessible to both developers and non-technical team members. - **Metadata**: Arbitrary key-value context attached to the request (for example, userId, orgId, plan). You can pass this from your app so rules can reference it. - **Versions**: Each change produces a new draft. Deploy to make it live with instant rollback. +:::note[Budgets without fallbacks] + +To set budgets or control model access for users and teams without falling back to another model, use [policies](/ai-gateway/features/policies/) instead of a **Budget Limit** node. Policies apply to every request on the gateway and reject requests that exceed a budget. Use a **Budget Limit** node when you want requests to fall back to a cheaper model after a budget is used up. + +::: + ## Getting Started :::caution diff --git a/src/content/docs/ai-gateway/features/routing/dynamic-routing/json-configuration.mdx b/src/content/docs/ai-gateway/features/routing/dynamic-routing/json-configuration.mdx index 20559e77b8a..d7828979290 100644 --- a/src/content/docs/ai-gateway/features/routing/dynamic-routing/json-configuration.mdx +++ b/src/content/docs/ai-gateway/features/routing/dynamic-routing/json-configuration.mdx @@ -91,6 +91,8 @@ Routes requests probabilistically across multiple outputs, useful for A/B testin Apply limits based on request metadata. Supports both count-based and cost-based limits. +To enforce budgets without falling back to another model, use [policies](/ai-gateway/features/policies/) instead. Use a cost-based limit in a route when you want requests to fall back to another model after a budget is used up. + - **Inputs**: Request - **Outputs**: - `success`: Forwards request to provided element if request is not rate limited diff --git a/src/content/docs/ai-gateway/features/spend-limits.mdx b/src/content/docs/ai-gateway/features/spend-limits.mdx index 58f8cecc8ce..3808ba6130b 100644 --- a/src/content/docs/ai-gateway/features/spend-limits.mdx +++ b/src/content/docs/ai-gateway/features/spend-limits.mdx @@ -4,13 +4,19 @@ title: Spend limits description: Set cost-based budgets on your AI Gateway to control spending by model, provider, or custom metadata dimensions like user or team. sidebar: order: 4 - badge: Beta + badge: Deprecated products: - ai-gateway --- import { Steps } from "~/components"; +:::caution[Deprecated] + +Spend limits are deprecated. [Policies](/ai-gateway/features/policies/) replace spend limits, and existing spend limit rules continue to work until you migrate. Policies support the same metadata-based budgets, and can also use the verified identity of the caller and block or allow access to models. To move your rules, refer to [Migrate from spend limits](/ai-gateway/features/policies/#migrate-from-spend-limits). + +::: + Spend limits let you set cost-based budgets on your AI Gateway. When cumulative spend reaches the limit within a time window, AI Gateway blocks further requests with a `429` response until the window resets. Unlike [rate limiting](/ai-gateway/features/rate-limiting/), which caps the number of requests, spend limits track actual dollar cost per request based on model pricing. You can scope limits to any combination of model, provider, or [custom metadata](/ai-gateway/observability/custom-metadata/) dimensions like user ID, team, or application. @@ -37,7 +43,7 @@ Each rule can be scoped by one or more dimensions: Each dimension can be configured in one of two modes: -| Mode | Behavior | Example | +| Mode | Behavior | Example | | ------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | **Split by value** | Each distinct value gets its own independent budget bucket. | For example, if you pass in `agent_id`, splitting by `agent_id` gives every agent its own budget. | | **Filter by value** | The rule applies only when the dimension equals a specific value. | For example, if you pass in `agent_id`, filtering `agent_id` to `agent_42` limits only that agent's requests. | @@ -48,13 +54,13 @@ If a dimension is not configured on a rule, all values share one budget bucket. Given a request with model `openai/gpt-5.5` and an `agent_id` metadata value of `agent_42`: -| Scenario | Dimensions | Budget bucket | -| -------------------------- | ---------------------------------------------------------------- | ---------------------------------------------- | -| Global budget for everyone | None | One shared bucket | -| Per-agent budget | `agent_id` metadata: split by value | Separate bucket per agent | -| Per-provider, per-agent | `agent_id` metadata: split by value, `provider`: split by value | Separate bucket per agent+provider combination | -| Specific model only | `model`: filter by value `openai/gpt-5.5` | Only applies to `openai/gpt-5.5` requests | -| Per-agent, per-model | `agent_id` metadata: split by value, `model`: split by value | Separate bucket per agent+model combination | +| Scenario | Dimensions | Budget bucket | +| -------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | +| Global budget for everyone | None | One shared bucket | +| Per-agent budget | `agent_id` metadata: split by value | Separate bucket per agent | +| Per-provider, per-agent | `agent_id` metadata: split by value, `provider`: split by value | Separate bucket per agent+provider combination | +| Specific model only | `model`: filter by value `openai/gpt-5.5` | Only applies to `openai/gpt-5.5` requests | +| Per-agent, per-model | `agent_id` metadata: split by value, `model`: split by value | Separate bucket per agent+model combination | ## Configure spend limits diff --git a/src/content/docs/ai-gateway/features/unified-billing.mdx b/src/content/docs/ai-gateway/features/unified-billing.mdx index 7f6433a22ba..9cd02ee9892 100644 --- a/src/content/docs/ai-gateway/features/unified-billing.mdx +++ b/src/content/docs/ai-gateway/features/unified-billing.mdx @@ -197,7 +197,7 @@ The HTTP API supports the following providers: ### Spend limits -Set [spend limit rules](/ai-gateway/features/spend-limits/) on individual gateways to cap spend, scoped by model, provider, or custom metadata dimensions like user or team. +Set [policies](/ai-gateway/features/policies/) on individual gateways to cap spend by user, email domain, model, provider, or custom metadata like team. Policies replace [spend limit rules](/ai-gateway/features/spend-limits/). ### Zero Data Retention (ZDR)