# AI Gateway

One Responses API for configured model providers: catalog model IDs, Ferrite tokens or inference keys, spend caps, calendar budgets, rate limits, BYOK, explicit fallback, streaming, stored responses, and usage evidence.

The platform AI gateway serves a supported subset of the Responses API from each installation's resident inference service (`https://ai.ferrite.cloud` on Ferrite Cloud). Your applications and external clients call `POST /v1/responses` and `GET /v1/models` against that single endpoint; the gateway owns the provider credentials, model catalog, routing, retry budget, outbound egress, and account-attributed usage ledger. Compatible clients can create responses over HTTP, receive SSE streams, and upgrade to the supported WebSocket event surface for the models configured on the installation.

Platform-funded model calls draw on the same prepaid balance as your applications' hosting and deploys. Before dispatching a call, the gateway reserves a pessimistic cost estimate; if your balance cannot cover it, the gateway returns `402 insufficient_credit` and sends nothing to a provider. Calls made with your account's own sealed provider credential (BYOK) draw no Ferrite credit. On Ferrite Cloud, the gateway serves calls only after your account has sealed its own provider key; see [Where it runs](#where-it-runs) and [BYOK](#byok).

## Where it runs

The platform runs the AI gateway as a resident service beside your applications, so you never deploy a gateway app yourself. Ferrite Cloud serves it at `https://ai.ferrite.cloud`; other installations publish their own URL, and clients must use that published address. Which providers and models answer, and whether platform-funded calls are enabled or only BYOK calls are served, depends on each installation's configuration. Query `GET /gw/v1/catalog?view=availability` with your credential before building against a route.

On Ferrite Cloud, the gateway runs without platform provider credentials, so calls are served only once your account seals its own provider key under [BYOK](#byok). Those calls are metered at catalog prices, count against your inference key's cap, and charge no Ferrite credit.

## Call it

Authenticate with either a Ferrite bearer token or an inference key. Both credentials resolve directly to your account; you never pass an account or tenant field in the request:

| Credential | Where it comes from | Use it for |
| --- | --- | --- |
| Ferrite bearer token | Account or app token used by the `ferrite` CLI and MCP | Model calls; key, budget, ledger, and BYOK administration when account-scoped |
| Inference key `<key_id>.<secret>` | `POST /gw/v1/keys`, minted for your account | Model calls from an app or harness, with optional spend caps and rate limits |

```bash
curl -s "$GATEWAY/v1/responses" \
  -H "authorization: Bearer $INFERENCE_KEY" -H 'content-type: application/json' \
  -d '{
    "model": "anthropic/claude-sonnet-4-6",
    "instructions": "Answer briefly.",
    "input": "What is Ferrite?",
    "max_output_tokens": 300
  }'
```

The request body follows the Responses API create schema: `model`, `input`, `instructions`, `tools`, `tool_choice`, `previous_response_id`, `reasoning` (`effort`, `summary`), `text.format` for structured output, `metadata`, `store`, `stream`, `background`, `max_output_tokens`, `temperature`, `top_p`, and the remaining reference fields. Unknown fields pass through to OpenAI models. For Anthropic models, the gateway translates supported request and response fields between the Responses API and Anthropic's Messages API, including thinking signatures sealed in an `encrypted_content` envelope.

You can pass the credential as `Authorization: Bearer`, as `x-api-key`, or as a top-level `key` field in the JSON body (which the gateway strips before decoding the request). Stored responses, conversations, and files are isolated by account.

### Structured output by provider

OpenAI routes support both `text.format.type=json_object` and `json_schema`. Anthropic routes require `json_schema` with an explicit schema and refuse `json_object` with HTTP 400 `unsupported_text_format` before provider dispatch or credit reservation, including on background requests, because the gateway cannot infer required properties from a prompt.

To request a JSON object containing a `word` string from an Anthropic model:

```json
"text": {
  "format": {
    "type": "json_schema",
    "name": "answer",
    "schema": {
      "type": "object",
      "properties": { "word": { "type": "string" } },
      "required": ["word"],
      "additionalProperties": false
    }
  }
}
```

Every object type in an Anthropic schema must set `additionalProperties: false`. Refer to [Anthropic's supported schema subset](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) for additional constraints. The gateway forwards your schema directly, so an unsupported schema can still be rejected by the provider. The catalog's `supports` flags cover tools, vision, files, and prompt caching, and do not report `text.format` compatibility.

### What a call costs

Completed responses carry the standard Responses token counts inside `usage`, alongside two gateway fields:

```json
"usage": {
  "input_tokens": 42, "output_tokens": 31, "total_tokens": 73,
  "billing": "platform-credit",
  "cost_micros": 591
}
```

- `billing` reports `platform-credit` when your account's Ferrite credit funded the call, or `byok` when your own sealed provider credential ran the call with no Ferrite credit debit.
- `cost_micros` reports the catalog cost in USD micros (1,000,000 micros equals one dollar), calculated from the served model's catalog prices and reported tokens. This is the amount settled against your balance or, under BYOK, counted against your key cap.

Per-token rates come from the priced catalog at `GET /gw/v1/catalog`; the Google and Bedrock entries also list the provider's pricing page and the date it was checked. Every operation records the `pricing_version` active when it ran, so later catalog updates never rewrite past charges. Read rates from your installation's catalog at runtime instead of hardcoding prices in your app.

Platform-funded inference draws from the same prepaid balance as hosting and deploys. Before dispatching a call, the gateway reserves a pessimistic estimate; if the balance falls short, it returns `402` with code `insufficient_credit` and `{ "balance_micros", "estimate_micros" }`, without contacting a provider. Once the call completes, the reservation settles to `cost_micros`. A failure that could not have executed provider work refunds the reservation. If provider work may have run while terminal usage is unavailable, the ledger retains the disclosed estimate and marks `usage_unknown` instead of inventing token counts, and the inference key's spend and usage log keep that same monetary estimate. Under BYOK, that estimate counts against the key's provider-spend cap while platform credit stays untouched.

### Streaming

Set `"stream": true` to receive standard Responses SSE events (`response.created`, `response.in_progress`, `response.output_item.added`, `response.output_text.delta`, `response.function_call_arguments.delta`, `response.reasoning_summary_text.delta`, `response.completed`, `response.failed`, `response.incomplete`), each numbered with `sequence_number`. Call `GET /v1/responses/{id}?stream=true&starting_after=N` to resume a stored stream after a given sequence number. The gateway holds the terminal event until the durable response write succeeds, so a caller never receives a completion event before `GET /v1/responses/{id}` can return the stored response.

`/v1/responses` also accepts a WebSocket upgrade. Send `response.create` client events with the create fields at the top level; server frames follow the SSE event vocabulary, and failures arrive as `error` events.

### Stored responses and chaining

Stored responses remain available for 30 days within your account. Fetch a response with `GET /v1/responses/{id}`, inspect its resolved inputs with `GET /v1/responses/{id}/input_items`, or remove it with `DELETE /v1/responses/{id}`. Passing `previous_response_id` expands the predecessor's retained input server-side, so multi-turn flows require no client-maintained transcript. `POST /v1/responses/input_tokens` returns a byte-based estimate documented as an estimate only.

## Models

`GET /v1/models` returns the catalog in OpenAI's format, and `GET /gw/v1/catalog` returns the priced catalog plus the installation's default model. Each entry lists its context window, maximum output tokens, supported modalities, capability flags, and USD-micros-per-million-token rates for input, output, cache read, cache write, and one-hour cache write (`cache_write_1h`), along with a `long_prompt` tier where providers price long prompts higher.

Model IDs use `provider/model` across the API. The catalog defines four providers behind bounded adapters:

| Provider | Adapter | Example IDs |
| --- | --- | --- |
| OpenAI | Responses passthrough | `openai/gpt-5.6-luna`, `openai/gpt-5.5` |
| Anthropic | Translated to and from the Messages API | `anthropic/claude-sonnet-4-6`, `anthropic/claude-haiku-4-5` |
| Google Gemini | Native adapter, qualified offline only | `google/gemini-4-carbon`, `google/gemini-4-argon`, `google/gemini-4-hydrogen` |
| Amazon Bedrock Nova | Native adapter, qualified offline only | `bedrock/nova-2-lite-us`, `bedrock/nova-2-lite-eu`, `bedrock/nova-2-lite-global-us` |

Every Bedrock model ID pins its source region and inference profile; global routing is never applied as an implicit fallback. The catalog marks Google and Bedrock entries `offline-contract-only`.

Appearing in the catalog does not guarantee that your installation or BYOK credential can reach a model. Query `GET /gw/v1/catalog?view=availability` with your credential to read the `available` list of models your account currently has a usable credential for on that installation. That list is a point-in-time snapshot, and each call is still validated on dispatch.

`POST /gw/v1/tokens/count` works for Google models only; it calls Google's tokenizer directly without generating output or debiting credit. Like the byte-based estimate from `POST /v1/responses/input_tokens`, its count does not bound what a subsequent generation call will cost.

A bare suffix such as `claude-sonnet-4-6` resolves when exactly one catalog entry ends in it. An ambiguous bare ID returns `bad_model`, and an unknown ID returns `model_not_found`. Passing an empty model or the literal `agent-default` selects the installation's configured default model. Operators can override a model's route or disable a model (`model_disabled`).

## Keys, caps and rate limits

Mint an inference key when you want an app or test harness to call models under its own spend cap, rate limit, and usage tags:

```bash
# mint a capped, rate-limited key with an account-scoped Ferrite token
curl -s -X POST "$GATEWAY/gw/v1/keys" -H "authorization: Bearer $FERRITE_TOKEN" -H 'content-type: application/json' \
  -d '{"key_id":"support","secret_sha256":"<sha256 of the secret>","spend_cap_micros":50000000,"rate_limit":{"requests":600,"window_s":60},"tags":["support"]}'
```

The new key binds automatically to the minting token's account and cannot name another account in the request body. Each record stores `key_id`, `secret_sha256` (the gateway keeps only the SHA-256 fingerprint), `enabled`, `spend_cap_micros`, `rate_limit` (`requests` per `window_s`), and `tags` copied onto every usage record. Callers present `<key_id>.<secret>`. App-scoped tokens can run model calls, while key creation and management require an account-scoped Ferrite token. `GET /gw/v1/keys` lists only your account's keys. Because `key_id` shares a single namespace across accounts, attempting to claim an ID already held by another account returns `404` (`key_id_unavailable`); pick a different ID.

To create, rotate, or disable keys with optimistic concurrency, use the Dashboard's **Keys and providers** section or `POST /gw/v1/keys/manage` with `action` set to `create`, `rotate`, or `disable`. Rotating or disabling a key requires its current `expected_revision`.

A key's `spend_cap_micros` enforces a fixed 30-day spend limit alongside your account balance. Exceeding the cap returns `429` with code `insufficient_quota` and a message naming the cap; exceeding the rate limit returns `429` with code `rate_limit_exceeded` and the retry interval. The gateway enforces whichever limit is lower: a spend cap never authorizes spend past your balance, and your balance never overrides a cap. Usage and spend reads remain accessible after a key hits its cap.

An inference key is rate-limited only when its record defines `rate_limit`. A bare Ferrite token (without an inference key) is capped at 600 requests per minute shared across the account for model calls and read endpoints alike, and returns `429 rate_limit_exceeded` past that threshold. Bare tokens carry no key spend cap; their spend is bounded by your account balance and any [calendar budget](#calendar-budgets).

### BYOK

Ferrite Cloud's AI gateway resolves provider credentials in strict priority order: a per-request key (`x-ferrite-provider-key`), then your account's sealed BYOK credential, and finally a configured platform credential only when neither is present and `x-ferrite-byok-only` is not set. Setting `x-ferrite-byok-only: request` (or `true`) guarantees that the gateway never falls back to a shared platform credential. Choose the BYOK pattern that matches your application's ownership model:

#### Account-level BYOK (single-tenant apps)

If your startup or team deploys an application that runs models under your own provider account, seal your Anthropic, OpenAI, or Google Gemini credential once at the gateway using `PUT /gw/v1/byok/{provider}` with an account-scoped Ferrite token:

```bash
curl -s -X PUT "$GATEWAY/gw/v1/byok/anthropic" \
  -H "authorization: Bearer $FERRITE_TOKEN" \
  -H "content-type: application/json" \
  -d '{"api_key":"'"$ANTHROPIC_API_KEY"'"}'
```

The gateway stores the credential sealed and never returns it. Whenever your account holds a BYOK credential for the resolved provider, requests use it and debit no Ferrite credit (`usage.billing` is `byok`). BYOK calls still count against your inference key cap at catalog prices, write usage records, and follow rate limits. Provider credentials are never accepted inside a request body.

#### Per-user BYOK (multi-user apps)

If your application lets each signed-in user bring their own Anthropic, OpenAI, or Gemini API key — without ever calling providers directly from the app — route both key verification and inference strictly through the AI gateway:

1. **Discover BYOK-eligible routes** from `GET /gw/v1/catalog?view=availability`. In addition to `available`, the catalog includes `byok_available` (enabled `anthropic`, `openai`, and `google` routes usable with a per-request key even when zero account-level keys are sealed) and `protocols.per_request_byok_v1: true` / `protocols.byok_verify_v1: true`.
2. **Validate keys live through the gateway** before saving them by posting to `POST /gw/v1/byok/verify`:

```bash
curl -s -X POST "$GATEWAY/gw/v1/byok/verify" \
  -H "authorization: Bearer $INFERENCE_KEY" \
  -H "content-type: application/json" \
  -d '{"provider":"anthropic","api_key":"'"$USER_ANTHROPIC_KEY"'"}'
```

The gateway checks the key live against the provider's model listing endpoint over its own egress, intersects the returned models with the enabled gateway catalog, and responds with `{ "valid": true, "provider": "anthropic", "models": [...], "matched_exact": true, "upstream_model_count": N }` (or `{ "valid": false, "code": "invalid_api_key", "error": "...", "models": [] }`). It never stores, logs, or echoes the key, and enforces a dedicated 30 req/min per-account verification rate limit.

3. **Pass the user's key per request** on `/v1/responses` or `/v1/messages` using these request headers:

| Header | Purpose |
| --- | --- |
| `x-ferrite-provider-key` | The end user's verified provider API key for this request (header-safe ASCII, 1–1024 bytes, single instance only) |
| `x-ferrite-provider-key-provider` | Optional provider binding (`anthropic`, `openai`, or `google`); refuses dispatch with `400 bad_provider_key_provider` if the resolved route uses another provider |
| `x-ferrite-byok-only` | Set to `request` to forbid both platform-key and account-sealed BYOK fallback, or `true` to forbid platform-key fallback only |

Every malformed, control-bearing, oversized, or duplicated BYOK header fails closed with `400` (`bad_provider_key` / `bad_provider_key_provider` / `bad_byok_mode`) before dispatch. Cross-provider `ferrite_routing` fallbacks (`400 bad_routing_byok`), `ferrite_cache` (`400 bad_cache_byok`), and tenant-shared gateway state (`previous_response_id`, `conversation`, `item_reference` -> `400 bad_byok_state`) are refused when per-request BYOK is used, and the SHA-256 hash of `x-ferrite-provider-key`, provider binding, and `x-ferrite-byok-only` mode are mixed into the idempotency request digest so two users' keys never cross-replay cached outcomes.

4. **Reuse the open-source `byok-vault` package** to encrypt keys at rest per user in your application's `Store` and call `/gw/v1/byok/verify` without writing boilerplate cryptography:

```bash
ferrite add byok-vault
```

Add `https://ai.ferrite.cloud/gw/v1/byok/verify` alongside `/v1/responses` (and `/v1/messages` if using native Anthropic) in your `gateway-egress` destinations in `ferrite.json`. Your application never needs an egress grant to `api.anthropic.com`, `api.openai.com`, or `generativelanguage.googleapis.com`.

### Calendar budgets

A calendar budget caps spend in USD micros over one UTC day or one UTC month. Read or replace budgets in the Dashboard's **Budgets** section or through `GET` and `PUT /gw/v1/budgets` using an account-scoped token. Budgets can target the whole account (`{ "kind": "account" }`), one inference key (`{ "kind": "key", "id": "support" }`), or one BYOK credential (`{ "kind": "provider_credential", "id": "byok:google" }`). Every matching budget must admit a call; exceeding any budget returns `429` with code `budget_exceeded`.

```json
{
  "revision": "0",
  "policies": [
    {
      "id": "support-month",
      "scope": { "kind": "key", "id": "support" },
      "period": "month",
      "limit_micros": "50000000"
    }
  ]
}
```

`PUT /gw/v1/budgets` replaces the entire policy list, so fetch the current `revision` with `GET` first and include every policy you want to retain; a stale revision conflicts and changes nothing. Both amounts and revisions are decimal strings. Admission reserves against the model's full context and output limits, so a tight budget can refuse a request even when its actual token usage would be small. Rotating a key or provider credential does not reset its accumulated spend. Calendar budgets operate independently from a key's older fixed 30-day `spend_cap_micros`.

## Retries and explicit fallback

Standard requests execute on the selected model route within bounded attempt and time limits. When you want an ordered fallback chain, pass one to three distinct catalog model IDs (preferably canonical `provider/model` IDs) in `ferrite_routing`:

```json
{
  "model": "openai/gpt-5.6-luna",
  "input": "Summarize this message.",
  "max_output_tokens": 300,
  "ferrite_routing": {
    "fallbacks": ["anthropic/claude-haiku-4-5"],
    "max_attempts": 2,
    "retry_budget_ms": 10000
  }
}
```

A request can name at most four candidates including the primary model. The gateway validates all candidates before dispatch, requires every candidate to share the same billing source, and executes at most one physical attempt per candidate in fixed order. Optional `max_attempts` must be at least the candidate count and at most 8; `retry_budget_ms` accepts 1 to 60,000 ms. The gateway rejects unknown routing fields, unknown or ambiguous model IDs, duplicate routes, mixed BYOK and platform billing sources, combinations with `ferrite_cache`, and fallback on compaction. A budget refusal never advances to another provider.

Advancing to the next candidate requires four conditions: a retryable failure, zero exposed output, proof that no provider work occurred, and confirmed zero settlement. An HTTP 429 admission refusal can satisfy that contract. HTTP 408, 499, server errors, Bedrock 424, unknown status codes, and ambiguous transport or audit failures retain possible-work liability and neither retry nor advance. Absence of visible output alone never proves a call was free.

Each fallback attempt records its own financial operation and tariff under one parent that owns the public response, history, and idempotency outcome. An unresolved child or lost settlement acknowledgement halts further execution. Retrying an `Idempotency-Key` replays the retained outcome or reports the unresolved claim; it never grants a fresh execution after a crash.

## Idempotency and bounds

Any non-GET request carrying an `Idempotency-Key` is admitted once per account and credential, bound to a digest of the account, HTTP method, path, and normalized request body (model, input, all parameters, and stream flag). Reusing the same key with a different request returns `409` (`idempotency_key_reused`) before dispatch or billing. An identical request arriving while the first is still running waits up to 20 seconds for the outcome and then returns `409` (`idempotency_busy`). Completed responses replay for 15 minutes with zero additional billing; streamed responses replay up to 2,000 events or 512 KiB, after which only the terminal event replays. A request that fails before provider dispatch releases the key for immediate retry; a failure after dispatch became possible (or under fallback routing) records its outcome or leaves an unresolved claim (`409 idempotency_unresolved`) rather than granting a fresh execution. Malformed keys (longer than 256 characters, containing control characters, empty, or repeated headers) fail with `400` (`bad_idempotency_key`) and are never ignored. Over WebSocket, `response.create` accepts a string `idempotency_key` field under the same rules. Identical keys from different accounts never collide.

Hard size, concurrency, and timeout limits apply to every request:

- Prompts cap at 1 MB (`prompt_too_large`), attachments at 12 MiB (`attachments_too_large`), streamed replies at 8 MiB, and total request bodies at 16 MiB. Empty prompts are refused.
- Overall request deadline is 330 seconds. Each provider call allows 10 seconds to the response head and 30 seconds of stream silence; exceeding stream silence fails as a possible-work error with no retry and retains the estimate.
- Each gateway replica runs at most 4 concurrent background responses.
- Provider `4xx` responses other than `401`, `403`, and `429` return with their status and sanitized provider message; provider `401` and `403` errors map to `502` because they indicate a rejected upstream credential.
- Every reply includes an `x-ferrite-request-id` header matching the usage record's correlation ID.

Errors follow the Responses error envelope with `error.type` (`invalid_request_error`, `authentication_error`, `rate_limit_error`, `not_found_error`, and similar), `error.code`, `error.message`, and the matching HTTP status. Supporting create, retrieve, stream, and delete does not mean every OpenAI sub-operation is implemented; handle these explicit refusals without retrying them as transient failures:

| Operation | Refusal |
| --- | --- |
| Paginate a response's `input_items` | `pagination_unimplemented` |
| Compact an individual response | `compaction_unimplemented` |
| Compact with a non-OpenAI model | `compaction_unimplemented` |

`DELETE /v1/files/{id}` and `DELETE /v1/conversations/{id}` remove the object and return OpenAI's deletion payload, or `404` (`file_not_found`, `conversation_not_found`) if the ID does not belong to your account. Items inside a deleted conversation expire according to retention.

### Other routes

Alongside creating, retrieving, streaming, and deleting responses, the gateway serves:

| Route | Behavior |
| --- | --- |
| `POST /v1/responses/{id}/cancel` | Cancel a background response |
| `POST /v1/responses/compact` | Compaction, for OpenAI models |
| `POST /v1/files` · `GET /v1/files` | Multipart upload (at most 8 MiB per file, retained 30 days unless `expires_after` specifies between 1 hour and 30 days); list files |
| `GET /v1/files/{id}` · `GET /v1/files/{id}/content` | Read file metadata; download file content |
| `POST /v1/conversations` · `GET`, `POST`, `DELETE /v1/conversations/{id}` | Create (at most 32 initial items), read, update metadata, delete |
| `GET`, `POST /v1/conversations/{id}/items` | List conversation items; append at most 32 items |
| `POST /acp` | Agent Client Protocol over JSON-RPC (`accept: text/event-stream` for session updates); at most 32 messages per batch |

### Ferrite request options

Create requests accept two Ferrite-namespaced fields:

- `ferrite_tags` takes at most 16 tags of 1 to 64 characters matching `[A-Za-z0-9_.:/-]` (invalid values return `400 bad_json`). The gateway stores them on the usage record as `request_tags`, separate from the inference key's `tags`.
- `ferrite_cache` (`{ "ttl_s": N }`, bounded from 10 seconds to 24 hours) serves an identical buffered request from your account out of cache with no provider call and no charge. It is refused alongside `stream`, `background`, `previous_response_id`, `conversation`, or an explicit `store: true`.

If your account's platform spending limit blocks a call before your balance or gateway budgets do, the gateway returns `402` with code `spending_limit_exceeded` and `{ "remaining_micros", "estimate_micros" }`.

## Usage evidence

Every call writes a usage record retained for 90 days containing the timestamp, correlation ID, credential and account, requested and served model, provider, endpoint, HTTP status, error code, token counts (input, output, cache read, cache write, one-hour cache write), web-search calls, `cost_micros`, latency, time to first token, cache hits, attempts, key `tags`, and `request_tags` from `ferrite_tags`. Who paid appears on the response's `usage.billing` field and is not duplicated on the stored usage record.

| Surface | Who | Returns |
| --- | --- | --- |
| `GET /gw/v1/usage?since_ms=&until_ms=&limit=` | Any credential (own usage) | Totals and records (`limit` defaults to 100) |
| `GET /gw/v1/logs` | Any credential (own usage) | Unaggregated usage records |
| `GET /gw/v1/spend` | Any credential (own key) | Current period spend and cap |
| `GET /gw/v1/ledger?limit=&cursor=` · `GET /gw/v1/ledger/{response_id}` | Account-scoped Ferrite token | Account inference operations across all credentials: estimate, charged amount, `byok`, `usage_unknown`, and pricing basis (`pricing_version` and applied prices); unknown ID returns `404 operation_not_found` |
| `GET /gw/v1/keys` · `POST /gw/v1/keys` | Account-scoped Ferrite token | Account key records (fingerprints only) |
| `POST /gw/v1/keys/manage` | Account-scoped Ferrite token | Create, rotate, or disable a key with a revision check |
| `GET`, `PUT /gw/v1/budgets` | Account-scoped Ferrite token | Read or replace account calendar budgets |
| `PUT`, `GET`, `DELETE /gw/v1/byok/{provider}` | Account-scoped Ferrite token | Seal, probe, or delete an account-level BYOK provider credential |
| `POST /gw/v1/byok/verify` | Any credential | Validate an Anthropic, OpenAI, or Google API key live through the gateway and return its matching catalog model IDs without storing the key |
| `GET /healthz` | Unauthenticated | Liveness probe |

Each credential reads only its own usage records; query with a specific inference key to read that key's usage (`key=` is reserved for operators). The ledger returns newest operations first, 50 per page by default up to 500, with `next_cursor` for pagination.

Application hosting usage and AI gateway attribution stay separate; see [Analytics & Usage](/developers/analytics/).

## Why one gateway

Giving every application its own provider keys and direct provider connections multiplies the places a key can leak and forces every manifest to repeat provider egress grants. Concentrating provider credentials inside one gateway lets each app call models with a revocable, capped, metered account credential while keeping provider hosts confined to the gateway's own egress allowlist.

## Choose an integration

When you build on the agent SDK, every model call travels over the application's `gateway-egress` handle to `agents-gateway-url` with the credential in `agents-gateway-key`. Point that handle at the AI gateway with an inference key or Ferrite bearer token, and no provider credential ever enters the app: calls charge your account's Ferrite credit or sealed BYOK credential. Provider API keys are rejected by the gateway.

The checked-in `ferrite-agents` reference manifest takes the direct OpenAI path instead: its `gateway-egress` grants `https://api.openai.com/v1/` and `agents-gateway-key` holds an OpenAI API key billed by OpenAI. See [ferrite-agents app](/developers/agents-app/) for switching it to the AI gateway.

If you need a provider or model outside the catalog, or a client tied to Chat Completions or Anthropic's Messages API, your app can call that provider directly using its own egress grant and application secret as covered in [Secrets & Egress](/developers/secrets-egress/). Direct calls bill the provider directly and do not appear in gateway usage logs or ledgers. Moving a direct client onto the AI gateway requires changing three things together: the wire format (Responses API only), the egress destination, and the credential. Updating the base URL alone will fail.

## Call it from another app

Because the gateway is an HTTP service, another Ferrite app calls it through a declared egress grant in `ferrite.json` and two secrets read by the agent SDK:

```json filename="ferrite.json (excerpt)"
{
  "applications": [{
    "egress": [
      { "handle": "gateway-egress", "destinations": ["https://<the gateway's host>/v1/"] }
    ]
  }]
}
```

Although egress destinations normally cannot target the platform's own domain, installations with a configured resident inference origin admit destinations under that exact origin's `/v1/` or `/gw/v1/` path. Bare origins, other paths, explicit ports, other platform hosts, and any gateway host on an installation without a configured resident inference origin are refused with `APP_EGRESS_INTERNAL_DESTINATION`.

| Secret | Carries |
| --- | --- |
| `agents-gateway-url` | The gateway's base URL, `https://ai.ferrite.cloud` on Ferrite Cloud (kept in a secret so manifests stay deployment-independent) |
| `agents-gateway-key` | Your app's gateway credential: an inference key minted for the deployment's account, or a Ferrite bearer token. Store a provider API key here only when `gateway-egress` targets the provider directly. |

The SDK's `GatewayEgressTransport` posts `/v1/responses` through `gateway-egress` with `stream: true` forced. The request authenticates identically to external calls and charges the account bound to the credential. No provider key enters the calling app, and the gateway owns catalog lookup, pricing, metering, and billing. The SDK exposes `usage.billing` and `usage.cost_micros` on its `Usage` type so session transcripts and console readouts report what each turn cost and who paid.

A secret is set once and never returned by any read API, while the running application does receive its value and can send requests only to declared egress destinations. Mint a dedicated inference key per app with a spend cap or calendar budget and a rate limit so a compromised key stays bounded, and rotate it via `POST /gw/v1/keys/manage`. See [Secrets & Egress](/developers/secrets-egress/) for what secret isolation does and does not protect against.

The platform egress handle enforces fixed transport timeouts with no per-call deadline argument, so `GatewayEgressTransport` enforces its `timeout_ms` parameter with a local timer that drops the stream without signaling a deadline to the gateway. Neither a streamed first byte nor the gateway's retry budget bounds total model generation time, so if your application must respond to its caller within a shorter window, bound the wait in your own handler and treat late arrivals accordingly.

The egress transport is the agent SDK's sole model path; agent apps never connect to the gateway through a `depends` entry. See [Agent Runtime](/developers/agent-runtime/) and [ferrite-agents app](/developers/agents-app/).

## Protect credentials and prompts

- Account-level provider credentials stay sealed inside the gateway, and per-user BYOK calls pass `x-ferrite-provider-key` with `x-ferrite-byok-only: request` strictly in headers (never in the request body), fail closed on malformed or duplicate headers, and never fall back to platform credentials.
- Inference keys are stored solely as account-bound SHA-256 fingerprints, and per-request BYOK keys are redacted from debug logs and mixed into idempotency digests by hash.
- Requests cannot name an account or tenant, pass a provider credential in the body, or widen outbound egress.
- Each calling app receives its own inference key value at runtime, so isolate keys per app with spend caps, budgets, and rate limits.
- Upstream provider traffic leaves strictly through declared egress destinations, with no sidecar and no raw socket path.
- Error details that could expose provider internals stay server-side and are stripped from non-admin responses.
- Retries preserve idempotency and never resume a partially consumed caller stream.

See [Secrets & Egress](/developers/secrets-egress/) for the platform egress and secret model.
