Repository navigation
fix(ai): report OpenAI Agents cached and reasoning tokens #1102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mosafariuk
wants to merge
2
commits into
PostHog:main
Choose a base branch
from
mosafariuk:fix/openai-agents-cache-reasoning-tokens
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+221
β5
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog: patch | ||
| --- | ||
|
|
||
| Report cached input and reasoning tokens from OpenAI Agents generation and response spans, which nest them under the usage details fields. |
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
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1]Declare inclusive accounting when forwarding compatible-provider cache usage
IMPORTANT Β· REQUIRED Β· Amplified pre-existing defect
Location:
posthog/ai/openai_agents/processor.py:561β565, RIGHT.A cached Claude request through an OpenAI-compatible endpoint can now make PostHog's estimated input cost increase instead of decrease. The newly emitted cached tokens are already included in the input total, but the backend treats Claude-model usage as exclusive unless
$ai_cache_reporting_exclusiveexplicitly says otherwise.An ordinary supported caller is:
Agents documents compatible-provider configuration. OpenRouter documents inclusive prompt usage, with
10339prompt tokens including10318cached tokens,60completion tokens and no cache writes. Agents normalizes these details without changing the total.The pinned backend calculator infers exclusive accounting from the Anthropic/Claude model name despite
$ai_provider: "openai". Explicitfalseoverrides it. Model/provider lookup resolves this model to catalog rates of$3/Mordinary input and$0.30/Mcached input.Using the same documented-shaped synthetic response through real
Runner.run,instrument, SDK queue and HTTP delivery on both revisions, then executing that backend calculator on the captured properties:$0.031017$0.0341124$0.0031584The correct calculation is
(10339 β 10318) Γ 0.000003 + 10318 Γ 0.0000003.Base was already wrong. This patch amplifies that defect by another
$0.0030954per fixture request, approximately 10% above the previous estimate. It affects analytics estimates, not the provider's actual bill. The demonstrated trigger is cached, inclusive Chat Completions usage with a model matched by the backend's Claude heuristic and no explicit convention/cost override; ordinary GPT requests are unaffected.Consider declaring
$ai_cache_reporting_exclusive: falsefor recognized inclusive nested-usage paths, preserving custom flat-key conventions and caller overrides. The Node Agents processor already declares this convention for Chat Completions and Responses. Add a compatible-Claude regression alongside the GPT case; the corresponding Responses mapping should remain consistent where its provider contract is inclusive.Executed regression:
Executed under identical Python/provider dependencies with sandboxed
PYTHONPATH=<snapshot> python -m pytest -p pytest_timeout -c /dev/null --rootdir=<runtime> --confcutdir=<runtime> test_cache_reporting.py --timeout=30 -q -p no:cacheprovider:None is False.node cost-check.cjsexits 0 confirming amplification and the inclusive control;node cost-check.cjs --assert-correctexits 1 withhead cost 0.0341124, expected 0.0031584. It executes pinned calculator source with TypeScript erasure/module-linkage substitution and realjs-big-decimal; only logger/metrics are stubbed, not arithmetic. No full ingestion stack was run.A verified supported mitigation is
instrument(posthog_client, properties={"$ai_cache_reporting_exclusive": False}). It is processor-wide, not automatic per-model handling, and can be inappropriate for mixed custom-model conventions. No fix was applied or tested.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch, thanks. Fixed in 4de76ae.
$ai_cache_reporting_exclusive: False, on both generation spans (input_tokens_details/prompt_tokens_details) and response spans. This matches the Node processor.cache_read_input_tokensfrom custom models gets no flag, so their own convention is kept.$ai_cache_reporting_exclusive(viainstrument(..., properties=...)) still wins, because processor-wide properties are merged last.Tests:
test_cached_compatible_claude_usage_is_declared_inclusiveas written. It fails on e424062 (None is False) and passes now.test_flat_cache_keys_keep_their_own_conventionandtest_caller_cache_reporting_convention_takes_precedence.Running real
Runner.runwithOpenAIChatCompletionsModel("anthropic/claude-sonnet-4.6")and your OpenRouter-shaped usage now captures$ai_input_tokens: 10339,$ai_cache_read_input_tokens: 10318and$ai_cache_reporting_exclusive: false. That's the inclusive interpretation behind your$0.0031584.Full suite: 5136 passed, 16 skipped. Ruff, mypy and the public API check are clean.