Skip to content

fix(visualizer): show per-request token usage alongside cumulative to… - #4146

Merged
VascoSch92 merged 7 commits into
OpenHands:mainfrom
luciobaiocchi:fix/4105-per-request-metrics-v2
Jul 22, 2026
Merged

VascoSch92 merged 7 commits into
OpenHands:mainfrom
luciobaiocchi:fix/4105-per-request-metrics-v2

Conversation

@luciobaiocchi

@luciobaiocchi luciobaiocchi commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

While debugging LLM costs I kept misreading the running totals shown under
each event as per-request token usage. This PR makes the visualizer show
both, so the numbers finally mean what they look like.


AGENT:

Why

Fixes #4105. The metrics subtitle under each event showed only cumulative
totals ("↑ input 54k"), which read as per-request usage. Readers (including
while debugging cost issues) misinterpret running totals as single-request
numbers, and there was no way to tell the two apart.

Summary

  • _format_metrics_subtitle() now takes the event being rendered and shows
    per-request usage alongside the running total: ↑ input 4.63K (total 9.02K).
    Reasoning tokens and cache hit rate get the same per-request treatment.
  • Per-request usage is found by matching event.llm_response_id against
    TokenUsage.response_id (_find_request_usage()), not by taking
    token_usages[-1] — the combined list merges agent/condenser usages and is
    not chronological across them.
  • Events with no attributable request (user messages, AgentErrorEvent,
    unknown or per-session response ids as in ACP) fall back to totals-only —
    now labeled explicitly: ↑ input 54K (total) • … • $ (total 0.4231).
    Labeling was chosen over skipping because ACP events never match, so
    skipping would remove the subtitle entirely for ACP transcripts.
  • Cost is always shown as $ (total …): Cost entries carry no
    response_id (unlike TokenUsage), so per-request cost cannot be
    attributed today (see Notes).
  • DelegationVisualizer forwards the event into _format_metrics_subtitle
    in both of its render paths, so delegate transcripts use the same format.

Issue Number

Fixes #4105

How to Test

uv run pytest tests/sdk/conversation/test_visualizer.py tests/tools/delegate/test_visualizer.py -v

7 new tests: per-request vs cumulative placement (full-string assertion),
per-request reasoning/cache-hit, response_id lookup vs naive last-index
(agent + condenser interleaved), labeled totals-only fallback (no event /
unknown response id), user-message fallback, delegate event forwarding, and
delegate labeled fallback. All 40 visualizer tests pass; ruff and
pyright clean.

Manual check: run any example (e.g.
uv run python examples/01_standalone_sdk/01_hello_world.py) and compare
the subtitle under an agent action (per-request + total) with the one under
a user message (labeled totals).

Video/Screenshots

Subtitle for an event with attributable usage:

Tokens: ↑ input 4.63K (total 9.02K) • cache hit 50.00% (total 36.67%) • ↓ output 114 (total 258) • $ (total 0.4231)

Fallback (user message / ACP / error events):

Tokens: ↑ input 9.02K (total) • cache hit 36.67% (total) • ↓ output 258 (total) • $ (total 0.4231)

Type

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

Notes

  • Output change for previously totals-only subtitles: they now carry
    explicit (total) labels. No API changes; visualizer-only.
  • Follow-up candidate: add response_id to Cost (as ResponseLatency
    already has) to enable true per-request cost. Kept out of this PR per
    review discussion.

- Replace getattr with isinstance check for llm_response_id lookup
- Use walrus operator in _find_request_usage; drop redundant final return
- Fix DelegationVisualizer to forward event into _format_metrics_subtitle
  so ActionEvent/MessageEvent subtitles no longer stay cumulative-only
  while other event types show per-request numbers
- Clarify docstring: response_id matching is not guaranteed on the ACP path
- Give reasoning tokens and cache hit rate the same per-request "(total X)"
  treatment as input/output tokens, avoiding unlabeled cumulative numbers
  next to per-request ones
- Strengthen test to assert the full formatted subtitle string instead of
  loose substring checks
- Add regression tests for the DelegationVisualizer event-forwarding bug
  and the reasoning/cache-hit formatting bug
@luciobaiocchi

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @VascoSch92 — addressed all of it in 6c7d08f:

  • getattr on _find_request_usage: replaced with an explicit isinstance(event, (ActionEvent, MessageEvent, Condensation)) check against the classes that
    actually declare llm_response_id, so it's properly typed instead of silently swallowing mismatches.
  • Walrus operator: applied to the conversation_stats check.
  • Redundant return None: removed the trailing one; the declared TokenUsage | None return type already covers the implicit fallthrough (confirmed clean
    with pyright).
  • DelegationVisualizer not forwarding event: this was the real bug — fixed both call sites (visualizer.py:168 and :247) to pass
    self._format_metrics_subtitle(event). Added a regression test (test_delegation_visualizer_action_event_shows_per_request_usage) since nothing previously
    caught this.
  • Docstring overclaiming a 1:1 response_id correspondence: reworded to call out that the ACP path does not guarantee it and falls back to cumulative-only,
    matching your note about acp_agent.py.
  • Reasoning tokens / cache hit staying cumulative-only: both now get the same X (total Y) treatment as input/output when a per-request match exists (cache
    hit reuses the existing MetricsSnapshot.cache_hit_rate property instead of duplicating the formula). Added
    test_metrics_subtitle_reasoning_and_cache_hit_are_per_request to cover the exact case you flagged as untested.
  • Weak test assertions: replaced the loose in subtitle checks in test_metrics_subtitle_shows_per_request_and_cumulative with a single exact full-string
    assertion, so number placement is actually pinned down.

ruff check, ruff format --check, and pyright are clean on the changed files; the visualizer test suites (38 tests) pass.

@luciobaiocchi
luciobaiocchi requested a review from VascoSch92 July 20, 2026 17:38
@VascoSch92 VascoSch92 self-assigned this Jul 20, 2026

@VascoSch92 VascoSch92 left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Rebase looks good and last round's stuff is all handled: reasoning and cache hit are per-request now, delegate visualizer passes the event through in both spots.

I did go check whether the response_id lookup is actually safe after a resume, since that was my worry. It is. restore_metrics shares the object by reference so usage_to_metrics doesn't go stale, and merge concatenates per usage-id so token_usages[-1] genuinely would have been wrong. Good call there.

Two things left and they're really the same thing: numbers on that line that aren't labelled. Inline.

Also description still says three new tests, there's five.

Comment thread tests/tools/delegate/test_visualizer.py Resolved
luciobaiocchi and others added 4 commits July 21, 2026 15:30
Round-2 review feedback on OpenHands#4146: cost is always cumulative (Cost entries
carry no response_id, unlike TokenUsage) and now says so; events with no
attributable per-request usage (user messages, unknown/per-session
response ids as in ACP) label every number (total) instead of printing
bare cumulative values that read as per-request.
- cost prints as '$ (total 0.4231)' as suggested, so nothing on the
  line is unlabeled; a per-request cost needs response_id on Cost
  entries, which is a separate PR
- _find_request_usage: collapse the double loop into next(...)
- fix delegate test docstring: only Condensation carries an
  llm_response_id; AgentErrorEvent does not show per-request numbers
The fallback previously appended a bare '(total)' label; the review asks
for '(total 54K)' so unattributable events (user messages,
AgentErrorEvent, ACP) use the same shape as the per-request format and
the cost field.

@VascoSch92 VascoSch92 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM.

There is just one thing with parallel tool execution that I saw just now. response_dispatch.py:205-210 emits one ActionEvent per tool call, all sharing the same llm_response_id, so a parallel batch repeats the identical per-request numbers.

Therefore, you will have duplication in the output (but this is just missleading is not affecting the final results).

It is not a blocker. But if you could open a follow up PR would be great :-) (but up to you)

@VascoSch92
VascoSch92 merged commit cae92b8 into OpenHands:main Jul 22, 2026
31 of 32 checks passed
@luciobaiocchi

Copy link
Copy Markdown
Contributor Author

LGTM.

There is just one thing with parallel tool execution that I saw just now. response_dispatch.py:205-210 emits one ActionEvent per tool call, all sharing the same llm_response_id, so a parallel batch repeats the identical per-request numbers.

Therefore, you will have duplication in the output (but this is just missleading is not affecting the final results).

It is not a blocker. But if you could open a follow up PR would be great :-) (but up to you)

yes for sure, i will open an issue first

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.

Visualizer metrics subtitle shows only cumulative token usage, easily mistaken for per-request usage

2 participants