Repository navigation
Record Anthropic agent session token usage and cost in XCom - #71463
Merged
Merged
Conversation
kaxil
force-pushed
the
anthropic-session-usage-xcom
branch
from
August 11, 2026 19:58
e32520d to
3e44b9e
Compare
kaxil
marked this pull request as ready for review
August 11, 2026 19:58
kaxil
requested review from
amoghrajesh,
ashb,
bbovenzi,
bugraoz93,
choo121600,
dheerajturaga,
eladkal,
ephraimbuddy,
guan404ming,
jason810496,
jedcunningham,
jscheffl,
mobuchowski,
pierrejeambrun,
potiuk,
ryanahamilton,
shahar1,
shubhamraj-git,
uranusjr,
vatsrahul1001 and
vincbeck
as code owners
August 11, 2026 21:02
kaxil
removed request for
XD-DENG,
amoghrajesh,
bbovenzi,
bugraoz93,
choo121600,
dheerajturaga,
eladkal,
guan404ming,
henry3260,
jason810496,
jedcunningham,
jscheffl,
mobuchowski,
pierrejeambrun,
rawwar,
shahar1,
shubhamraj-git,
vatsrahul1001 and
vincbeck
August 11, 2026 21:47
kaxil
force-pushed
the
anthropic-session-usage-xcom
branch
from
August 12, 2026 06:38
e69f66c to
db8d322
Compare
Lee-W
reviewed
Aug 12, 2026
kaxil
force-pushed
the
anthropic-session-usage-xcom
branch
2 times, most recently
from
August 12, 2026 13:10
2e8acf5 to
a27bb08
Compare
Lee-W
approved these changes
Aug 13, 2026
A session budget is a stop trigger, not a spend cap: the ceiling is
checked between model requests, so a request already in flight runs to
completion. Measured against the live API, a $0.01 ceiling admitted
between $0.32 and $0.61 of usage across four runs. Setting a budget
therefore tells you nothing about what a run actually cost, and the
operator returned only a session ID.
``AnthropicAgentSessionOperator`` now pushes the session's usage to XCom
under ``usage``, making cost per Dag run queryable:
{"input_tokens": 827, "output_tokens": 14002,
"cache_read_input_tokens": 0,
"cache_creation": {"ephemeral_5m_input_tokens": 0,
"ephemeral_1h_input_tokens": 0},
"server_tool_use": {"web_search_requests": 0,
"web_fetch_requests": 0},
"active_seconds": 213.7,
"list_cost": {"amount": "36", "currency": "USD"},
"try_number": 1}
``AnthropicHook.get_session_usage`` flattens the SDK models to plain
scalars so the value survives XCom serialization. ``amount`` stays the
API's minor-unit string rather than becoming a float, because a cost
figure must not pick up binary rounding. ``list_cost`` is ``None`` when
usage includes a model with no list price -- and that is exactly when a
caller has to price the run from usage instead, so every billable
dimension is reported: cache writes are billed above base input and
server tool calls are billed per request.
Usage is recorded on failure as well as success, since a budget-stopped
session is precisely the one whose spend needs recording. Teardown runs
first on the failure paths: it is the time-critical call, and
``sessions.archive`` returns the session carrying its final usage, so
``summarize_usage`` reports spend without a second request against an API
that may be why the task is failing. If archiving fails, usage falls back
to a fetch. The whole push is best effort -- it runs immediately before
re-raising, so anything that throws there would otherwise replace the
exception the task should fail with.
Airflow clears XCom at the start of each attempt, so ``usage`` holds the
final attempt only; ``try_number`` records which, and the docs say total
spend across retries must be summed from the session records.
Verified end to end against the live API: a real deferred run resumed by
a real triggerer failed with AnthropicSessionBudgetExceeded and left the
usage above in XCom, read back over the REST API.
18 of 91 tasks
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.
Problem
A session budget is a stop trigger, not a spend cap: the ceiling is checked between model
requests, so a request already in flight runs to completion. Measured against the live API,
a $0.01 ceiling admitted between $0.32 and $0.61 across four runs. Setting a budget
therefore tells you nothing about what a run actually cost, and the operator returned only a
session ID.
Solution
The session's usage is pushed to XCom under
usageon both success and failure, so costper Dag run is queryable and a budget-stopped run still records what it consumed:
{ "input_tokens": 814, "output_tokens": 14002, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "active_seconds": 213.666, "list_cost": {"amount": "36", "currency": "USD"}, "try_number": 1, }amountstays the API's minor-unit string rather than becoming a float, because a costfigure must not pick up binary rounding.
list_costisNonewhen usage includes a modelwith no list price -- which is exactly when a caller has to price the run from usage
instead, so every billable dimension is reported: cache writes are billed above base
input, and server tool calls are billed per request.
Teardown runs first on the failure paths. It is the time-critical call, and
sessions.archivereturns the session carrying its final usage, so spend is reportedwithout a second request against an API that may be the reason the task is failing. If
archiving fails, usage falls back to a fetch. The whole push is best effort: it runs
immediately before re-raising, so anything that throws there would otherwise replace the
exception the task should fail with.
Verified end to end
A real deferred run, resumed by a real triggerer against postgres, failed with
AnthropicSessionBudgetExceededand left the usage above in XCom, read back over the RESTAPI.
Gotchas
Airflow clears a task's XCom at the start of every attempt, so
usageholds the finalattempt only and
try_numberrecords which one that was. With retries enabled, totalspend across attempts is not recoverable from this key and must be summed from the session
records.
retries=0keeps this and the fresh-budget-per-retry problem away together.