Skip to content

fix(vertex_ai): bill per-character text embeddings on Google's billableCharacterCount - #47460

Merged
klu-berri merged 1 commit into
mainfrom
litellm_vertex_embedding_per_character_cost
Oct 20, 2026
Merged

klu-berri merged 1 commit into
mainfrom
litellm_vertex_embedding_per_character_cost

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Google bills text-embedding-005 and text-multilingual-embedding-002 per character, LiteLLM charged per token
  • The cost map already has input_cost_per_character: 2.5e-08 on both keys, the embedding path never read it
  • metadata.billableCharacterCount in the Vertex predict response was dropped

How it solves it:

  • The embedding response usage carries billableCharacterCount as prompt_tokens_details.character_count
  • A model with input_cost_per_character bills that count instead of its text tokens, never both
  • Per-token embeddings (gemini-embedding-001, any key without input_cost_per_character) bill as before

Intentional product change: every Vertex text embedding response now has usage.prompt_tokens_details.character_count (per-token models included). Nothing is removed

Related: #47069 covers the same issue from an OSS contributor. Nothing was taken from that branch. It stashes the count in a hidden param read from a ModelResponse branch an embedding never takes, and it reads the count from per-prediction statistics where Vertex does not put it (the live response below has it under top-level metadata). This PR reuses the existing character_count usage field and the character branch generic_cost_per_token already has

User Flow

Before: a platform team charging Vertex embedding spend back to internal teams sees LiteLLM log more than Google invoices

  1. They send POST https://litellm-domain/v1/embeddings with "model": "vertex_ai/text-embedding-005" and a 43 character sentence
  2. The response comes back with usage.prompt_tokens: 11 and the header x-litellm-response-cost: 1.1e-06
  3. https://litellm-domain/ui/?page=logs shows the request at $0.0000011, Google bills 35 characters at $0.000000875

After: the same request is logged at Google's per-character price

  1. They send the same POST https://litellm-domain/v1/embeddings
  2. The response has usage.prompt_tokens: 11, usage.prompt_tokens_details.character_count: 35 and x-litellm-response-cost: 8.75e-07
  3. https://litellm-domain/ui/?page=logs shows the request at $0.000000875, and a vertex_ai/gemini-embedding-001 request still shows its per-token price

Relevant issues

Fixes section 2 of #46880

Linear ticket

Resolves LIT-9892

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Live proxy on localhost:4000 with Postgres, real Vertex AI calls. Config:

model_list:
  - model_name: vertex_ai/text-embedding-005
    litellm_params:
      model: vertex_ai/text-embedding-005
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: us-central1
  - model_name: vertex_ai/gemini-embedding-001
    litellm_params:
      model: vertex_ai/gemini-embedding-001
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: us-central1
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

The input is The quick brown fox jumps over the lazy dog, 43 characters, which Vertex reports as "metadata": {"billableCharacterCount": 35} (whitespace is not billed) and 11 tokens, so the two prices differ: 11 x 1e-07 = 1.1e-06 per token, 35 x 2.5e-08 = 8.75e-07 per character. Both calls were made with

for m in vertex_ai/text-embedding-005 vertex_ai/gemini-embedding-001; do
  curl -s http://localhost:4000/v1/embeddings -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
    -d "{\"model\": \"$m\", \"input\": \"The quick brown fox jumps over the lazy dog\"}" -D - -o resp.json | grep -i "x-litellm-response-cost:"
  python3 -c "import json; d=json.load(open('resp.json')); d['data'][0]['embedding']=d['data'][0]['embedding'][:2]+['...']; print(json.dumps(d))"
done
psql "$DATABASE_URL" -c 'SELECT model, spend, prompt_tokens, completion_tokens, metadata->>'"'"'usage_object'"'"' AS usage_object FROM "LiteLLM_SpendLogs" ORDER BY "startTime" DESC LIMIT 2;'

Before (497f31d)

text-embedding-005 is billed per token

  1. curl ... vertex_ai/text-embedding-005
  2. Output
x-litellm-response-cost: 1.1e-06
{"model": "vertex_ai/text-embedding-005", "data": [{"object": "embedding", "index": 0, "embedding": [-0.046401575207710266, -0.009816601872444153, "..."]}], "object": "list", "usage": {"completion_tokens": 0, "prompt_tokens": 11, "total_tokens": 11, "completion_tokens_details": null, "prompt_tokens_details": null}}

gemini-embedding-001 is billed per token

  1. curl ... vertex_ai/gemini-embedding-001
  2. Output
x-litellm-response-cost: 1.35e-06
{"model": "vertex_ai/gemini-embedding-001", "data": [{"object": "embedding", "index": 0, "embedding": [-0.01571161486208439, 0.010199472308158875, "..."]}], "object": "list", "usage": {"completion_tokens": 0, "prompt_tokens": 9, "total_tokens": 9, "completion_tokens_details": null, "prompt_tokens_details": null}}

SpendLogs rows

  1. psql ... LIMIT 2
  2. Output
             model              |  spend   | prompt_tokens | completion_tokens |                                                            usage_object
--------------------------------+----------+---------------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------
 vertex_ai/gemini-embedding-001 | 1.35e-06 |             9 |                 0 | {"total_tokens": 9, "prompt_tokens": 9, "completion_tokens": 0, "prompt_tokens_details": null, "completion_tokens_details": null}
 vertex_ai/text-embedding-005   |  1.1e-06 |            11 |                 0 | {"total_tokens": 11, "prompt_tokens": 11, "completion_tokens": 0, "prompt_tokens_details": null, "completion_tokens_details": null}

After (fe38060)

text-embedding-005 is billed per character

  1. curl ... vertex_ai/text-embedding-005
  2. Output, 35 x 2.5e-08 = 8.75e-07
x-litellm-response-cost: 8.75e-07
{"model": "vertex_ai/text-embedding-005", "data": [{"object": "embedding", "index": 0, "embedding": [-0.046401575207710266, -0.009816601872444153, "..."]}], "object": "list", "usage": {"completion_tokens": 0, "prompt_tokens": 11, "total_tokens": 11, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": null, "text_tokens": null, "image_tokens": null, "video_tokens": null, "initial_prompt_tokens": null, "character_count": 35}}}

gemini-embedding-001 is billed per token

  1. curl ... vertex_ai/gemini-embedding-001
  2. Output, unchanged at 9 x 1.5e-07 = 1.35e-06
x-litellm-response-cost: 1.35e-06
{"model": "vertex_ai/gemini-embedding-001", "data": [{"object": "embedding", "index": 0, "embedding": [-0.01571161486208439, 0.010199472308158875, "..."]}], "object": "list", "usage": {"completion_tokens": 0, "prompt_tokens": 9, "total_tokens": 9, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": null, "text_tokens": null, "image_tokens": null, "video_tokens": null, "initial_prompt_tokens": null, "character_count": 35}}}

SpendLogs rows

  1. psql ... LIMIT 2
  2. Output
             model              |  spend   | prompt_tokens | completion_tokens |                                                                                                                                            usage_object
--------------------------------+----------+---------------+-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 vertex_ai/gemini-embedding-001 | 1.35e-06 |             9 |                 0 | {"total_tokens": 9, "prompt_tokens": 9, "completion_tokens": 0, "prompt_tokens_details": {"text_tokens": null, "audio_tokens": null, "image_tokens": null, "video_tokens": null, "cached_tokens": null, "character_count": 35, "initial_prompt_tokens": null}, "completion_tokens_details": null}
 vertex_ai/text-embedding-005   | 8.75e-07 |            11 |                 0 | {"total_tokens": 11, "prompt_tokens": 11, "completion_tokens": 0, "prompt_tokens_details": {"text_tokens": null, "audio_tokens": null, "image_tokens": null, "video_tokens": null, "cached_tokens": null, "character_count": 35, "initial_prompt_tokens": null}, "completion_tokens_details": null}

Regression tests

tests/unit/llms/vertex_ai/vertex_embeddings/test_embedding_handler.py::test_vertex_embedding_usage_carries_the_billable_character_count_google_prices_on and tests/unit/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py::test_generic_cost_per_token_bills_a_character_counted_prompt_under_one_unit. On the merge base the character cases fail ((8, None) == (8, 10) and 1.975e-06 != 8.75e-07, the token-plus-character double charge) and the no-metadata and token-priced cases pass, which is the "per-token embeddings unchanged" proof. All six pass on the fix

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Batch rows of per-character embedding models are not costed today (no usageMetadata, no embedding object, native_vertex_batch_row_stats returns None for them), so no input_cost_per_character_batches field is added. Adding batch character pricing is a separate design decision
  • usage.prompt_tokens_details.character_count is now set on per-token Vertex embedding responses too (see the gemini-embedding-001 After output). It is ignored for cost there

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/3192b8ae836340568c04a74ffcd6816c
Open in Devin Desktop: https://app.devin.ai/desktop/session/3192b8ae836340568c04a74ffcd6816c?variant=devin
Requested by: @kerrylu-berri


Note

Medium Risk
Changes billing math for Vertex character-priced embedding models and alters reported usage metadata; per-token embedding pricing is intended to stay the same but spend/logging will shift for affected models.

Overview
Fixes Vertex per-character text embeddings (text-embedding-005, etc.) being overcharged because LiteLLM billed tokens while Google bills metadata.billableCharacterCount.

Vertex embedding responses now surface that count on usage.prompt_tokens_details.character_count. In _calculate_input_cost, models with input_cost_per_character bill only the character count (text-token base cost is skipped so tokens and characters are never charged together). Per-token embedding models keep token pricing; character_count may still appear on usage but is ignored for cost.

Unit tests cover the cost-calc branch and the Vertex usage transform.

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

…leCharacterCount

Vertex text embedding predict responses report metadata.billableCharacterCount, the
unit Google bills text-embedding-005 and text-multilingual-embedding-002 on. Carry it
into usage.prompt_tokens_details.character_count and, when the model carries
input_cost_per_character, bill that count instead of the token count so the prompt is
charged under one unit. Per-token embeddings (gemini-embedding-001) are unchanged.
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 32 untouched benchmarks


Comparing litellm_vertex_embedding_per_character_cost (fe38060) with main (b2eda10)

Open in CodSpeed

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at fe38060. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at fe38060. Changes billing math for Vertex character-priced embedding models and alters reported usage metadata; per-token embedding pricing is intended to stay the same but spend/logging will shift for affected models. Bugbot run requested, finished in 5 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@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 fe38060. Configure here.

@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 20, 2026
@klu-berri
klu-berri merged commit d29200f into main Oct 20, 2026
91 checks passed
@klu-berri
klu-berri deleted the litellm_vertex_embedding_per_character_cost branch October 20, 2026 01:17
pamanseau pushed a commit to KubeTEE-AI/litellm that referenced this pull request Oct 25, 2026
…leCharacterCount (BerriAI#47460)

Backport of BerriAI#47460 to stable/1.103.x

Cherry-picked from d29200f (main)
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
…leCharacterCount (BerriAI#47460)

Vertex text embedding predict responses report metadata.billableCharacterCount, the
unit Google bills text-embedding-005 and text-multilingual-embedding-002 on. Carry it
into usage.prompt_tokens_details.character_count and, when the model carries
input_cost_per_character, bill that count instead of the token count so the prompt is
charged under one unit. Per-token embeddings (gemini-embedding-001) are unchanged.

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

Backport of BerriAI#47460 to stable/1.106.x
Cherry-picked from d29200f (main)
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
…leCharacterCount (#47460)

Vertex text embedding predict responses report metadata.billableCharacterCount, the
unit Google bills text-embedding-005 and text-multilingual-embedding-002 on. Carry it
into usage.prompt_tokens_details.character_count and, when the model carries
input_cost_per_character, bill that count instead of the token count so the prompt is
charged under one unit. Per-token embeddings (gemini-embedding-001) are unchanged.

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit d29200f)
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
…leCharacterCount (BerriAI#47460)

Vertex text embedding predict responses report metadata.billableCharacterCount, the
unit Google bills text-embedding-005 and text-multilingual-embedding-002 on. Carry it
into usage.prompt_tokens_details.character_count and, when the model carries
input_cost_per_character, bill that count instead of the token count so the prompt is
charged under one unit. Per-token embeddings (gemini-embedding-001) are unchanged.

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

Backport of BerriAI#47460 to stable/1.105.x.
Cherry-picked from d29200f (main).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants