Repository navigation
Python: fix(python): support sum(), validate operands, and add total_tokens to CompletionUsage - #14706
Open
Hardik K (hardikkaurani) wants to merge 2 commits into
Conversation
Hardik K (hardikkaurani)
deployed
to
github-app-auth
November 1, 2026 17:27 — with
GitHub Actions
Active
Contributor
Author
|
Hi Eduard van Valkenburg (@eavanvalkenburg), could you please take a look at this PR when you have a moment? It adds radd support for sum(), validates operand types in add, and adds the total_tokens property on CompletionUsage. Tests and ruff checks pass cleanly. Thank you! |
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
This PR improves
CompletionUsageinsemantic_kernel.connectors.ai.completion_usage:__radd__andsum()support:Currently, attempting to aggregate multiple
CompletionUsageobjects using Python's standardsum([u1, u2, ...])fails with:This occurs because
sum()starts with0as the default accumulator and delegates to__radd__. Implementing__radd__allowssum()to work seamlessly on sequences ofCompletionUsageobjects.Operand type validation in
__add__:__add__did not check operand types before accessing attributes likeother.prompt_tokens. Adding an unsupported type previously raised an uninformativeAttributeError: 'int' object has no attribute 'prompt_tokens'instead of returningNotImplementedto let Python raise the standardTypeError.total_tokensproperty:Adds a computed
total_tokensproperty ((self.prompt_tokens or 0) + (self.completion_tokens or 0)) matching provider conventions (e.g.,openai.types.CompletionUsage).Verification
python/tests/unit/connectors/ai/test_completion_token_usage.pycovering:sum([u1, u2, u3])total_tokenscomputation on non-empty and empty instancesTypeErrorwhen adding unsupported operand types