← Blog

Gemini Usage Metadata Needs Contract-Level Validation

Parminder Singh
Parminder Singh··7 min read
Summarize with AI

Gemini usageMetadata separates effective prompt tokens, cached prompt tokens, generated candidate tokens, tool-use prompt tokens, thinking tokens, and the total generation count. A production gateway should preserve the exact field definitions, validate integer and arithmetic invariants carefully, retain modality details, and keep provider-reported usage separate from local budgets and billing records.

Platform & Architectureai-securityllm-securitypolicy-enforcementforensic-auditarchitecture
Gemini Usage Metadata Needs Contract-Level Validation

Gemini returns usageMetadata as output-only token-usage metadata for a generation request. The object carries more than prompt and output totals. Cached content stays inside the effective prompt count, while tool-use prompts and thinking tokens have their own fields and also contribute to the total.

That accounting model deserves a typed validator. Flattening every value into input_tokens and output_tokens throws away the evidence needed to explain budget changes and cache behavior. It also obscures tool-heavy turns and thinking-model usage.

TL;DR

  • Preserve Gemini's usage fields under their documented names and meanings.
  • promptTokenCount includes cached content when cached content is set; cachedContentTokenCount reports the cached part within that effective prompt.
  • Keep candidate and tool-use prompt token counts separate from thought token counts, then validate totalTokenCount against the documented components.
  • Retain modality detail arrays. Distinguish provider-reported usage from local estimates and limits. Keep invoices separate.

The fields describe separate token pools

Google's GenerateContent API reference defines usageMetadata as metadata on the generation request's token usage. Its scalar fields carry specific meanings:

  • promptTokenCount is the number of tokens in the prompt. When cached content is set, Google says this remains the total effective prompt size and includes the cached content.
  • cachedContentTokenCount is the number of tokens in the cached part of the prompt.
  • candidatesTokenCount is the total number of tokens across all generated response candidates.
  • toolUsePromptTokenCount is the number of tokens present in tool-use prompts.
  • thoughtsTokenCount is the number of thought tokens for thinking models.
  • totalTokenCount is the total for the generation request: prompt and response candidates, plus tool-use prompts and thoughts.

Preserve those definitions in schema comments and data contracts. Renaming cachedContentTokenCount to cache_savings would invent an economic meaning. Renaming thoughtsTokenCount to hidden_output would invent a content meaning.

Cached content remains part of the effective prompt

The cache relationship is the first place dashboards go wrong. promptTokenCount already includes cached tokens when cached content is set. Adding promptTokenCount and cachedContentTokenCount produces double counting.

A useful record stores both values and can derive the non-cached portion as a local calculation only after validation: effective prompt count minus cached content count. Mark the derived value as locally calculated because the two source fields came from Gemini.

Validate both as non-negative integers. When both appear, a cached count greater than the effective prompt count is contradictory under the documented definitions. Preserve the raw metadata and emit a named finding. Follow route policy rather than silently clamping the number.

Cache identity and token accounting also solve different audit questions. Record the cached-content resource reference or request configuration separately from token usage. The per-route AI policy guide shows where a route can permit cached context and set budgets. It also shows how contradictory response evidence can affect delivery.

The white usage card in an operator console should show effective prompt tokens first, with cached tokens indented beneath them. Side-by-side totals invite someone to add them.

Tool and thought tokens need visible budgets

Tool-use prompts consume their own documented token pool. In a multi-turn function workflow, those tokens can rise even when the user's text stays short. Store toolUsePromptTokenCount and its modality details instead of folding the value into an unexplained overhead field.

Thinking models add another pool through thoughtsTokenCount. Google's definition says this is the number of tokens of thoughts for thinking models. Treat the count as usage evidence. It does not expose the thought content or certify reasoning quality. It also does not authorize a tool action.

The official Gemini token guide explains token counting and notes that input can include text plus other modalities. Provider tokenization can also depend on the model. A local preflight estimate is useful for admission control, but the returned usageMetadata is the provider's report for that generation request.

Set independent route budgets for effective prompts and generated candidates. Where the application needs them, add separate ceilings for tool-use prompts and thoughts. Keep the total under its own ceiling. A total-only ceiling can stop runaway cost after several components have already grown. Component ceilings identify the specific path that exceeded policy.

My committee-deletable opinion is simple: a dashboard that hides thought and tool tokens under "other" is an accounting failure wearing a clean chart.

Total validation needs the documented equation

Google defines totalTokenCount as the prompt plus response candidates. Tool-use prompts and thoughts also contribute to that total. When all component fields are present, validate the reported total against that equation.

The validator also needs presence-aware logic. An omitted optional or inapplicable component should remain absent in the raw record. Converting every absence to zero can erase the difference between "provider reported zero" and "field unavailable on this response shape." A normalized analytics layer may use zero with an accompanying presence flag, but the audit copy should retain the original shape.

Use safe integer handling and explicit upper bounds suitable for the API contract. Reject strings, floating-point numbers, negatives, booleans, and values outside the parser's accepted range. Preserve the raw object or its protected digest before normalization so an updated parser can revisit a disputed record.

A mismatch should create a finding such as usage_total_mismatch, including the raw total and present components. Record the parser version and route decision with it. Avoid rewriting the provider total to match local arithmetic. The discrepancy itself is the evidence.

Modality details keep mixed-media usage explainable

The API reference provides detail arrays for prompt and cached content. It also provides arrays for candidates and tool-use prompts. promptTokensDetails lists modalities processed in request input. cacheTokensDetails lists modalities of cached request content. candidatesTokensDetails covers modalities returned in the response. toolUsePromptTokensDetails covers modalities processed for tool-use request inputs.

Validate each array as structured provider evidence. Retain the modality enum and count for every entry, including unknown future modalities. Known values can feed dashboards. Unknown values should remain searchable. They should trigger a parser-review finding rather than disappearing into an other bucket with no raw value.

Cross-field checks can flag impossible local states without claiming undocumented provider guarantees. Negative modality counts are invalid for your schema. Duplicate modality entries can be preserved and flagged. A detail sum that differs from its scalar count deserves review, but route policy should account for API-version behavior before blocking production traffic.

The AI audit log schema provides the identity and request envelope. It also provides the policy and decision envelope. Usage metadata belongs on the same attempt so responders can connect token consumption to one authenticated request and its final disposition.

Usage evidence is separate from billing evidence

usageMetadata reports generation token usage under the API contract. An invoice can apply service tier or cache pricing. Batch pricing and credits may also apply. Rounding or commercial terms can sit outside this object. Record invoice and cost data in a separate billing domain, linked by project and time window, with any available provider references.

The same separation applies to local budgets. A route may reserve 20,000 tokens before dispatch and receive a lower provider total. It may charge an internal team under another allocation rule. Store budget_reserved and provider_usage as separate objects. Store internal_charge separately as well.

High-cardinality attempt IDs and response IDs belong in searchable evidence. Token counts work as metrics values, while model and route can act as bounded dimensions after validation. Disposition and service tier can do the same. Avoid using user identifiers or raw cache resource names as metrics labels.

The Google Gemini enterprise audit logs guide covers administrative and platform logs. Attempt-level usageMetadata fills a narrower gap by attaching provider token accounting to the exact AI HTTP exchange.

Fixtures should exercise every component

Build a Gemini-compatible stub behind the deployed route. Start with prompt and candidate counts whose total matches. Add cached content and verify that the validator includes it within promptTokenCount rather than adding it again.

Next, include tool-use prompt tokens and thought tokens before calculating the documented total. Omit each component in separate fixtures, then return explicit zero in others. Confirm that the raw audit distinguishes absence from zero while the analytics projection follows its declared normalization rule.

Add negative integers and numeric strings. Add floating-point values and booleans. Include very large integers and a total mismatch. Test modality arrays with known entries and an unknown modality. Add duplicate modalities and counts that disagree with the scalar field. Every case should preserve raw evidence and emit a stable finding.

Finally, retry one business operation twice with different usage metadata and response IDs. The operation view should keep both attempts. Adding only the successful attempt's tokens would understate provider work performed during the retry path.

DeepInspect

DeepInspect can inspect Gemini responses on authenticated user or agent HTTP traffic routed through its stateless proxy. Before response delivery, the proxy can validate the returned usage object and enforce per-route token ceilings. Unknown or contradictory fields enter the audit record with identity, policy version, model, response ID, and disposition.

The application owns preflight estimates and project budgets. It also owns invoice reconciliation and cache lifecycle. Downstream cost allocation remains with the application. Calls that bypass the proxy remain outside this enforcement and audit boundary.

Book a technical deep dive at deepinspect.ai.

Frequently asked questions

Does promptTokenCount exclude cached content?

No. Google's definition says promptTokenCount remains the total effective prompt size when cached content is set, including the cached content. cachedContentTokenCount reports the cached part within that prompt count.

What does candidatesTokenCount include?

It is the total number of tokens across all generated response candidates. Keep candidate count and selection metadata beside it so a reviewer can distinguish provider generation from the single candidate the application may have delivered.

Are thought tokens part of totalTokenCount?

Yes. Google defines the total as the prompt, response candidates, tool-use prompts, and thoughts. thoughtsTokenCount is a separate output-only field for thinking models.

Should absent usage fields be converted to zero?

Preserve absence in the audit copy. An analytics projection can normalize an absent component to zero only with a presence flag and a documented rule. That keeps "missing" distinct from "reported zero."

Can usageMetadata be used as an invoice?

Treat it as provider-reported generation usage. Billing can apply pricing terms and cache rates. Tiers and credits may also apply. Rounding can occur outside the response object. Reconcile invoices in a separate billing record rather than assigning monetary guarantees to token metadata.

What should happen when the total disagrees with components?

Preserve every raw value and emit a usage_total_mismatch finding. Apply the route's evidence policy. The system should avoid changing Google's reported value or hiding the discrepancy behind a recalculated total.