Skip to content

Record Anthropic agent session token usage and cost in XCom - #71463

Merged
kaxil merged 1 commit into
mainfrom
anthropic-session-usage-xcom
Aug 13, 2026
Merged

kaxil merged 1 commit into
mainfrom
anthropic-session-usage-xcom

Conversation

@kaxil

@kaxil kaxil commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

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 usage on both success and failure, so cost
per 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,
}

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 -- 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.archive returns the session carrying its final usage, so spend is reported
without 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
AnthropicSessionBudgetExceeded and left the usage above in XCom, read back over the REST
API.

Gotchas

Airflow clears a task's XCom at the start of every attempt, so usage holds the final
attempt only
and try_number records which one that was. With retries enabled, total
spend across attempts is not recoverable from this key and must be summed from the session
records. retries=0 keeps this and the fresh-budget-per-retry problem away together.

@kaxil
kaxil force-pushed the anthropic-session-usage-xcom branch 2 times, most recently from 2e8acf5 to a27bb08 Compare August 12, 2026 13:10
@kaxil
kaxil requested a review from Lee-W August 12, 2026 13:37

@Lee-W Lee-W 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. the remaining are nits.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants