Repository navigation
fix(vertex): preserve Gemini Embedding 2 usageMetadata for cost tracking - #31354
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR fixes
Confidence Score: 4/5Safe 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.
|
| 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 SummaryThis PR fixes zero-cost recording for Gemini Embedding 2
Confidence Score: 3/5Safe 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 The core fix correctly wires litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py — specifically
|
| 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.
|
Thanks for the review. Two follow-ups in de8e561: files/ image references (3/5 concern) - fixed. You're right that this path is reachable: _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 |
|
bugbot run Generated by Claude Code |
There was a problem hiding this comment.
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.
|
|
|
Generated by Claude Code |
|
On the Generated by Claude Code |
|
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 Updated summary: Confidence Score: 5/5 All concerns from the earlier review are now resolved:
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. |
|
bugbot run Generated by Claude Code |
There was a problem hiding this comment.
✅ 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.
Relevant issues
Multimodal Gemini Embedding 2 (
embedContent) calls returned successful embeddings but LiteLLM recordedprompt_tokens=0and spend$0whenever the Vertex response-cost header was absent. TheembedContentresponse carriesusageMetadatawith 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
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewCI (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
then send a real multimodal Gemini Embedding 2
embedContentrequest through/v1/embeddings(image, audio or video input) hitting the real Vertex API, and confirm viahttp://localhost:4000/ui/?page=logsthat the request records nonzeroprompt_tokensand nonzero spend instead of$0Type
🐛 Bug Fix
Changes
process_embed_content_responsenow derivesUsagefrom the GeminiembedContentresponse'susageMetadatainstead of always rebuilding it from the request. The raw metadata is validated with aTypeAdapter(UsageMetadata)so the parsing stays fully typed,promptTokenCount/totalTokenCountpopulate the token totals, and thepromptTokensDetailsmodality breakdown plus the request's image inputs populatePromptTokensDetailsWrapper(text tokens, audio seconds, image count, video seconds) thatgeneric_cost_per_tokenreads forgemini-embedding-2pricing.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_secondandinput_cost_per_audio_per_second.generic_cost_per_tokengains anaudio_length_secondscost path sogemini-embedding-2audio (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
usageMetadatais absent the behavior stays conservative: text-only input still falls back totoken_counter, and multimodal input keepsprompt_tokens=0rather than estimating tokens from the base64 payload.Tests extend the mapped
test_batch_embed_content_transformation.pyandtest_llm_cost_calc_utils.pywith regressions that fail before this change: a multimodal image response withusageMetadatayields nonzeroprompt_tokens,image_count=1, and nonzero cost throughgeneric_cost_per_token; a text response populatestext_tokens; a video response derivesvideo_length_secondswith the 1-token floor; an audio response derivesaudio_length_secondsand bills per second; a video+audio response keepstext_tokens=1and does not reassign video tokens to text; a resolvedfiles/image reference bills per image; and a response withoutusageMetadatadoes not estimate from base64Note
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_tokenson multimodal Gemini Embedding 2embedContentwhen Vertex does not supply a response-cost header by buildingUsagefrom the API’susageMetadatainstead of zeroing multimodal calls or re-estimating from payloads.Vertex
embedContentpath:process_embed_content_responsenow mapspromptTokenCount, modality breakdowns, and request-side image detection (including resolvedfiles/…refs) intoPromptTokensDetailsWrapper. 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) preventsgeneric_cost_per_tokenfrom treating video tokens as text-priced input.Shared cost plumbing: Adds
audio_length_secondson prompt token details and charges it viainput_cost_per_audio_per_secondin_calculate_input_cost. Handlers passresolved_filesinto 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.