litellm - 💡(How to fix) Fix feat: opt-in accurate token counting for Gemini multimodal embeddings via countTokens [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
BerriAI/litellm#24339Fetched 2026-04-08 01:13:14
View on GitHub
Comments
0
Participants
1
Timeline
1
Reactions
0
Author
Participants
Timeline (top)
labeled ×1

Code Example

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:countTokens?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "hello"}, {"inline_data": {"mime_type": "image/png", "data": "..."}}]}]}'

---

{
    "totalTokens": 260,
    "promptTokensDetails": [
        {"modality": "TEXT", "tokenCount": 2},
        {"modality": "IMAGE", "tokenCount": 258}
    ]
}
RAW_BUFFERClick to expand / collapse

Feature Request

Gemini's embedding endpoint does not return usageMetadata in the response, so LiteLLM currently sets prompt_tokens = 0 for multimodal inputs (images, audio, video). This means cost tracking is inaccurate.

However, Gemini's countTokens endpoint works with embedding models and returns accurate token counts per modality:

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:countTokens?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "hello"}, {"inline_data": {"mime_type": "image/png", "data": "..."}}]}]}'

Response:

{
    "totalTokens": 260,
    "promptTokensDetails": [
        {"modality": "TEXT", "tokenCount": 2},
        {"modality": "IMAGE", "tokenCount": 258}
    ]
}

Proposal

Add an optional flag (e.g. count_tokens=True) that calls countTokens before/after the embedding request to populate usage.prompt_tokens with the value. Off by default to avoid the extra latency. This could be useful for users who need accurate cost tracking for multimodal embeddings, billing dashboards, and budget monitoring.

extent analysis

Fix Plan

To implement the proposed solution, follow these steps:

  • Add an optional count_tokens flag to the embedding endpoint function
  • Use the countTokens endpoint to retrieve accurate token counts when the flag is enabled
  • Update the usageMetadata with the retrieved token count

Example code:

import requests

def gemini_embedding_endpoint(contents, count_tokens=False):
    # ... existing code ...

    if count_tokens:
        token_count_response = requests.post(
            "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:countTokens",
            headers={"Content-Type": "application/json"},
            json={"contents": contents}
        )
        token_count_data = token_count_response.json()
        usage_metadata["prompt_tokens"] = token_count_data["totalTokens"]

    # ... existing code ...

Verification

To verify the fix, test the embedding endpoint with the count_tokens flag enabled and check that the usageMetadata contains the accurate token count.

Example test:

contents = [{"parts": [{"text": "hello"}, {"inline_data": {"mime_type": "image/png", "data": "..."}}]}]
response = gemini_embedding_endpoint(contents, count_tokens=True)
print(response["usageMetadata"]["prompt_tokens"])  # Should match the totalTokens value from the countTokens response

Extra Tips

  • Consider adding error handling for the countTokens endpoint call to ensure robustness.
  • Document the count_tokens flag and its usage to inform users about the feature.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

litellm - 💡(How to fix) Fix feat: opt-in accurate token counting for Gemini multimodal embeddings via countTokens [1 participants]