Repository navigation
fix(sdk): normalize LLM usage telemetry through a typed adapter - #5029
Conversation
Telemetry rediscovered the provider usage aliases at four separate call sites by probing for them with `getattr`, so the Chat Completions and Responses API spellings of the same quantities -- `prompt_tokens` vs `input_tokens`, `completion_tokens` vs `output_tokens`, and the cache and reasoning detail objects -- were each re-derived independently for metrics, for span attributes, and for the completion log. Add `UsageSnapshot`, a frozen typed value, plus a module-level `normalize_usage()` that is the single boundary for both provider shapes. `Telemetry.on_response` now normalizes once and passes the same snapshot to metrics and to the span, and `log_llm_call` reads it too, so the completion log and the app's token accounting cannot disagree. A usage object of an unrecognized shape normalizes to `None` rather than being guessed at, which preserves the existing "no token accounting" behavior. Accounting behavior is otherwise unchanged: the `prompt_tokens_details is None` cache fallbacks and the four-key `usage_summary` payload are identical. `telemetry.py` no longer needs any of the 24 `getattr` allowances it carried in the forbidden dynamic attributes baseline, which now holds 98 entries, all in other files. Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Scope: In-repo and correctly owned — this is an SDK LLM telemetry utility change (openhands-sdk/.../llm/utils/telemetry.py plus tests and the dynamic-attribute baseline), matching issue #4975. It is observability-only and does not touch prompts, tool calling, the agent loop, condenser/memory, or terminal handling, so it is not in the eval-risk category and needs no eval-monitor evidence. No UI surface, so no live-evidence gate applies.
Verification on head 0ebce0c:
- Reproduced the PR's end-to-end reproduction command. Both
Usage(Chat Completions) andResponseAPIUsage(Responses API) normalize to the sameUsageSnapshot, and absent/unknown shapes returnNoneinstead of invented counts. - Confirmed against litellm 1.93.0 that
ModelResponsedoes not declareusageas a field (extra="allow"), so pydantic keeps it inmodel_extra;_response_usagereads that mapping. Verified end-to-end throughconvert_to_model_response_object,litellm.stream_chunk_builder(streaming chat), andResponsesAPIResponse.usage. - The
model_fields_setcache-write gate and the Responsesinput_tokens_details.cached_tokensread preserve the removed_cache_bucketsbehavior; an Anthropic-style usage object still yields cache read/write correctly. - The removed private helpers (
_has_meaningful_usage,_cache_buckets) and the changed_record_usagesignature have no callers outside the module and its tests, so this stays inside the private surface. - Local runs:
uv run pytest tests/sdk/llm/test_llm_telemetry.py tests/sdk/llm/test_llm_span_cost.py -q-> 53 passed;check_forbidden_dynamic_attributes.pyontelemetry.pyexits 0; every check-run on the head SHA issuccess(sdk-tests, integration-test, coverage-report, pre-commit, public-type-budget, etc.).
No blocking or non-blocking correctness/security findings. The one description nit ("normalizes exactly once" while log_llm_call re-invokes the same pure normalize_usage/_response_usage) is harmless because both paths derive from the same function on the same response, so metrics and logs cannot diverge.
✅ APPROVED
HUMAN:
I chose #4975 because the telemetry typing issue is well scoped and relevant to the SDK's maintainability. I used an AI coding agent to help investigate and implement the change, then reviewed the diff, tests, and reasoning behind the typed normalization before deciding to submit it for review.
AGENT:
Why
Telemetryreads provider token accounting out of LiteLLM response objects, butLiteLLM reports that accounting in two disjoint shapes. Chat Completions
responses carry
Usage(prompt_tokens/completion_tokens), while ResponsesAPI responses carry
ResponseAPIUsage(input_tokens/output_tokens). Thequantities are the same; the names are not.
Before this change,
telemetry.pyrediscovered those aliases at four separatecall sites by probing for them with
getattr, so metrics, span attributes, andthe completion log each re-derived the provider shape independently. Adding a
provider, or a new detail object, meant remembering all four sites. It also
meant
telemetry.pycarried 24 entries inscripts/forbidden_dynamic_attributes_baseline.json— the repository's ownAGENTS.mdasks contributors to "prefer accessing typed attributes directly"and to "convert inputs up front into a canonical shape", and this file was the
largest remaining exception.
Summary
UsageSnapshotdataclass and a module-levelnormalize_usage()that is the single boundary between the two provider shapes and the SDK's one
internal vocabulary.
Telemetry.on_responsenow normalizes exactly once and hands the samesnapshot to metrics, to the span, and to
log_llm_call, so the completion logand the application's token accounting cannot disagree.
_has_meaningful_usageand_cache_bucketsalong with the 24getattrallowancestelemetry.pycarried in the baseline, which now holds98 entries, all in other files.
Issue Number
Fixes #4975
How to Test
Unit tests alone do not demonstrate the normalization contract, so here is an
end-to-end reproduction of the behaviour the change is about. It builds one
usage object of each provider shape, runs both through the same public
normalizer, and prints the result:
Both shapes print the same five fields, which is the point. Actual output:
An unrecognized usage shape normalizes to
Nonerather than being guessed at,which preserves the previous "no token accounting" behaviour instead of feeding
invented counts into cost and cache accounting.
The repo-prescribed checks for the touched files:
Video/Screenshots
N/A — this change has no user-visible surface. The reproduction above is the
observable evidence.
Design Doc
N/A — the change is confined to one utility module and its tests.
Type
Notes
Accounting behaviour is unchanged; only the route to the numbers changed. The
prompt_tokens_details is Nonecache fallbacks still hold, theusage_summarypayload still has exactly its four keys, and an absent usage object still
records nothing.
One deliberate subtlety worth a reviewer's attention:
ModelResponseacceptsusageas a constructor argument but does not declare it as a field, sopydantic keeps it in the model's extra mapping.
_response_usagereads thatmapping rather than probing for an attribute, which is what lets the typed path
cover Chat Completions responses at all.
ResponsesAPIResponsedeclaresusagenormally.cache_write_tokensis derived fromprompt_tokens_details.cache_creation_tokensonly when that field is present in
model_fields_set. It defaults toNone,so presence in
model_fields_setis what distinguishes "the provider reported acache write" from "the provider said nothing about cache writes".