fix(ai): omit token counts the provider never reported - #906
Open
bernatixer wants to merge 2 commits into
Open
Conversation
Every integration wrote $ai_input_tokens: 0 and $ai_output_tokens: 0 when the provider never reported usage, so an interrupted stream priced as a free call downstream. Token counts are now written only when they trace back to a provider report: the shared capture paths, both embedding events, the LangChain callback and the Agents and Claude Agent SDK processors omit unreported counts, and the stream accumulators and response extractors no longer seed at zero. A zero the provider reported is still sent as 0, so zero keeps meaning a real report of nothing. LangChain cache and reasoning counts follow the same rule instead of coalescing to 0, and the Agents processor's $ai_total_tokens is the sum of the reported sides, omitted when neither side reported. Mirrors the posthog-js change (PostHog/posthog-js#4664). Ingestion distinguishes absent from zero since PostHog/posthog#90211 and older ingestion coalesces absent to 0 at read time, so this ships independently. Generated-By: PostHog Desktop Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
Contributor
posthog-python Compliance ReportDate: 2026-08-31 21:20:27 UTC ✅ All Tests Passed!111/111 tests passed Capture_V1 Tests✅ 94/94 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
|
extract_gemini_embedding_token_count now returns Optional[int], returning None when no embedding carried a token count. Regenerated with make public_api_snapshot. Generated-By: PostHog Desktop Task-Id: ec0cc27f-fc40-4994-b153-2bfe74de1edf
bernatixer
marked this pull request as ready for review
August 31, 2026 21:21
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
💡 Motivation and Context
An LLM call whose provider never reported usage shows up as
$0.00in LLM analytics. Every integration sent$ai_input_tokens: 0and$ai_output_tokens: 0for it, and ingestion prices a call by multiplying a rate with that count. The common case is a cancelled stream: it consumed its prompt, but usage only arrives at the end.Token counts are now written only when they trace back to a provider report:
posthog/ai/utils.py, the OpenAI and Gemini embedding events, the LangChain callback, and the OpenAI Agents and Claude Agent SDK processors.0. Zero keeps meaning a real report of nothing.0.$ai_total_tokenson the Agents processor is the sum of the reported sides, omitted when neither side reported.This applies the PostHog/posthog-js#4664 semantic to this SDK, following the cross-SDK assessment on that PR. Ingestion distinguishes absent from zero since PostHog/posthog#90211. Older ingestion coalesces absent to 0 at read time, so this ships independently.
Note
$ai_input_tokensand$ai_output_tokenswere previously always present on wrapper events. Anything reading them downstream has to handle absence.💚 How did you test it?
0, one-sided usage sends one side. It fails when the.get(..., 0)default is restored, verified by reverting it.== 0, which pins the boundary.posthog/test/aisuite passes locally: 648 passed, 5 skipped. The 9 failing tests make live provider calls that this sandbox's gateway rejects with 403, and they fail identically with the change stashed.ruff format,ruff check, and the CI mypy command (throughmypy-baseline filter) pass.extract_gemini_embedding_token_countnow returnsOptional[int], the one intentional signature change.mainin the same environment (verified locally), and two of the four jobs fail during setup before any test runs. It points at an upstream MCP SDK or fastmcp release from today and will affect the next run onmaintoo.📝 Checklist
If releasing new changes
.sampo/changesets/(hand-written in thesampo addformat)🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Written by Claude Code in a PostHog Desktop session directed by @bernatixer, as the cross-SDK follow-up agreed on PostHog/posthog-js#4664. An audit found the fabrication concentrated at the shared property-write layer plus the zero-seeded accumulators. Cancellation handling needed no work here: the stream wrappers already capture from a
finallyand close the generator on early exit.Decisions: provider-reported zeros keep sending
0, pinned by two existing LangChain fixtures.$ai_total_tokensstays a sum of reported sides rather than being omitted on partial usage, matching the lower-bound totals decision on the JS PR. The unused zero defaults inside_get_tokens_sourcestay untouched to keep the diff behavioral.Skills invoked: writing-tests, writing-pr-descriptions.
Created with PostHog Desktop