fix(langchain): capture usage on streamed gemini responses #1309
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.
Important
Fixes usage parsing bug in
CallbackHandler.pyfor streamed Gemini responses, ensuring valid usage data is captured._parse_usageinCallbackHandler.pyfor streamed Gemini responses._parse_usage_model()returns non-None, ensuring valid usage data is found.test_basic_chat_openaiintest_langchain.pyas flaky.This description was created by
for 15ff192. You can customize this summary. It will automatically update as commits are pushed.
Disclaimer: Experimental PR review
Greptile Summary
This PR fixes a bug in the Langchain integration's usage parsing logic for streamed Gemini responses. The change modifies the
_parse_usagefunction inCallbackHandler.pyto improve how it handles usage metadata extraction from generation chunks.The core issue was in the loop that iterates through generation chunks looking for usage metadata. Previously, the function would break out of the loop immediately after finding any chunk with
usage_metadata, regardless of whether that metadata was valid or usable. The fix adds a conditional check that only breaks the loop when_parse_usage_model()returns a non-None value, indicating that valid usage data was actually found.This change is specifically important for Gemini streaming responses, where early chunks may contain empty or invalid usage metadata, while later chunks contain the actual token usage information. The Langfuse Usage model (as seen in the context) tracks input/output tokens and associated costs, making accurate usage capture critical for billing and monitoring purposes. By ensuring the function continues searching until it finds valid usage data, this fix enables proper token usage tracking for streamed Gemini responses in the Langchain integration.
Confidence score: 4/5
CallbackHandler.py