Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions openhands-sdk/openhands/sdk/llm/utils/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,12 +255,16 @@ def _cache_buckets(usage: Usage | ResponseAPIUsage) -> tuple[int, int]:
details = usage.prompt_tokens_details
if details is None:
return 0, 0
cache_write = (
details.cache_creation_tokens
if "cache_creation_tokens" in details.model_fields_set
else 0
# NB: PromptTokensDetailsWrapper deletes unset optional fields
# (e.g. providers without prompt caching like MiniMax), so direct
# attribute access raises AttributeError. getattr with a default
# is the only safe read here.
cache_write = getattr(details, "cache_creation_tokens", 0) or getattr(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: these getattr calls fail the repository's own Forbid dynamic attribute access in SDK pre-commit hook (scripts/check_forbidden_dynamic_attributes.py exits 1 with violations at 262 x2 and 265), and the committed baseline may only shrink, so this cannot be allowed through. uv run ruff format --check also reports this file needs reformatting.

model_dump() achieves the same tolerance without dynamic attribute access — deleted optional fields are simply absent from the dump:

            dumped = details.model_dump()
            cache_read = dumped.get("cached_tokens") or 0
            cache_write = (
                dumped.get("cache_creation_tokens")
                or dumped.get("cache_write_tokens")
                or 0
            )
            return int(cache_read), int(cache_write)

Note this would also require replacing the MagicMock in test_record_usage_with_cache_read, since a mock's model_dump() returns another mock.

details, "cache_write_tokens", 0
)
return int(getattr(details, "cached_tokens", 0) or 0), int(
cache_write or 0
)
return int(details.cached_tokens or 0), int(cache_write or 0)

details = usage.input_tokens_details
cache_read = details.cached_tokens if details is not None else 0
Expand Down
22 changes: 22 additions & 0 deletions tests/sdk/llm/test_llm_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,28 @@ def test_record_usage_with_cache_write(self, basic_telemetry):
token_usage = basic_telemetry.metrics.token_usages[0]
assert token_usage.cache_write_tokens == 30

def test_record_usage_with_real_details_no_cache_fields(self, basic_telemetry):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test does not fail on the pre-fix code in the environment CI installs. With the old _cache_buckets restored in memory, this test passes: at litellm==1.93.0 (pinned in uv.lock) PromptTokensDetailsWrapper(cached_tokens=25) yields model_fields_set == {'cached_tokens'}, so the old guard is False and returns (25, 0) without raising. PromptTokensDetailsWrapper(cached_tokens=0) behaves the same way, so it cannot stand in as the reproduction either.

A shape that does raise on the old code at 1.93.0 is the explicit null, which keeps the name in model_fields_set while the attribute is deleted:

        usage = Usage(
            prompt_tokens=100,
            completion_tokens=50,
            total_tokens=150,
            prompt_tokens_details={"cached_tokens": 25, "cache_creation_tokens": None},
        )

Covering that (or the equivalent raw ModelResponse usage dict with cache_creation_tokens: null) makes this a real regression guard.

"""Providers without prompt caching (e.g. MiniMax) return a real
PromptTokensDetailsWrapper with the cache attributes deleted.

Regression test: _record_usage must not raise AttributeError here,
and must still count cache reads.
"""
from litellm.types.utils import PromptTokensDetailsWrapper

usage = Usage(
prompt_tokens=100,
completion_tokens=50,
total_tokens=150,
prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=25),
)

basic_telemetry._record_usage(usage, "test-id", 4096)

token_usage = basic_telemetry.metrics.token_usages[0]
assert token_usage.cache_read_tokens == 25
assert token_usage.cache_write_tokens == 0

def test_record_usage_missing_tokens(self, basic_telemetry):
"""Test token usage recording with missing token counts."""
usage = Usage() # Empty usage
Expand Down
Loading