fix: correct Gemini countTokens payload format to prevent premature context truncation #8115
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR attempts to address Issue #8113 by fixing the incorrect payload format sent to Gemini's
countTokensmethod, which was causing premature context truncation in long-running conversations.Problem
The Gemini token counting was failing because we were sending
Part[]instead of the requiredContent[]format. This caused the SDK to returnundefinedfor token counts, forcing a fallback to the generic tiktoken estimator that overestimates tokens by 1.5x, leading to premature truncation at ~90k-130k tokens instead of the expected ~250k.Solution
countTokensmethod insrc/api/providers/gemini.tsto wrap the parts in a properContentstructure with user role[{ role: "user", parts: Part[] }]Changes
countTokensto send correctContent[]formatcountTokensincluding:Testing
countTokensmethodContent[]structure is sent to the SDKNotes
Fixes #8113
Feedback and guidance are welcome!
Important
Fixes
countTokenspayload format ingemini.tsto prevent premature context truncation, with comprehensive tests added.countTokensingemini.tsto sendContent[]format with user role, preventing premature context truncation.gemini.spec.tsfor correct format, multimodal content, fallback scenarios, and empty content handling.Content[]structure is sent to SDK.This description was created by
for 18995aa. You can customize this summary. It will automatically update as commits are pushed.