Skip to content

fix(sdk): normalize LLM usage telemetry through a typed adapter - #5029

Merged
VascoSch92 merged 2 commits into
OpenHands:mainfrom
Charlie-Wang-03:fix/4975-typed-usage-telemetry
Sep 22, 2026
Merged

VascoSch92 merged 2 commits into
OpenHands:mainfrom
Charlie-Wang-03:fix/4975-typed-usage-telemetry

Conversation

@Charlie-Wang-03

Copy link
Copy Markdown
Contributor

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

Telemetry reads provider token accounting out of LiteLLM response objects, but
LiteLLM reports that accounting in two disjoint shapes. Chat Completions
responses carry Usage (prompt_tokens / completion_tokens), while Responses
API responses carry ResponseAPIUsage (input_tokens / output_tokens). The
quantities are the same; the names are not.

Before this change, telemetry.py rediscovered those aliases at four separate
call sites by probing for them with getattr, so metrics, span attributes, and
the 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.py carried 24 entries in
scripts/forbidden_dynamic_attributes_baseline.json — the repository's own
AGENTS.md asks 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

  • Add a frozen UsageSnapshot dataclass and a module-level normalize_usage()
    that is the single boundary between the two provider shapes and the SDK's one
    internal vocabulary.
  • Telemetry.on_response now normalizes exactly once and hands the same
    snapshot to metrics, to the span, and to log_llm_call, so the completion log
    and the application's token accounting cannot disagree.
  • Remove _has_meaningful_usage and _cache_buckets along with the 24
    getattr allowances telemetry.py carried in the baseline, which now holds
    98 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:

uv run python -c "
from litellm.types.llms.openai import ResponseAPIUsage, InputTokensDetails, OutputTokensDetails
from litellm.types.utils import Usage, PromptTokensDetailsWrapper, CompletionTokensDetailsWrapper
from openhands.sdk.llm.utils.telemetry import normalize_usage

chat = Usage(prompt_tokens=1000, completion_tokens=250,
             prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=768),
             completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=64))
responses = ResponseAPIUsage(input_tokens=1000, output_tokens=250, total_tokens=1250,
             input_tokens_details=InputTokensDetails(cached_tokens=768),
             output_tokens_details=OutputTokensDetails(reasoning_tokens=64))
print('chat      :', normalize_usage(chat))
print('responses :', normalize_usage(responses))
print('absent    :', normalize_usage(None))
"

Both shapes print the same five fields, which is the point. Actual output:

chat      : UsageSnapshot(prompt_tokens=1000, completion_tokens=250, reasoning_tokens=64, cache_read_tokens=768, cache_write_tokens=0)
responses : UsageSnapshot(prompt_tokens=1000, completion_tokens=250, reasoning_tokens=64, cache_read_tokens=768, cache_write_tokens=0)
absent    : None

An unrecognized usage shape normalizes to None rather 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:

uv run pytest tests/sdk/llm/test_llm_telemetry.py tests/sdk/llm/test_llm_span_cost.py -q
# 53 passed in 0.31s

PYTHONUTF8=1 uv run python scripts/check_forbidden_dynamic_attributes.py \
  openhands-sdk/openhands/sdk/llm/utils/telemetry.py
# exit 0 -- telemetry.py has no remaining dynamic-attribute violations

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

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

Notes

Accounting behaviour is unchanged; only the route to the numbers changed. The
prompt_tokens_details is None cache fallbacks still hold, the usage_summary
payload still has exactly its four keys, and an absent usage object still
records nothing.

One deliberate subtlety worth a reviewer's attention: ModelResponse accepts
usage as a constructor argument but does not declare it as a field, so
pydantic keeps it in the model's extra mapping. _response_usage reads that
mapping rather than probing for an attribute, which is what lets the typed path
cover Chat Completions responses at all. ResponsesAPIResponse declares
usage normally.

cache_write_tokens is derived from prompt_tokens_details.cache_creation_tokens
only when that field is present in model_fields_set. It defaults to None,
so presence in model_fields_set is what distinguishes "the provider reported a
cache write" from "the provider said nothing about cache writes".

Charlie-Wang-03 and others added 2 commits September 13, 2026 17:55
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>
@VascoSch92
VascoSch92 enabled auto-merge (squash) September 13, 2026 22:21

@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: 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) and ResponseAPIUsage (Responses API) normalize to the same UsageSnapshot, and absent/unknown shapes return None instead of invented counts.
  • Confirmed against litellm 1.93.0 that ModelResponse does not declare usage as a field (extra="allow"), so pydantic keeps it in model_extra; _response_usage reads that mapping. Verified end-to-end through convert_to_model_response_object, litellm.stream_chunk_builder (streaming chat), and ResponsesAPIResponse.usage.
  • The model_fields_set cache-write gate and the Responses input_tokens_details.cached_tokens read preserve the removed _cache_buckets behavior; an Anthropic-style usage object still yields cache read/write correctly.
  • The removed private helpers (_has_meaningful_usage, _cache_buckets) and the changed _record_usage signature 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.py on telemetry.py exits 0; every check-run on the head SHA is success (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

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.

Normalize LLM usage telemetry through a typed adapter

3 participants