Skip to content

fix(sdk): tolerate missing cache fields in LLM usage telemetry - #5335

Open
yunusgungor wants to merge 1 commit into
OpenHands:mainfrom
yunusgungor:fix/telemetry-missing-cache-fields
Open

yunusgungor wants to merge 1 commit into
OpenHands:mainfrom
yunusgungor:fix/telemetry-missing-cache-fields

Conversation

@yunusgungor

Copy link
Copy Markdown

HUMAN:
I hit this on Agent Canvas with a cheaperinference profile: every turn failed with AttributeError: 'PromptTokensDetailsWrapper' object has no attribute 'cache_creation_tokens'. The agent kept doing its work but I never saw a reply, and a working profile also failed validation so it could not be saved. The patch fixes both paths.


AGENT:

Why

Any provider whose usage response contains prompt_tokens_details without cache
fields crashes token accounting. LiteLLM's PromptTokensDetailsWrapper.__init__
deletes the attributes for fields the provider did not report, while still
listing them in model_fields_set. normalize_usage tested
"cache_creation_tokens" in prompt_details.model_fields_set and then read the
attribute directly, so the membership check passed and the read raised:

AttributeError: 'PromptTokensDetailsWrapper' object has no attribute 'cache_creation_tokens'

The crash is fatal for the turn: the assistant reply is never produced, so the
conversation appears to stall after the agent has already done its work. The
same error also reaches profile validation — the pre-flight completion raises,
so a working configuration is reported as invalid and the profile cannot be
saved.

Summary

  • Read cache_creation_tokens defensively in normalize_usage: an absent
    attribute means the provider reported no cache write, which is the value the
    model_fields_set check was already trying to produce.
  • Added a regression test in TestUsageNormalization that reproduces the exact
    wrapper state (name listed in model_fields_set, attribute deleted) and
    asserts normalization still reports the cache-read count.
  • No behavior change for providers that do report cache writes.

Issue Number

Fixes #5168

How to Test

uv run pytest tests/sdk/llm/test_llm_telemetry.py -q

Before the fix the new test fails with the reported error:

E   AttributeError: 'PromptTokensDetailsWrapper' object has no attribute 'cache_creation_tokens'
======================= 1 failed, 47 deselected in 0.68s =======================

After the fix all 48 tests pass:

====================== 48 passed in 0.40s ======================

End-to-end check against a live OpenAI-compatible provider whose usage omits the
cache fields (the crash needs the wrapper state LiteLLM produces at runtime,
which the LiteLLM version pinned in this workspace does not reproduce on its
own, so the regression test constructs that state explicitly):

'cache_creation_tokens' in __dict__          : False
'cache_creation_tokens' in model_fields_set  : True
normalize_usage -> UsageSnapshot(prompt_tokens=35, completion_tokens=16,
                     reasoning_tokens=16, cache_read_tokens=0, cache_write_tokens=0)

Full SDK LLM suite: 1062 passed, 1 failed. The failure
(test_default_provider_store_is_sibling_of_base_dir) is pre-existing and
reproduces on a clean main checkout.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

cached_tokens and reasoning_tokens are always present on the LiteLLM
wrappers, so only the cache-write field needs the defensive read.

LiteLLM's ``PromptTokensDetailsWrapper`` registers optional fields in
``model_fields_set`` and then deletes the unset attributes, so a provider
without prompt caching (whose usage carries no ``cache_creation_tokens``)
made ``normalize_usage`` raise ``AttributeError`` and killed the turn before
the assistant reply was produced. Read the cache-write field defensively
instead of assuming it is present.

Fixes OpenHands#5168

Co-authored-by: openhands <openhands@all-hands.dev>
@all-hands-bot

Copy link
Copy Markdown
Collaborator

⏳ Review waiting on checks

The current head 73996e4a726f still has checks that have not finished, so no review conversation was started:

  • Agent Server
  • Check Docstrings
  • Deprecation deadlines
  • Persisted settings compatibility checks
  • Pre-commit checks
  • REST API breakage checks
  • Review Thread Gate
  • Run tests
  • TypeScript client CI
  • TypeScript client endpoint audit
  • TypeScript client integration tests
  • Version bump guard

No action is needed. The scheduled scan retries once every check on the head reports a conclusion.

This is an automated check - no AI was used to generate this comment.

@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot September 30, 2026 00:42

@all-hands-bot all-hands-bot left a comment

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 review was posted by an AI agent (OpenHands).

Scope: this is an SDK-side token-accounting fix in openhands-sdk/openhands/sdk/llm/utils/telemetry.py, which this repository owns. It changes no public/persisted compatibility surface, so it belongs here.

Assessment

  • Root cause is accurate, and I reproduced it against the LiteLLM version pinned in this workspace (litellm==1.93.0). PromptTokensDetailsWrapper.__init__ deletes cache_creation_tokens when it is None, while the name can remain in model_fields_set; the old membership guard therefore passed and the direct attribute read raised AttributeError. The reachable runtime shape is a provider payload that carries a null cache-write key (e.g. cache_creation_input_tokens=None), which flows through LiteLLM's Usage._from_openai into PromptTokensDetailsWrapper(**prompt_tokens_details), leaving cache_creation_tokens in model_fields_set but absent from __dict__.
  • The new defensive read returns 0 in exactly that case and is unchanged when a cache write is reported (verified: base 30, head 30). cached_tokens and reasoning_tokens are unconditionally present on the wrappers, so leaving those reads direct is correct and matches the PR's stated scope.
  • Focused suite on the head: uv run --frozen pytest tests/sdk/llm/test_llm_telemetry.py -q -> 48 passed. The added regression test reproduces the failing wrapper state and asserts the cache-read count is preserved.

Non-blocking note: the new test constructs the failure state by mutating model_fields_set and popping __dict__ directly. The same state is reachable through the real constructor, PromptTokensDetailsWrapper(**{"cached_tokens": 25, "cache_creation_tokens": None}), so a small follow-up driving it through that path would make the regression test faithful to production. The current test still covers the defect, so this does not block.

CI: on this head, PR Description Check and PR Artifacts succeeded; the remaining workflows report action_required (first-time-contributor approval for the fork PR), so the full test matrix has not run yet. Local focused tests pass.

✅ APPROVED

@all-hands-bot
all-hands-bot requested a review from enyst September 30, 2026 07:00
@all-hands-bot
all-hands-bot requested review from enyst and removed request for enyst November 9, 2026 14:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AttributeError in Telemetry._cache_buckets for providers without prompt caching

2 participants