Repository navigation
fix(sdk): tolerate missing cache fields in LLM usage telemetry - #5335
yunusgungor wants to merge 1 commit into
Conversation
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>
⏳ Review waiting on checksThe current head
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. |
all-hands-bot
left a comment
There was a problem hiding this comment.
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__deletescache_creation_tokenswhen it isNone, while the name can remain inmodel_fields_set; the old membership guard therefore passed and the direct attribute read raisedAttributeError. 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'sUsage._from_openaiintoPromptTokensDetailsWrapper(**prompt_tokens_details), leavingcache_creation_tokensinmodel_fields_setbut absent from__dict__. - The new defensive read returns
0in exactly that case and is unchanged when a cache write is reported (verified: base 30, head 30).cached_tokensandreasoning_tokensare 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
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_detailswithout cachefields 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_usagetested"cache_creation_tokens" in prompt_details.model_fields_setand then read theattribute directly, so the membership check passed and the read raised:
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
cache_creation_tokensdefensively innormalize_usage: an absentattribute means the provider reported no cache write, which is the value the
model_fields_setcheck was already trying to produce.TestUsageNormalizationthat reproduces the exactwrapper state (name listed in
model_fields_set, attribute deleted) andasserts normalization still reports the cache-read count.
Issue Number
Fixes #5168
How to Test
Before the fix the new test fails with the reported error:
After the fix all 48 tests pass:
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):
Full SDK LLM suite:
1062 passed, 1 failed. The failure(
test_default_provider_store_is_sibling_of_base_dir) is pre-existing andreproduces on a clean
maincheckout.Type
Notes
cached_tokensandreasoning_tokensare always present on the LiteLLMwrappers, so only the cache-write field needs the defensive read.