Skip to content

fix(vertex): preserve Gemini Embedding 2 usageMetadata for cost tracking - #31354

Merged
mateo-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_gemini_embedding_2_multimodal
Jun 26, 2026
Merged

mateo-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_gemini_embedding_2_multimodal

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Multimodal Gemini Embedding 2 (embedContent) calls returned successful embeddings but LiteLLM recorded prompt_tokens=0 and spend $0 whenever the Vertex response-cost header was absent. The embedContent response carries usageMetadata with per-modality token counts that we were discarding.

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

CI (LiteLLM team)

  • Branch creation CI run
    Link:

  • CI run for the last commit
    Link:

  • Merge / cherry-pick CI run
    Links:

Screenshots / Proof of Fix

PENDING a separate live-repro phase. Plan: run a local proxy

python litellm/proxy/proxy_cli.py --config litellm/proxy/dev_config.yaml --detailed_debug --reload --use_v2_migration_resolver 2>&1 | tee litellm.log

then send a real multimodal Gemini Embedding 2 embedContent request through /v1/embeddings (image, audio or video input) hitting the real Vertex API, and confirm via http://localhost:4000/ui/?page=logs that the request records nonzero prompt_tokens and nonzero spend instead of $0

Type

🐛 Bug Fix

Changes

process_embed_content_response now derives Usage from the Gemini embedContent response's usageMetadata instead of always rebuilding it from the request. The raw metadata is validated with a TypeAdapter(UsageMetadata) so the parsing stays fully typed, promptTokenCount / totalTokenCount populate the token totals, and the promptTokensDetails modality breakdown plus the request's image inputs populate PromptTokensDetailsWrapper (text tokens, audio seconds, image count, video seconds) that generic_cost_per_token reads for gemini-embedding-2 pricing.

Per-modality seconds are reverse-derived from the response's reported token counts using Google's documented tokenizer rates rather than re-parsing the media: video at 258 tokens/sec and audio at 32 tokens/sec (https://ai.google.dev/gemini-api/docs/tokens). Because these are the same rates Google uses to produce the reported token counts, dividing the reported VIDEO / AUDIO tokens by them recovers the exact billable second count; the per-second prices themselves stay in the cost map as input_cost_per_video_per_second and input_cost_per_audio_per_second. generic_cost_per_token gains an audio_length_seconds cost path so gemini-embedding-2 audio (priced per second, not per token) no longer records $0.

A 1-token text floor is applied for video inputs whose only billable modality is video, matching generic_cost_per_token's text-fallback trigger (text_tokens == 0 and image_count == 0); this keeps video tokens billed per-second instead of being reassigned to the text rate, and it holds even when audio is also present so video+audio is not double-billed.

When usageMetadata is absent the behavior stays conservative: text-only input still falls back to token_counter, and multimodal input keeps prompt_tokens=0 rather than estimating tokens from the base64 payload.

Tests extend the mapped test_batch_embed_content_transformation.py and test_llm_cost_calc_utils.py with regressions that fail before this change: a multimodal image response with usageMetadata yields nonzero prompt_tokens, image_count=1, and nonzero cost through generic_cost_per_token; a text response populates text_tokens; a video response derives video_length_seconds with the 1-token floor; an audio response derives audio_length_seconds and bills per second; a video+audio response keeps text_tokens=1 and does not reassign video tokens to text; a resolved files/ image reference bills per image; and a response without usageMetadata does not estimate from base64


Note

Medium Risk
Changes embedding usage and spend calculation for Vertex Gemini Embedding 2; incorrect mapping would misreport proxy logs and customer billing, though scope is limited to embedContent and cost detail fields.

Overview
Fixes $0 spend / zero prompt_tokens on multimodal Gemini Embedding 2 embedContent when Vertex does not supply a response-cost header by building Usage from the API’s usageMetadata instead of zeroing multimodal calls or re-estimating from payloads.

Vertex embedContent path: process_embed_content_response now maps promptTokenCount, modality breakdowns, and request-side image detection (including resolved files/… refs) into PromptTokensDetailsWrapper. Video and audio billable duration is derived from reported VIDEO/AUDIO token counts (258 and 32 tokens/sec). A 1-token text floor when only video (no text/images) prevents generic_cost_per_token from treating video tokens as text-priced input.

Shared cost plumbing: Adds audio_length_seconds on prompt token details and charges it via input_cost_per_audio_per_second in _calculate_input_cost. Handlers pass resolved_files into response processing for correct per-image counts.

Regression tests cover image/text/video/audio usage, file-reference image billing, video+audio without double text billing, and missing-metadata fallbacks.

Reviewed by Cursor Bugbot for commit ffb6a09. Bugbot is set up for automated code reviews on this repo. Configure here.

@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.42857% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...i_embeddings/batch_embed_content_transformation.py 90.32% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri
mateo-berri marked this pull request as ready for review June 25, 2026 22:46
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes prompt_tokens=0 / spend=$0 on Vertex Gemini Embedding 2 embedContent calls by reading the response's usageMetadata field instead of always zeroing multimodal usage. It adds per-modality billing helpers (image count, video seconds, audio seconds), threads resolved_files through both sync and async handlers so file-API image references are billed at the per-image rate, and extends generic_cost_per_token with a new audio_length_seconds cost path.

  • process_embed_content_response now delegates to _usage_from_embed_content_response, which validates usageMetadata via TypeAdapter(UsageMetadata) and maps promptTokensDetails modalities to PromptTokensDetailsWrapper fields used by generic_cost_per_token.
  • A 1-token text floor is introduced for video-only inputs to prevent generic_cost_per_token's text-fallback rewrite from misallocating video tokens to the text rate.
  • Eight new unit tests cover image, text, video, audio modalities, file references, and the missing-metadata fallback; all are mock-only with no real network calls.

Confidence Score: 4/5

Safe to merge for the billing-preservation fix itself; audio-embedding billing accuracy depends on whether 32 tokens/sec matches Gemini Embedding 2's actual audio tokenization rate, which is not publicly documented.

The usageMetadata parsing, 1-token video floor, and image-count logic are well-tested and correct. The one open question is _AUDIO_TOKENS_PER_SECOND = 32.0: this constant is the sole divisor that converts the API-reported audio_tokens count into audio_length_seconds, and therefore into the billed amount. The PR description explicitly cites the video rate from Google's docs but provides no equivalent source for the audio rate. If Gemini Embedding 2 tokenizes audio at a different rate (e.g., 25 tokens/sec as Gemini 1.5 models do), every audio embedding will be mis-billed by that ratio without any error or warning.

litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py — the _AUDIO_TOKENS_PER_SECOND constant needs a documented source before audio billing can be trusted.

Important Files Changed

Filename Overview
litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py Core change: replaces hardcoded prompt_tokens=0 for multimodal with TypeAdapter-validated usageMetadata parsing; adds per-modality billing helpers; introduces _AUDIO_TOKENS_PER_SECOND=32.0 constant with no documented source
litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py Threads resolved_files into process_embed_content_response for both sync and async paths; minimal, correct change
litellm/litellm_core_utils/llm_cost_calc/utils.py Adds audio_length_seconds to PromptTokensDetailsResult and a new AUDIO LENGTH COST block in _calculate_input_cost; consistent with existing video_length_seconds pattern
litellm/types/utils.py Adds audio_length_seconds field to PromptTokensDetailsWrapper with None-deletion in init; follows existing pattern for video_length_seconds
tests/test_litellm/llms/vertex_ai/gemini_embeddings/test_batch_embed_content_transformation.py Adds TestProcessEmbedContentResponseUsage with 8 new unit tests covering image/text/video/audio modalities, file references, and missing metadata fallback; no real network calls
tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py Adds audio_length_seconds=0.0 to an existing fixture dict to match the expanded PromptTokensDetailsResult TypedDict

Reviews (4): Last reviewed commit: "fix(vertex): bill Gemini embedding audio..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes zero-cost recording for Gemini Embedding 2 embedContent calls by parsing the response's usageMetadata into a typed Usage block with per-modality token details, rather than always returning prompt_tokens=0 for multimodal inputs.

  • _usage_from_embed_content_response reads promptTokenCount, totalTokenCount, and promptTokensDetails (text, audio, video) from the raw response; image count is derived by inspecting the request input for data-URI and GCS-URL elements.
  • A 1-token text floor is applied for video-only inputs to prevent generic_cost_per_token from overwriting text tokens with the full prompt count, which would price video tokens at the wrong rate.
  • Five new unit tests cover the image, text, video, and missing-metadata paths; existing tests received minor cosmetic reformatting.

Confidence Score: 3/5

Safe to merge for the common case (data URI and GCS URL image inputs), but file-referenced images will be billed at the text rate instead of the per-image rate until the gap in _is_image_element is addressed.

The core fix correctly wires usageMetadata into the Usage object and the new unit tests validate the main paths. The billing gap for files/… image references is a present defect — that input type is already supported by _build_part_for_input in the same file, so callers can reach it today. The hardcoded video-token-rate constant is a minor maintainability concern for future models.

litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py — specifically _is_image_element (missing files/… branch) and _VIDEO_TOKENS_PER_SECOND (hardcoded model-specific rate).

Important Files Changed

Filename Overview
litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py Adds _usage_from_embed_content_response to parse Gemini usageMetadata into a typed Usage object with per-modality cost details; process_embed_content_response now uses this instead of always defaulting to zero for multimodal. Two gaps: _is_image_element misses files/… references (causing under-billing at text rate for file-referenced images), and _VIDEO_TOKENS_PER_SECOND is hardcoded.
tests/test_litellm/llms/vertex_ai/gemini_embeddings/test_batch_embed_content_transformation.py Adds five regression tests for process_embed_content_response covering image, text, video, and missing-metadata paths. All tests use mocked response dicts — no real network calls. Minor cosmetic reformatting of existing dict literals (single-line) does not weaken coverage.

Reviews (2): Last reviewed commit: "style(vertex): apply ruff format to batc..." | Re-trigger Greptile

…ge rate

Resolved files/... references whose mime type is an image were not detected
by _is_image_element, so image_count stayed 0 and generic_cost_per_token fell
back to the text token rate instead of input_cost_per_image. Thread the
resolved_files mapping into the usage builder so resolved image references are
counted and billed per image. Also modernize the _flatten_input return
annotation to satisfy the ruff UP006 strict gate.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Two follow-ups in de8e561:

files/ image references (3/5 concern) - fixed. You're right that this path is reachable: _resolve_file_references resolves files/... inputs on the embedContent path and _build_part_for_input turns them into image parts, but _count_input_images only saw the raw input string and could not know the resolved mime type, so resolved image refs fell through to the text token rate. I threaded the resolved_files mapping into process_embed_content_response -> _usage_from_embed_content_response -> _count_input_images -> _is_image_element, which now counts a files/... element as an image only when its resolved mime type is in _IMAGE_MIME_TYPES. Both handler call sites (sync and async) pass it through. Added two regressions: test_file_reference_image_billed_per_image_not_text asserts a resolved files/... png yields image_count == 1 and a generic_cost_per_token prompt cost of $0.00012 (the per-image rate) rather than the $0.0000516 text rate it produced before, and test_file_reference_non_image_not_counted_as_image guards that a files/... ref resolving to audio is not image-counted.

_VIDEO_TOKENS_PER_SECOND = 258 (P2) - keeping it inline. This is a fixed Gemini tokenizer constant, not a pricing knob. Gemini samples video at 1 frame/sec and tokenizes each frame at 258 tokens (https://ai.google.dev/gemini-api/docs/tokens), so 258 is the API's tokens-per-second-of-video rate that we use purely to reverse-derive the billable second count from the response's reported VIDEO token count. The actual price per second already lives in the cost map as input_cost_per_video_per_second and is applied by generic_cost_per_token, so pricing is not hardcoded here. Sourcing 258 through get_model_info would require adding a brand-new non-pricing field to the ModelInfoBase/ModelInfo TypedDicts in utils.py, populating it at the model-info construction sites, and threading custom_llm_provider plus a fallback into the transform layer, which is well outside the scope of this billing-preservation fix. If a future model ever changes the tokenizer rate, that is a one-line constant bump at that point

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run


Generated by Claude Code

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Audio embed spend stays zero
    • Added an audio_length_seconds field to PromptTokensDetailsWrapper / PromptTokensDetailsResult, derived it from audio_tokens at 32 tokens/sec in _usage_from_embed_content_response, and have _calculate_input_cost bill it via input_cost_per_audio_per_second so gemini-embedding-2 audio responses now record nonzero spend.
  • ✅ Fixed: Video plus audio double-billed
    • Replaced has_billable_non_video with a check aligned to generic_cost_per_token's rewrite trigger (video_length_seconds > 0 and text_tokens == 0 and image_count == 0) so video+audio responses still get the 1-token text floor and video tokens are no longer re-billed as text.

You can send follow-ups to the cloud agent here.

…dio double-billing

Audio-only embedContent responses set audio_tokens, but generic_cost_per_token only
charges audio via input_cost_per_audio_token. gemini-embedding-2 prices audio via
input_cost_per_audio_per_second, so spend stayed at $0. Plumb a new
audio_length_seconds field through PromptTokensDetailsWrapper, parse it in
_parse_prompt_tokens_details, and bill it from _calculate_input_cost. The vertex
embedding transformation derives audio_length_seconds from audio_tokens using
the documented 32 tokens/sec Gemini rate.

The 1-token text floor that protects video billing only fired when no other
modality was billable, but audio presence flipped that flag, leaving text_tokens
at zero for video+audio responses. generic_cost_per_token then rewrote
text_tokens to prompt_tokens minus audio_tokens (the video token count),
charging video tokens as text on top of the per-second video cost. The rewrite
trigger is text_tokens == 0 and image_count == 0; align the floor with that
trigger and ignore audio_tokens.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ mateo-berri
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai


Generated by Claude Code

@mateo-berri

Copy link
Copy Markdown
Contributor Author

On the _AUDIO_TOKENS_PER_SECOND = 32.0 question: 32 tokens/sec is Google's documented audio tokenizer rate (https://ai.google.dev/gemini-api/docs/tokens, https://ai.google.dev/gemini-api/docs/audio; one minute of audio is 1,920 tokens), the audio analogue of the 258 tokens/sec video rate. The constant only inverts Google's own tokenization: usageMetadata reports the AUDIO tokenCount that Google computed at 32/sec, so audio_tokens / 32 recovers the exact billable second count, and the per-second price stays separate in the cost map as input_cost_per_audio_per_second. Accuracy therefore depends on matching Google's tokenizer, which we do, not on any pricing assumption; the 25 tokens/sec figure that sometimes comes up is Live API audio pricing, not embedContent tokenization. I added this source to the PR description next to the video rate

@greptileai


Generated by Claude Code

@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

The clarification checks out. Google's docs confirm 32 tokens/sec for audio (Firebase AI Logic docs corroborate this independently — "Audio: 32 tokens per second"). The audio_tokens / 32 inversion correctly recovers the billable second count from what the API itself computed at that rate — no pricing assumption is baked in, and the distinction from Live API's 25 tokens/sec rate is valid.

Updated summary:

Confidence Score: 5/5

All concerns from the earlier review are now resolved:

  • files/... image references — fixed by threading resolved_files into _count_input_images / _is_image_element, so file-API image refs bill at the per-image rate ($0.00012) rather than the text rate.
  • Audio spend $0 — fixed by adding audio_length_seconds to PromptTokensDetailsWrapper and a per-second audio cost path in _calculate_input_cost.
  • Video+audio double-billing — fixed; the floor trigger now matches generic_cost_per_token's actual rewrite condition (text_tokens == 0 and image_count == 0) regardless of audio_tokens.
  • _AUDIO_TOKENS_PER_SECOND = 32.0 — confirmed from Google's docs (32 tokens/sec for audio). Distinct from Live API's 25 tokens/sec rate.

The implementation is well-structured, the unit tests cover the key modality paths, and the billing logic correctly inverts Google's own tokenizer constants rather than making independent pricing assumptions. Safe to merge.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run


Generated by Claude Code

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit ffb6a09. Configure here.

@mateo-berri
mateo-berri merged commit 6e35408 into litellm_internal_staging Jun 26, 2026
78 checks passed
@mateo-berri
mateo-berri deleted the litellm_gemini_embedding_2_multimodal branch June 26, 2026 02:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants