Skip to content

fix(ai): keep latest cumulative output tokens across message_deltas - #1100

Merged
marandaneto merged 2 commits into
PostHog:mainfrom
Harsh23Kashyap:fix/anthropic-stream-delta-output-tokens
Oct 22, 2026
Merged

marandaneto merged 2 commits into
PostHog:mainfrom
Harsh23Kashyap:fix/anthropic-stream-delta-output-tokens

Conversation

@Harsh23Kashyap

Copy link
Copy Markdown
Contributor

Closes #1099.

What

A streamed Anthropic generation over-reported output tokens when its stream contained more than one message_delta. Each delta's usage is cumulative, but the accumulator merged output_tokens incrementally, so a stream whose deltas reported 50 then 110 cumulative tokens captured 160.

Fix

For message_delta events, keep the latest cumulative output_tokens instead of adding it, the same way #1074 handles the input and cache counts, and matching how the Anthropic SDK accumulates usage ('cumulative totals, so they overwrite rather than add').

Tests

New sync and async tests pin a stream with two cumulative message_deltas (pause_turn then end_turn) to the final total of 110. Full posthog/test/ai/anthropic/test_anthropic.py: 47 passed, 1 skipped.

@Harsh23Kashyap
Harsh23Kashyap requested a review from a team as a code owner October 21, 2026 19:37
@marandaneto

Copy link
Copy Markdown
Member

thanks @Harsh23Kashyap

Commits must have verified signatures.

for next PRs

Harsh23Kashyap and others added 2 commits October 22, 2026 12:23
Server tools such as web search can emit several message_delta events in
one Anthropic stream, and each delta's usage is cumulative. The stream
accumulator added every delta's output_tokens together, so a stream with
two deltas reporting 50 then 110 cumulative tokens captured 160. Keep
the latest cumulative value, matching how the input and cache counts are
already handled and how the Anthropic SDK accumulates usage.
@marandaneto
marandaneto force-pushed the fix/anthropic-stream-delta-output-tokens branch from f7d2700 to 3844c36 Compare October 22, 2026 10:24
@marandaneto
marandaneto enabled auto-merge (squash) October 22, 2026 10:25
@marandaneto
marandaneto merged commit 34ec4f8 into PostHog:main Oct 22, 2026
42 checks passed
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.

Streamed Anthropic generations stack output tokens when a stream emits more than one message_delta

2 participants