# Valuation: the cost of each call

**Last updated:** 2026-11-27T08:38:27-03:00 (UTC-3)

Each recorded request gets an estimated cost in dollars, calculated with the price at that moment and the tokens the provider reported. The price is frozen in the event: if the price changes tomorrow, today's cost does not change. The result appears in **Analytics → Estimated cost**, by model, team and provider, over time.

## How to turn it on

```yaml
features:
  usage_analytics: true
  usage_valuation: true        # requires usage_analytics
  cost_adjustments: true       # optional: discounts and margins
```

The price comes from the [manual price book](/docs/features/pricing/) when it has an entry in effect for the connection and model, and otherwise from [automatic pricing](/docs/features/automatic-pricing/). The rate stored with each event says which: `source`, `manual_fallback: true` for a manual price, and `override: true` when that manual price replaced an available automatic one.

## How to read the result

Each event has a state:

| State | Meaning | Counts in the total? |
| --- | --- | --- |
| `known` | The provider reported both token counters, a usable price exists and the call type is supported | Yes |
| `partial` | Only one counter came; that component appears, but the event total is `null` | No |
| `unknown` | The price is missing or the call has something the gateway cannot price safely | No |
| `unvalued` | Event recorded before the flag was turned on | No |

**The total sums only `known` events.** With no known event, the total is `null`, never zero. A zero cost only appears when the counters and the rate prove zero. The coverage (how many events in each state) comes along, so you know how much of the traffic the number represents.

## What is valued

| Call type | Valuation |
| --- | --- |
| Chat, Messages, Responses and Gemini, in JSON or streamed | Per token |
| System One decisions, in JSON | Per token; the current decision profile has no streaming |
| Image, speech, transcription and Runway video | Per unit: image, character, second of audio, second of video |
| GPT Image (`gpt-image-1` and its family), with `image_token_pricing` | Per token by category, from the answer's usage |
| Embeddings, in JSON | Per input token, from the answer's `usage.prompt_tokens`; an embedding has no output tokens, so the output counts as zero. Give the rate an `output_per_million` (`"0"` for a model with no output price): a rate without one stays `unknown` (`unsupported_rate`) |
| Rerank | Not valued yet |
| MCP tool calls and listings | Not valued: they call no model provider, so their request log rows have no valuation (`not_valued` in reports), zero model tokens and no provider |

**Streams** are valued from the counters the provider reports at the end, only when the [stream usage](/docs/features/stream-usage/) observer proves a complete answer: every event must fit the supported profile, with a matching model, complete usage and usable prices for the categories reported. A stream cut before its end has no counters and stays `unknown`. A Chat Completions stream whose client did not ask for the usage has no counters either, unless its alias sets [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf).

A Responses answer can echo the request's `tools` and `reasoning` settings in the answer or stream events; with function tools only, that echo is configuration, not a billed category, and the model nested under `response` is checked against the rate like any other.

**Prompt caching** is valued by category, the same way budgets measure it: the usage is split per dialect (an OpenAI prompt and a Gemini prompt include their cache reads, an Anthropic input excludes them, Bedrock reports reads and writes beside its input), and cache reads, five-minute writes and one-hour writes are valued at the cache prices the source publishes (the cost map's `cache_read_input_token_cost`, `cache_creation_input_token_cost` and `cache_creation_input_token_cost_above_1hr`, OpenRouter's `input_cache_read` and `input_cache_write`, models.dev's `cache_read` and `cache_write`), the rest of the input at the input price. A request that marks its own cache points (`cache_control` of type `ephemeral` with `ttl` `5m` or `1h`, on a block, a part, a message or a tool) is valued the same way when the target is Claude (Anthropic or Claude on Bedrock), since that answer reports what was written and read by time to live; a mark sent to any other target (an OpenAI Chat Completions passthrough, whose writes carry no time to live) and any other mark stay `unknown` (`non_text_or_stateful_profile`). See [prompt caching](/docs/features/prompt-caching/).

**Claude thinking on the Messages API** has no price of its own: the tokens Claude thinks are billed as output tokens and are inside the answer's `output_tokens`, whatever the request's `display` shows, and `usage.output_tokens_details.thinking_tokens` names how many of the output they were. So a `/v1/messages` request that sets `thinking` (`adaptive`, `enabled` with `budget_tokens`, or `disabled`, with an optional `display`), the thinking blocks of an answer or of an earlier turn sent back, and a usage whose only detail is `thinking_tokens` (never above `output_tokens`) are valued like any text call. Any other `thinking` field, any other usage detail, and a `thinking` field on another route stay `unknown`. The current Claude models think by default and Claude Code names the setting on every call, so before this rule none of those calls had a cost. The budget measures the same way (see [budget profiles](/docs/features/quota-protocols/)), so a thinking answer settles its reservation at the same tokens the valuation prices. The usage rule also serves a Chat Completions `reasoning_effort` translated to Claude, whose answers report the same detail. It applies to every provider of protocol `anthropic`: the price you approve for an Anthropic-compatible endpoint that is not Anthropic's asserts that its thinking is inside `output_tokens` too.

**Long context:** when the source publishes a higher tier (the cost map's `*_above_<N>k_tokens` prices, models.dev's `context_over_<N>k`), a request whose input (cache included) exceeds the threshold is valued entirely at the tier.

**Service tiers:** the tier the provider reports in the answer (`service_tier` of a Chat Completions answer or chunk, the terminal Responses object) selects the price: `default` or `auto` the standard rate, `priority` or `flex` that tier's published price; the frozen rate then holds the tier's prices and source. A tier no source prices stays `unknown` (`service_tier_unpriced`), a non-standard tier asked for and not reported too (`service_tier_unreported`). Gemini names its tier inside `usageMetadata` (`serviceTier`, `trafficType`); see [Gemini tiers, media and totals](#gemini-tiers-media-and-totals). See [service-tier pricing](/docs/features/service-tier-pricing/).

**Translated answers** (Bedrock, Anthropic, Gemini, Cohere or a Responses-API target behind another route) are valued from the provider's own usage, which the adapter reads and proves before translating, with the provider's billed model checked against the priced one.

**Function tools** the client runs itself (Chat and Responses `type: function`, Messages tools with an `input_schema`, Gemini function declarations), the calls the model writes and the results sent back are text, valued per token like any other.

**Image input** is valued like text when the provider bills image tokens as input tokens at the input price and counts them in its prompt counter, the same proof a budget settles on: OpenAI, Anthropic (also through Bedrock and its OpenAI-compatible endpoint), Gemini (API and Vertex AI) and Amazon Nova on Bedrock, on those providers' own hosts only (a third-party host speaking the same protocol bills by its own rules). Only images the gateway can inspect count (bytes that match their type, https URLs in image fields), and the source must not publish an image price of its own.

These stay `unknown`, with the reason:
- prompt-cache reads or writes when the price source publishes no cache price for them (`cache_price_unavailable`); audio, which has its own price; a service tier no source prices (`service_tier_unpriced`), a tier that is not a name (`billing_tier_unresolved`), two tiers in one stream (`service_tier_conflict`) and Messages or Bedrock tiers other than standard; Gemini media tokens without a published per-token price (`media_token_unpriced`) or that the usage does not count (`media_usage_unreported`); image input where the provider does not bill it as input tokens or the source prices images apart (`image_price_unresolved`); reasoning too, unless the provider proves it is part of the output (`completion_tokens_details.reasoning_tokens` within `completion_tokens` and `total_tokens` equal to input plus output), in which case it is valued as output;
- hosted tools (web search, code execution, server tools), detected from the declared tools, the hosted-tool counters and any hosted call or server tool result in the answer, a Responses stored prompt (`prompt`, which may carry hosted tools), conversation context and error responses;
- answers the gateway translates from another provider's format whose own usage the adapter could not prove (`provider_usage_unproven`), or whose billed model differs from the priced one (`response_model_mismatch`);
- a long-context tier the price source publishes in a shape the gateway cannot read, or more than one tier for the same model (`tiered_rate_unresolved`); the cost map's one-hour cache write price (`cache_creation_input_token_cost_above_1hr`) is a cache price, not a tier;
- **more than one attempt** sent to the provider (`multiple_upstream_attempts`): the last response does not state the cost of the earlier ones. With `attempt_charge_lines` each send is valued on its own instead; see [charge lines per provider send](#charge-lines-per-provider-send);
- **model swapped** in the response (`response_model_mismatch`): the requested model's price is not applied to another. A dated snapshot of the requested model (OpenAI answers `gpt-4o-mini` as `gpt-4o-mini-2024-07-18`) is valued at the snapshot's own published price when the source lists it, never at the alias's; another suffix, or a snapshot the source does not price, stays unknown;
- prompt cache without explicit counters (`cache_usage_unreported`), when the source publishes a cache price. Gemini omits zero-valued counters, so a Gemini usage that counts the prompt reports a cache read of zero by leaving `cachedContentTokenCount` out.

There is no token estimate with a local tokenizer: the number comes from the provider.

## Gemini tiers, media and totals

A Gemini answer (native `generateContent`, JSON or streamed) reports what it billed in `usageMetadata`, and the valuation prices every documented field instead of leaving it unknown. There is no separate flag: it follows `usage_valuation`.

**Tier.** `serviceTier` and `trafficType` select the price set, like `service_tier` does for OpenAI:

| Reported | Price |
| --- | --- |
| no tier, `serviceTier: standard`, `trafficType: ON_DEMAND` | Standard rate |
| `serviceTier: flex`, `trafficType: ON_DEMAND_FLEX` or `FLEX` | The `flex` tier price |
| `serviceTier: priority`, `trafficType: ON_DEMAND_PRIORITY` | The `priority` tier price |
| `trafficType: BATCH` | The `batch` tier price |
| `trafficType: PROVISIONED_THROUGHPUT` | The `provisioned` tier price when one is approved; otherwise the standard price, reason `provisioned_estimated` |
| An unknown name, or a `serviceTier` and a `trafficType` that disagree | `unknown` (`specialized_usage_unresolved`) |

`ON_DEMAND` is pay-as-you-go whatever its tier, so `ON_DEMAND` with `serviceTier: flex` is flex. Names are read case-insensitively. A tier the rate does not price stays `unknown` (`service_tier_unpriced`), as for every dialect. A request that names `serviceTier` itself and gets an answer that reports none stays `unknown` (`service_tier_unreported`). The request log shows the reported tier (for a stream, when valuation is on).

The API names a requested tier in `usageMetadata.serviceTier` in JSON and streamed answers (measured on 2026-11-15 with `gemini-3.5-flash-lite`), and sends an `x-gemini-service-tier` response header on JSON answers only. The header is a fallback: it names the tier of a JSON answer whose usage names none, and a header that contradicts the usage's own tier, names a tier this gateway does not map, or is sent twice with different values, leaves the answer `unknown` (`service_tier_conflict`, `billing_tier_unresolved`). Every chunk of a stream carries its usage: two chunks that name different tiers prove neither price (`service_tier_conflict`); a chunk that names no tier does not clash, and a tier an earlier chunk named still prices a final usage that names none.

**Provisioned throughput** is capacity paid in advance, which no catalog prices per token. An operator can approve the rate it should be valued at, zero or the committed rate, as a `provisioned` tier in the [manual price book](/docs/features/pricing/) or on an approved budget rate ([service-tier pricing](/docs/features/service-tier-pricing/)). Without one, the answer is valued at the standard price with the reason `provisioned_estimated`, shown in **Analytics → Estimated cost** as an estimate: it is counted in the total, and it is not what the provider invoices.

**Media.** `promptTokensDetails`, `candidatesTokensDetails` and `cacheTokensDetails` split the counts by modality. Audio, video and image input and image and audio output are priced at their own per-token price from the cost map entry that priced the rate (`input_cost_per_audio_token`, `input_cost_per_video_token`, `input_cost_per_image_token`, `output_cost_per_image_token`, `output_cost_per_audio_token`); the frozen rate stores them as `audio_input_per_million`, `video_input_per_million`, `image_input_per_million`, `image_output_per_million` and `audio_output_per_million`, and the reason of a valued answer is `media_token_estimate`. A modality the answer uses without a published price stays `unknown` (`media_token_unpriced`), never priced as text; so does media in a non-standard tier or above the long-context threshold, whose catalog media prices this version does not read. Images under the [image input](#what-is-valued) rule keep billing as text input, as before.

A request with inline audio, video or image parts (`inlineData`) or with `responseModalities` IMAGE or AUDIO is no longer refused outright: the gateway checks that the rate prices those categories (`media_token_unpriced` otherwise) and that the answer's usage counts them. An answer whose usage reads as text while the request sent media, or while it returned an inline image or audio part, stays `unknown` (`media_usage_unreported`). With `gemini_file_inputs`, a file part with a declared type (`fileData` or `inlineData` with `mimeType`, with or without its slice: `documentMetadata`, `spreadsheetMetadata`, `videoMetadata`, `mediaResolution`) is valued the same way, on GenerateContent, on Chat Completions and Responses translated to a Gemini target, and on the Interactions API: a document's pages, a spreadsheet's `VISUAL` layer and images are image tokens (input at the input price where images bill as input, as on the Gemini API and Vertex AI; the image input price elsewhere), text layers are text, audio and video have their own price. A file part with no declared type, any file part while the flag is off, and video output stay outside the profile. See [file inputs](/docs/features/file-inputs/#what-a-file-request-costs).

**Totals.** The text share is derived from the details: a breakdown without a `TEXT` entry leaves the text as the count minus the other modalities; a zero count Gemini omits is zero, and `totalTokenCount` must equal the prompt, candidates and thoughts. Only impossible numbers stay `unknown` (`specialized_usage_unresolved`): a negative or malformed count, details that exceed their count, a `TEXT` entry that does not add up with the others, one modality listed twice, a total that does not add up, cached audio or video, or cache reads not named as `TEXT` beside non-text input.

Example with a rate of 0.30 USD per million text input tokens, 1.00 per million audio input tokens and 2.50 per million output tokens: a prompt of 1,000 tokens of which 600 are `AUDIO`, and 100 output tokens, costs 400 × 0.30 + 600 × 1.00 + 100 × 2.50 = 970 per million, 0.00097 USD.

**Large media answers.** A generated image or audio clip arrives inline as base64 in `inlineData.data`, often megabytes, above the observation bounds (64 KiB of a JSON answer without a budget, 256 KiB per streamed event). The observer drops the contents of each `inlineData.data` string as the bytes go by, keeping the quotes, so it reads the same answer with an empty blob and its usage prices the media; the client still receives every byte. A blob that would not decode (a control character, an invalid escape) is observed as undecodable too, so emptying it never turns a malformed answer into a valued one. Only a key spelled exactly `data` directly inside an object under a key spelled exactly `inlineData` is emptied; nesting deeper than 64 levels is observed whole. The whole stream is still bounded at 32 MiB of observed bytes; above that it stays `unknown`.

**Translated routes.** A chat route translated to Gemini is measured by the adapter, which reads tiers, derived totals and tier changes, and refuses media. That is not a gap the meter can close: the chat-to-Gemini translator sends only text and inline images (no audio or video input, no `responseModalities`, no `serviceTier`), images bill as input tokens under the [image input](#what-is-valued) rule, and a chat answer has no field for a generated image. A media modality reported on a translated route therefore means the translated request was not what was sent, and it stays `unknown` (`provider_usage_unproven`).

**Budgets** read Gemini the same way: a request's `serviceTier` (`standard`, `flex`, `priority`, `batch`, any case) reserves at that tier like a chat request's `service_tier` (an explicit `standard` at the standard prices alone, no tier at the highest approved tier, a tier the rate does not approve refused with `service_tier_not_approved`, another name refused with `unsupported_service_tier`), the answer settles at the tier it reports (or the JSON header names), a tier asked for and not reported keeps the reservation, and a tier change between chunks keeps it too. Provisioned throughput settles at the standard price unless approved. Media tokens keep the reservation: the measurement budgets store has no media split.

## GPT Image tokens

With `image_token_pricing` on (off by default; requires `price_source_cost_map`) and a cost map row priced per token (see [automatic pricing](/docs/features/automatic-pricing/#media)), an `/v1/images/generations` or `/v1/images/edits` answer is valued from its `usage` object, as the Images API reference documents it (an edit at the same prices as a generation of the model; see [image generation and edits](/docs/features/image-generation/)):

```json
"usage": {
  "input_tokens": 50,
  "input_tokens_details": {"text_tokens": 50, "image_tokens": 0},
  "output_tokens": 4160,
  "total_tokens": 4210
}
```

Text input tokens are valued at the text input price, image input tokens at the image input price and output tokens at the image output price. At `gpt-image-1`'s cost map prices (US$ 5, 10 and 40 per million) this answer costs `0.00025 + 0.1664 = 0.16665` USD. When the answer splits its output (`output_tokens_details` with `text_tokens` and `image_tokens`), each part is valued at its own price; a model whose row publishes a text output price (`output_cost_per_token`, as `gpt-image-1.5` does) needs that split, and stays `unknown` without it (`image_output_split_unreported`).

The usage follows the images, which are base64 strings of megabytes, so the gateway reads the whole relayed answer for it and keeps only the top-level `usage` (bounded to 8 KiB), never an image byte. The answer reaches the client unchanged.

These stay `unknown`:
- a streamed request (`stream: true`, `image_stream_unpriced`) and a service tier other than the default (`billing_tier_unresolved`);
- an answer that is not one complete, well-formed JSON object, has an `error` or a second usage block such as `svg_usage`, repeats a member (in the answer or in its usage) or spells a top-level one with escapes, has more than 64 top-level members or nests deeper than 64 levels, or was cut before its end (`image_usage_unresolved`);
- a usage whose counts do not add up (`input_tokens` equal to its text plus image tokens, `total_tokens` equal to input plus output), or that carries any other nonzero field, such as a cached count the documented object does not have (`image_usage_unresolved`); no usage at all (`usage_unreported`);
- text output with no text output price (`text_output_unpriced`).

The documented usage object has no cached-token count, so the input is valued at uncached prices even though the cost map also publishes cached prices for these models: if the provider applied a cache discount it did not report, the estimate is above the bill, never below it. A provider's invoice comes in through [billing imports](/docs/features/native-billing-imports/).

Budgets and token limits admit GPT Image requests with `quota_image_tokens` and an approved image token rate, and settle from the same usage; see [GPT Image budgets](/docs/features/quota-protocols/#gpt-image-budgets). Without the flag they are refused before the provider (`image_token_pricing_requires_separate_profile`).

## Charge lines per provider send

A request the gateway [retried](/docs/features/resilience/) or sent to a fallback target reached the provider more than once. Without the flag it is `unknown` as a whole. With `attempt_charge_lines` (operator control, off by default, requires `usage_valuation`), each send becomes its own immutable **charge line** under the request's usage event, recorded in the same transaction (with the [durable receipt](/docs/features/durable-usage/) when that is on):

| Field | Meaning |
| --- | --- |
| `attempt` | Send order, from 1 |
| `provider`, `model` | The target of that send |
| `outcome` | `answered`; `provider_error` (the provider answered an error status, valued as below); `transport_failure` (no answer: a timeout or a dropped connection); `unmeasured_answer` (an answer the gateway refused or could not measure, such as a buffered body to a stream request) |
| `status` | The provider's HTTP status, when it answered |
| `final` | The send whose answer the client got |
| `state`, `reason`, `amount_usd` | The line's own valuation, with its frozen price (`rate`) |
| `input_tokens`, `output_tokens` | The reported counters of the final send |

How each line is valued:

- the **final send** is valued exactly like a request with one send;
- an earlier **provider refusal** is `known` at `0` (`provider_error_not_billed`): a 4xx status other than 408, or 503 or 529 (unavailable, overloaded), which the provider answers before doing work;
- any other earlier **provider error status** (500, 502, 504, 408 and the rest) is `unknown` (`provider_error_unproven`): the model may have generated before it;
- an earlier send with **no answer** is `unknown` (`attempt_outcome_unknown`), and an earlier **answer the gateway did not measure** is `unknown` (`answer_not_measured`): the provider may have billed them, so they are never estimated.

The request is `known` at the sum of its lines when every line is known; `partial` with reason `attempt_unknown` (and no amount) when the final send is known but an earlier one is not, the lines keeping what is known; and the final send's own state otherwise. A request with a single send has no lines and is valued as before. A request past 99 earlier sends is `unknown` as a whole (`multiple_upstream_attempts`), as without the flag, so a send is never left out of a total that reads known.

Lines add to spend: every report that sums valuations (cost estimates, attribution groups, finance reconciliation, the customer portal) counts the request's total, which includes them. They never count as requests: the request is still one usage event. Protected routes under a [budget or token limit](/docs/features/budgets-and-tpm/) admit one target without retries, so a protected request has one send and its budget settles from that one measurement, as before.

`GET /api/v1/admin/valuation` adds `charge_lines` to the items that have them; team roles get them without the rate. The console lists them under the request's estimated amount in **Usage → Cost estimates**. With the flag off, nothing changes: earlier lines are not recorded or returned. Migration 167 adds the `gateway_usage_charge_lines` table; deleting a usage event deletes its lines.

## Budget charge beside the estimate

A request under a [budget](/docs/features/budgets-and-tpm/) has two numbers, by design: the **budget charge**, settled at the operator-approved quota rate captured when the request was admitted (or, after a [provider-charge reconciliation](/docs/features/quota-finance/), the invoice amount), and the **estimated cost** on this page, priced from the price book or catalog with discounts and margins. With `budget_charge_reports` (operator control, off by default, requires `usage_valuation` and `budget_limits`), the reports show both, side by side, and say why they differ.

The budget side comes from the reservation the request's usage event names, which [single charge](/docs/features/durable-usage/#single-charge) (`single_charge_settlement`) records; events recorded without it have no link and are counted as `unlinked`. The budget side of one event has a state:

| `state` | Budget charge |
| --- | --- |
| `settled` | Settled at the approved rate: `amount_usd` |
| `reconciled` | Moved to the provider's invoice by a charge reconciliation: `amount_usd` |
| `released` | No provider attempt started: `0` |
| `held` | Reserved or `unknown`: the reserved amount (`held_usd`) stays charged until a reconciliation; never summed as known |
| `tokens_only` | A token ceiling without a USD rate |
| `archived` | Its ledger row was archived |
| `unlinked` | No reservation linked |

Where it appears:

- **Cost estimates** (`GET /api/v1/admin/valuation`): a `budget_charge` summary (`charged_usd`, `charged`, `held`) over the same filtered events, and `budget_charge` on each request. The console shows **Charged against budget** under the known amount and a **Budget** line on each request.
- **Per-window consistency check** (`GET /api/v1/admin/valuation/consistency`, `analytics:read`, same filters and team scope as the valuation report, hours through 7 days and days above): per window and in total, how many requests have both sides known and agree within `charge_accounting.consistency_tolerance_usd` (default `0.000001`, echoed in the report as `charge_accounting.consistency_tolerance_usd`), and how many differ, by cause: `reconciliation` (the budget took the invoice), `margin` (a discount or margin changed the estimate) or `rate` (the price book or catalog price is not the approved rate). It also counts `only_budget_known` (with the valuation reasons, such as `rate_unavailable`), `only_estimate_known` (the reservation is held), `neither_known`, `unlinked`, `archived` and `tokens_only`, and sums both sides where both are known. The console lists the windows with a difference under **Charged against budget vs estimated cost**.
- **[Attribution groups](/docs/features/attribution-groups/)** and the **[customer portal](/docs/features/customer-portal/)** usage (and the self-service customer view): each row adds `budget_charge`; their CSV exports add `budget_charged_usd`, `budget_charged` and `budget_held`; the console adds a **Charged against budget** column.
- **[Financial reconciliation](/docs/features/billing-connectors/)** already shows `ledger_settled_usd` (the budget side) beside `gateway_estimated_usd`.
- **The [analytics store copy](/docs/features/analytics-store/)** carries each event's `quota_reservation_id`, `valuation_state`, `estimated_usd`, `budget_charge_state` and `budget_charge_units` (1e-12 USD).

```yaml
charge_accounting:
  consistency_tolerance_usd: "0.000001" # 0-1 USD, at most six decimal places; restart to apply
```

With the flag off, the reports, exports and the copy read as before, and the consistency route answers `404`.

## Discounts and margins

With `cost_adjustments`, per-provider or global discounts and margins (percentages or a fixed amount per request) go into each event's frozen price: discount first, then margin. Useful to reflect a negotiated contract or a pass-through charge to internal customers.

```yaml
cost_adjustments:
  discounts:
    global: 0.05         # 5% off every provider
    openai: 0.12         # replaces the global entry for this provider
  margins:
    global: {percent: 0.10, fixed_usd: 0.002}
```

| Key | Default | What it does |
| --- | --- | --- |
| `cost_adjustments.discounts` | `{}` | Map of a provider ID, or `global`, to the negotiated discount as a fraction (0.05 is 5%), from 0 to below 1; a provider entry replaces the global one |
| `cost_adjustments.margins` | `{}` | Map of a provider ID, or `global`, to the margin added after the discount |
| `cost_adjustments.margins.<provider>.percent` | `0` | Margin as a fraction of the discounted cost, 0 to 10 |
| `cost_adjustments.margins.<provider>.fixed_usd` | `0` | Fixed amount in USD added to each request, 0 to 10 |

The block requires `usage_valuation`; the console and the API can override it at runtime (below).

## What the frozen price stores

Connection (as a hash of protocol, URL and version), provider, exact model ID, currency, unit, rates, source and date. It does not store secrets, private URLs, prompts or responses. Changing the configuration or the price later does not recalculate old events.

## Pricing coverage

The state above says whether a cost is known. **Pricing coverage** (`pricing_coverage`, an operator flag, off by default; requires `usage_valuation`) says, for every answered model call, why it is or is not, in four statuses a dashboard can alert on:

| Status | When | Valuation states and reasons |
| --- | --- | --- |
| `complete` | The cost is known, a valid zero included (an exact-cache hit) | `known` |
| `partial` | The final usage did not arrive whole, or a cached-token category has no published price | `partial`; `unknown` with `partial_counters`, `usage_unreported`, `cache_usage_unreported`, `cache_price_unavailable`, `image_output_split_unreported` or `service_tier_unreported` |
| `inconsistent` | The reported counters are negative or do not add up (cached tokens above the input) | `unknown` with `invalid_counters`; on the metric, also a known amount that does not equal its parts |
| `unavailable` | No price applies | every other reason (`rate_unavailable`, `unsupported_rate`, a model the rate does not name, ...) and a call with no valuation row |

```yaml
features:
  usage_valuation: true
  pricing_coverage: true
```

It never changes a cost. With it on:

- `/metrics` and the OTLP metrics push carry `gateway_pricing_coverage_total{provider,model,status}`, one count per answered call (a 2xx answer) as it ends ([inference series](/docs/features/observability/#inference-series)). A failed call has nothing to price and is not counted; a window without samples is unknown coverage.
- `/analytics/query` takes the dimension `pricing_status` (group, filter, `non_empty`) over the stored valuations (their state and reason: a call whose durable outcome was not settled when it ended, `partial` on the metric, reads as its stored valuation here), for example `group_by=pricing_status&metrics=calls&non_empty=pricing_status`; a call that was not answered reads as an empty status. It is a dimension of requests, not of evaluation results.
- **Usage → Cost estimates** shows **Pricing coverage**: the calls of the selection in each status and their share.

Turning it on counts calls from then on; the analytics dimension reads every stored valuation, older ones included. Off, the series stops growing and the dimension is refused with `feature_disabled`.

## API

`GET /api/v1/admin/valuation`, with the `analytics:read` permission:

- **Teams and organizations:** `team` is a team's requests of the organization it is in now; `organization` is what was recorded in that organization. A team that moved keeps its earlier cost in the former organization's report ([when a team moves](/docs/features/organizations/#when-a-team-moves)).
- **Filters:** `from` and `to` (RFC3339, up to 90 days), `principal`, `model`, `team`, `provider`, `key_id`, `operation`, and `origin` with [evaluation tracing](/docs/features/evaluation-tracing/#the-origin-of-a-request) on, narrowed to one helper sub-kind with `helper_kind` (with `origin=helper`). The same filters apply to usage analytics and the CSV.
- **Page:** 50 events, with `has_more` and `next_offset` (`offset` up to 100,000).
- **Aggregates** over all filtered events, not just the page:
  - `timeline`: `{time, coverage, known_amount_usd}`, in 1-hour buckets (up to 7 days) or 1-day buckets;
  - `by_model`, `by_team`, `by_provider`: `{name, coverage, known_amount_usd}`, up to 20 groups (`truncated_dimensions` flags the cutoff);
  - `by_origin`, with evaluation tracing on: the same shape by how the requests entered (`app`, `evaluation`, `experiment`, `playground`, `helper`, ...), so evaluation, Playground and helper spend are their own lines (**Spend by origin** in the console's Cost estimates);
  - `by_helper_kind`, with evaluation tracing on: the helper spend by sub-kind (`guardrail`, `classifier`, `summary`, `ask_ai` for m7 ai, `cache_embedding`, `tool_search`, `vector_store`, `model_test`), each feature's [helper calls](/docs/features/evaluation-tracing/#helper-calls) billed to the team and organization that caused them; shown under `helper` in **Spend by origin**.
- **Cost per request** (`cost_request_insights`, operator flag, off by default; requires `usage_valuation`): `per_request` is `{priced, unpriced, p50_usd, p95_usd, p99_usd, max_usd, avg_usd}` over the known cost of each filtered request (each percentile is the cost of an actual request, never interpolated; the mean is rounded to 12 decimals; unknown and partial events are left out and counted in `unpriced`, and every amount is `null` when no request has a known cost), and `most_expensive` the costliest requests of the selection, largest first, each with `request_id`, `trace_id`, `at`, `team`, `key_id`, `model`, `provider`, `operation`, `origin`, `amount_usd` and the reported `input_tokens` and `output_tokens`. `top_requests` sets how many (1 to 50, default 10). The same predicate and team scope as the rest of the report apply, in the same read. These two have a time limit of their own (2 s): on a selection too large for it the report is still answered, without them, and with `per_request_unavailable: true` (the console says so); narrow the range or the filters. In the console, **Cost estimates** shows **Cost per request** (median, p95, p99, largest, mean) and **Most expensive requests**, each request opening its trace on the Traces screen (its request log entry without the trace explorer); with `customer_portal` on it adds **Spend by customer organization**, read from the [structured usage query](/docs/features/ask-ai/#the-structured-usage-query) (`group_by=customer_org`). The same percentiles by any dimension are the `*_cost_usd` metrics of that query.
- **Every call is a cost line.** A helper call and a request-level fallback attempt each have their own event and valuation, also when a later attempt answered the client, so what the provider billed is never lost; Usage counts the client's request once (see [how requests are counted](/docs/features/evaluation-tracing/#how-requests-are-counted)). `coverage.events` counts these calls.
- Values as decimal strings or `null`. Response with `Cache-Control: private, no-store`.

**Who sees what:**
- `team_admin`, `team_viewer` and `user` see only the teams they belong to, with amount, state, reason and price hash, without the rate and target details.
- global admin and viewer see the full provenance;
- operator has no access to analytics.

## Limits

- **An estimate, not an invoice.** It is not a financial ledger, reconciliation or budget. To stop spending, use [budgets](/docs/features/budgets-and-tpm/); to compare with the invoice, the [billing imports](/docs/features/native-billing-imports/).
- Recording is separate from the response: a failure to record is logged and does not change the delivered response. Coverage shows what reached the database; it does not prove nothing was lost.
- Turning off the flag stops valuation and hides the panel; what was already recorded stays.
- Deleting a usage event deletes its valuation; the frozen prices stay. The flag does not create its own retention policy.

## Admin API routes

Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/).

| Route | What it does |
| --- | --- |
| `GET /api/v1/admin/cost-adjustments` | The discounts and margins in force, their YAML base, source and control version |
| `PUT /api/v1/admin/cost-adjustments` | Replaces the discounts and margins with a versioned console override |
| `DELETE /api/v1/admin/cost-adjustments` | Removes the console override and restores the YAML block |

## See also

- [Automatic pricing](/docs/features/automatic-pricing/).
- [Analytics experience](/docs/features/analytics-experience/).
- References: [usage accounting](https://openrouter.ai/docs/use-cases/usage-accounting) and [prompt caching](https://openrouter.ai/docs/guides/best-practices/prompt-caching) on OpenRouter.

## Manage provider discounts and margins

Under `cost_adjustments`, **Settings & sources → Discounts and margins** and `GET /api/v1/admin/cost-adjustments` show the YAML base, current advisory policy, control version and source. Global readers require `prices:read`; changes require `prices:manage`, PostgreSQL, same-origin CSRF and the current version. Operators gain no finance permission from the flag-catalog reader.

`PUT /api/v1/admin/cost-adjustments` replaces the whole block with an audited override; `DELETE` with the current version restores YAML. A stale version returns 409, invalid semantic policy 422, and malformed/noncanonical JSON 400. Members use exact lowercase names; duplicates, null numeric values and nonfinite discounts/margins are refused. Discounts are fractions from zero to below one; margin fractions and fixed USD fees range from zero to ten. Provider-specific entries replace global entries, including explicit zero exemptions.

The editor preserves numeric precision through decimal-text percentage conversion and uses own properties for provider IDs. Observed denial discards private drafts and late replies; authorized conflict/validation drafts remain editable. Both the stored override and its audit survive normal refreshes and replicas converge on the versioned snapshot. If an override names a provider removed from the YAML, its known entries continue to apply and a warning identifies ignored entries; the stored block is retained until an explicit save/revert. An otherwise invalid override falls back to the valid YAML policy with a warning; malformed persisted JSON is a refresh failure, retaining the last valid snapshot.

Adjustments affect future advisory valuations only. Existing event rate snapshots and amounts are not rewritten; approved budget rates/reservations are unchanged. The existing canonical schema migration 93 already provides this override table: this feature reuses it without a new migration or renumbering. Older binaries that do not implement the control reader ignore the override; upgrade all replicas before relying on it, and review the YAML fallback before a downgrade. This is not a provider invoice reconciliation or mixed-version valuation certification.


## Valuation policy constraints

Shared [parameter definitions](/docs/reference/parameter-registry/) preserve the cost-adjustment domains: a discount is a finite fraction from zero inclusive to one exclusive, and margin fractions and fixed USD fees are finite values from zero through ten inclusive. Provider entries replace the corresponding global entry; the discount is applied before the margin. These valuation settings do not approve enforcement rates or turn incomplete usage into a known charge. Required provider/model identities and published prices never receive invented defaults.


## Write integrity

Valuation writes retain exact finite decimal amounts; nonfinite accounting values are refused before persistence. The immutable proof hashes the original event/valuation DTO, before SQL normalizes decimal spelling or timestamp precision. Numerically equal spellings can therefore remain different retry proofs. Captured rate bytes and their content hash are preserved independently of database JSON formatting. An event and its valuation are atomic; a receipt finalization additionally owns its final state in that same transaction.

The shared valuation calculator and typed write boundary do not select a new engine or alter these public contracts. PostgreSQL remains the general regression database; accepted optional-adapter evidence is reused rather than repeating feature suites.

## Display currency

With `fx_display`, the valuation response adds `display_currency` and `known_amount_display`, converted with the daily ECB reference rate and labelled with its date; `known_amount_usd` and every other USD field are unchanged. See [display currency](/docs/features/display-currency/).
