skip to content

In Cloudflare AI Gateway, how does an application route its existing model-provider calls through a gateway, and what does the gateway add?

level: juniorimportance: should knowfreq 30%

answer

  1. a proxy in front of providers
  2. swap the base URL, keep the body
  3. account ID and gateway ID in the path
  4. the api.cloudflare.com ai/v1 endpoints
  5. settings live per gateway

basics

~10 s

Point the provider SDK's base URL at gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/{provider}, or use the newer REST API on api.cloudflare.com. Each call is then logged and can be cached, rate limited and retried without rewriting the request body.

solid answer

~40 s

AI Gateway is a proxy Cloudflare runs between your code and model providers. The provider-native way swaps the provider's base URL for `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai` (or `/anthropic` and the other listed providers) and keeps that provider's own request format. For new integrations Cloudflare recommends the REST API at `api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1/chat/completions` (also `/ai/run`, `/ai/v1/responses` and `/ai/v1/messages`), which takes `author/model` names such as `openai/gpt-4.1` and picks a gateway with the `cf-aig-gateway-id` header. A gateway named `default` is created on the first authenticated request. Per gateway you then get logs with tokens, cost and duration, analytics, optional caching, rate limiting and retries, plus per-request `cf-aig-*` headers such as `cf-aig-metadata` to tag a call with a user or team.

code

bash · 6 lines
bash
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "cf-aig-gateway-id: support-assistant" \
  --header 'cf-aig-metadata: {"team": "support", "user": 4182}' \
  --header "Content-Type: application/json" \
  --data '{"model": "openai/gpt-4.1-mini", "messages": [{"role": "user", "content": "Summarise our refund policy."}]}'

go deeper

for a junior

Recall the base-URL swap to gateway.ai.cloudflare.com with account and gateway IDs in the path, and name what the gateway adds: logs, caching, rate limiting and retries.

for a middle

Explain the two ways in, provider-native URLs versus the REST API with author/model names and cf-aig-gateway-id, and how the default gateway is created on first authenticated use.

for a senior

Show you can trim and tag logs deliberately: cf-aig-metadata limits, reserved cf. keys, and when cf-aig-collect-log-payload is the right privacy control.

for a principal

Frame the gateway as the single control point for model traffic, and say how many gateways a team should run and which settings each one owns.

## What AI Gateway is **AI Gateway** is a Cloudflare product that sits between an application and the **model providers** it calls (OpenAI, Anthropic, Google, Amazon Bedrock, Workers AI and the rest of its provider list). Every request goes to a Cloudflare endpoint first; the gateway records it, applies the settings of the **gateway** it names, forwards it to the provider and relays the answer. A *gateway* is a named configuration inside a Cloudflare account: it carries its own choices for logging, caching, rate limiting, retries, Guardrails and DLP. Several services can share one gateway, or each can have its own. The point is one place to see and control model traffic that otherwise leaves from many services with many provider keys. ## Two ways in | Way in | URL shape | Request format | Model name | | --- | --- | --- | --- | | Provider-native | `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/chat/completions` | The provider's own | The provider's own, such as `gpt-4o-mini` | | REST API | `https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1/chat/completions` | OpenAI chat completions (other endpoints for other shapes) | `author/model`, such as `openai/gpt-4.1`, or `@cf/...` for Workers AI | - **Provider-native** is a base-URL swap: an OpenAI SDK keeps its calls and only its `baseURL` changes to the gateway path ending in `/openai`; an Anthropic SDK points at the path ending in `/anthropic`. The body stays exactly what the provider expects. - The **REST API** (since May 2026) offers four endpoints: `/ai/run` for every model and modality, `/ai/v1/chat/completions` and `/ai/v1/responses` for OpenAI-shaped clients, and `/ai/v1/messages` for Anthropic-shaped ones. It authenticates with a Cloudflare API token in `Authorization`, and third-party models on it are paid through Unified Billing unless a stored provider key applies. - The older `/compat/chat/completions` endpoint on `gateway.ai.cloudflare.com` still works for existing integrations but is **deprecated for single-model calls**; new code uses the REST API. - From a Worker, the AI binding's `env.AI.run()` with a `gateway` option reaches the same gateway; that path belongs with the Workers AI material. ## The default gateway and picking one 1. On the REST API, third-party model requests go through the account's gateway named `default` unless the `cf-aig-gateway-id` header names another; Workers AI (`@cf/`) requests always need that header. 2. If no gateway called `default` exists, AI Gateway **creates it on the first authenticated request**, with authentication and logging on, caching off and rate limiting off. 3. Any other gateway ID must be created first, in the dashboard (**AI** > **AI Gateway** > **Create Gateway**) or the API. An account holds 10 gateways on the Free plan and 20 on a paid plan. ## What the gateway adds - **Logs**: each entry can hold the prompt, the response, provider, model, status, token usage, cost, duration and user agent. Logging is on by default per gateway. - **Analytics**: requests, tokens, cost, errors and the share of cached responses, per gateway. - **Caching**: off by default; when on, identical requests are answered from Cloudflare's cache without reaching the provider. - **Rate limiting**: a requests-per-period cap for the gateway, answered with `429 Too Many Requests` when exceeded. - **Retries and timeouts**: gateway-level retries for upstream failures, overridable per request with `cf-aig-max-attempts`, `cf-aig-retry-delay`, `cf-aig-backoff` and `cf-aig-request-timeout`. - **Guardrails, DLP and spend limits**: content checks on prompts and responses, data-loss scanning and dollar budgets, each configured on the gateway. ## Tagging and trimming logs `cf-aig-metadata` takes a JSON object of up to **five** entries whose values are strings, numbers or booleans (objects are not supported); entries past the fifth are ignored. Keys starting with `cf.` are reserved for Cloudflare and stripped. Tagging a call with a user or team ID is what later lets logs, analytics and spend limits be cut by that value. Two headers trim what is stored. `cf-aig-collect-log: false` drops the whole log entry for that request (or, on a gateway with logging off, `true` keeps one). `cf-aig-collect-log-payload: false` keeps the metadata entry but skips the request and response bodies, which is how a team keeps cost visibility without storing prompts that contain personal data. ## First-day mistakes 1. Inventing a gateway ID in the URL and expecting it to appear: only `default` is created on demand. 2. Mixing up the two credentials: on a provider-native URL that sends the provider's key in `Authorization`, the gateway token goes in `cf-aig-authorization`. 3. Assuming the gateway caches by default: caching must be turned on per gateway or per request. 4. Passing nested objects in `cf-aig-metadata`: only flat string, number and boolean values are saved.

  • What does the gateway ID in an AI Gateway URL refer to, and what if it names a gateway that does not exist?
    It is the name of a gateway in your account, and that gateway's settings for caching, logging, rate limiting and Guardrails apply to the call. Only the ID `default` is created on the first authenticated request; any other ID must be created first in the dashboard or through the API.
  • How do you keep prompts that contain personal data out of AI Gateway logs while still tracking cost?
    Send `cf-aig-collect-log-payload: false`. The log entry keeps metadata such as model, provider, status, tokens, cost and duration, but the request and response bodies are not stored. `cf-aig-collect-log: false` would drop the whole entry, metadata included, and it wins over the payload header.

  • AI Gateway requires rewriting every request into a Cloudflare-specific body format.
  • Any gateway ID written into the URL is created automatically on first use.
  • AI Gateway only fronts Workers AI models, not external providers.
  • cf-aig-metadata accepts nested JSON objects as tag values.
  • Setting cf-aig-collect-log-payload to false drops the whole log entry.

Assumes Cloudflare's platform as of 2026-10-10: the REST API on api.cloudflare.com arrived in May 2026, the default gateway is auto-created since March 2026, and /compat/chat/completions is deprecated for single-model calls.