Spend
Track what an agent costs, and stop it when a budget is gone.
flowchart TB
accTitle: Spend: budgets that outlast one run
accDescr: On each model request of an agent run, SpendLimits before_model_request reads every window from the spend store (in memory, Redis or PostgreSQL). With all under ceiling the request goes to the model, and with a window spent it is not sent and ends in SpendLimitExceeded. SpendLimits wrap_model_request takes the model's response and adds its price to each window in the store.
run["agent run"]
before["SpendLimits()<br/>before_model_request"]:::capability
model(["model"])
refused["SpendLimitExceeded<br/>request is not sent"]:::blocked
wrap["SpendLimits()<br/>wrap_model_request"]:::capability
store[("spend store<br/>in memory, Redis<br/>or PostgreSQL")]:::external
run -->|"each model request"| before
before -->|"all under ceiling"| model
before -.-x|"a window is spent"| refused
model -->|"response"| wrap
before <-->|"reads every window"| store
wrap -->|"adds its price<br/>to each window"| store
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
A loop that calls a model until a condition it never reaches keeps calling until something stops it. Pydantic AI’s UsageLimits caps tokens, requests and cost for a run(), counting on from the usage the run carries in with conversation= or usage=. It does not cover a time period such as a day, a per-tenant share of an allowance, or a counter shared by several workers: with a daily ceiling spread across a queue, each worker sees only its own spend.
Provider usage APIs are polled and report requests only after they are made. That is enough to reconcile a bill, not to refuse a runaway loop’s next request.
SpendLimits adds each response’s price to every configured window and refuses the next request once a window is spent. Pricing covers how a response is priced.
from decimal import Decimal
from pydantic_ai import Agent
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget
agent = Agent(
'openai:gpt-6.1-sol',
capabilities=[SpendLimits(budgets=[Budget(usd=Decimal('100'), window='day')])],
)
Past $100 in a UTC day, the next request raises SpendLimitExceeded.
A Budget is a ceiling, a period, and optionally a partition. Several apply at once:
from decimal import Decimal
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget
SpendLimits(
budgets=[
Budget(usd=Decimal('5'), window='run'), # one runaway run
Budget(usd=Decimal('100'), window='day'), # the whole deployment, per day
Budget(usd=Decimal('2000'), window='month', warn_at=0.8),
Budget(usd=Decimal('10'), window='day', scope=lambda ctx: ctx.deps.tenant_id, name='tenant'),
]
)
| Field | Meaning |
|---|---|
usd / tokens | ceilings; set either, both, or neither, as a value or a callable resolving one from the run |
window | run, conversation, day (default), month, total |
scope | derives a partition key from the run, so tenants count separately; typed against the agent’s deps |
warn_at | fraction past which BudgetStatus.warning is set; never blocks |
name | distinguishes budgets sharing a window and scope; defaults to 'default' |
retain | how long the counter is kept after its last write: 'window default' (default), 'forever', or a timedelta |
A window rolls over by producing a new store key, so nothing resets at midnight. A total counter never expires. run and conversation windows never roll over, but mint a key per run or conversation, so they expire 24 hours and 30 days after their last write; that expiry hands back the ceiling, and a conversation resumed past its horizon starts from zero. Set retain='forever' where a conversation ceiling must hold for the whole conversation, and clean the keys up some other way.
Budgets sharing a name, window, and scope share one counter, which is how one window carries both a USD and a token ceiling; each response is added once. Construction refuses:
- the same
nameandwindowwith differentscopecallables: two dimensions (per tenant, per user) that would merge whenever both return the same string. Use different names, or one callable. - a shared counter with different
retainvalues: one counter has one expiry, so declaration order would decide when a'forever'ceiling rolls over. - two
usd(or twotokens) ceilings on one counter: only the smaller would apply.
Budget is generic in the agent’s dependency type, so with a deps_type, a scope reading a missing field is a type error, not an AttributeError on the first request.
A ceiling can come from the run, so each partition gets its own allowance (a customer’s plan, an agent’s cap, a job’s approved budget) instead of sharing one number:
from dataclasses import dataclass
from decimal import Decimal
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget
@dataclass
class Account:
id: str
allowance_usd: Decimal | None
SpendLimits[Account](
budgets=[
Budget(
usd=lambda ctx: ctx.deps.allowance_usd,
window='month',
scope=lambda ctx: ctx.deps.id,
name='account',
),
]
)
The callable takes the run context, like scope (the Ceiling type alias names the accepted forms). It is called whenever the budget is read, more than once per request, so have it read values the application loaded before the run.
Nonemeans no ceiling on that partition.- Unlike a plain ceiling, a resolved zero or less is accepted: the partition reads as exhausted and its requests raise
SpendLimitExceeded. - The refusal,
warn_at,BudgetStatus.usd_limit,token_limitandSpendRecordedEventuse the resolved ceiling.BudgetStatus.budgetstays as configured. - If the callable raises, the run fails with that error. The response is still accrued, but neither
SpendRecordedEventnoron_spendreports it. - Counters are not keyed on the ceiling, so a partition’s spend carries over when its allowance changes.
A budget with no ceiling counts and reports but never refuses, for per-tenant accounting with no cap:
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget
SpendLimits(budgets=[Budget(window='month', scope=lambda ctx: ctx.deps.tenant_id, name='chargeback')])
Once a recorded response spends a window, SpendLimits refuses the next request.
It does not keep spend under the ceiling: the request that crosses the line completes, and concurrent runs can each pass the check before any records anything. A stream stopped part-way is charged for the usage reported so far, which can fall short of the bill, since many providers report output tokens only in the last event. Reconcile against the provider’s numbers for exact totals.
from decimal import Decimal
from pydantic_ai import Agent
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget, SpendRecordedEvent
limits = SpendLimits(budgets=[Budget(usd=Decimal('100'))])
agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[limits])
@agent.on_event(SpendRecordedEvent)
async def show(ctx, event):
print(f'{event.model} cost ${event.usd}')
SpendRecordedEvent carries the response usage and serializable budget readings. It is emitted after each response SpendLimits records, including one on_unpriced='raise' is about to reject. A response a FallbackModel or the ModelFallback capability rejected gets its own event (failed_attempt=True) and on_spend call with that attempt’s model and usage; see Composition. Under durable execution an event can be delivered again although the journaled accrual ran once, so keep listeners that write audit or billing records idempotent.
on_spend is deprecated but still works, with the same idempotency requirement; move its body to a SpendRecordedEvent subscription.
status() reads the same numbers outside a run, for a cost display in a UI:
from pydantic_ai_harness import SpendLimits
async def report(limits: SpendLimits[None]) -> None:
for status in await limits.status(scope='acme'):
print(status.budget.name, status.spent.usd, status.exhausted)
Without a run context, run and conversation budgets are omitted, as are budgets with a callable ceiling, and scoped budgets unless scope= names the partition. Inside a run, pass ctx instead and every budget resolves; passing both is refused.
expose_tools=True gives the agent a get_spend tool. It is off by default: a tool costs schema tokens on every request, and most applications want the number on a screen, not in the model’s context. To show the model its remaining budget on every request, use Report Remaining Budget.
Spend events are reports, not approval points: they can follow the response carrying the final answer. To act before a request, read status(ctx) in a capability’s before_model_request and hold the run until someone decides:
import asyncio
from dataclasses import dataclass
from decimal import Decimal
from pydantic_ai import Agent
from pydantic_ai.capabilities import AbstractCapability
from pydantic_ai.models import ModelRequestContext
from pydantic_ai.tools import RunContext
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget
limits = SpendLimits[None](budgets=[Budget(usd=Decimal('100'), warn_at=0.8)])
approvals: asyncio.Queue[bool] = asyncio.Queue()
@dataclass
class ApproveBeforeSpending(AbstractCapability[None]):
async def before_model_request(
self, ctx: RunContext[None], request_context: ModelRequestContext
) -> ModelRequestContext:
if any(status.warning for status in await limits.status(ctx)) and not await approvals.get():
raise RuntimeError('spending past the warning threshold was not approved')
return request_context
agent = Agent('openai:gpt-6.1-sol', deps_type=type(None), capabilities=[limits, ApproveBeforeSpending()])
The gate sees the previous response, which SpendLimits accrued inside wrap_model_request. It also gates a run’s first request, so a threshold crossed by an earlier run carries into the next. A capability listed after it can still skip the request with SkipModelRequest, so an approval here does not prove a request followed.
The pause holds a coroutine, so it lasts only as long as the process. To pause across processes, gate at a tool call: deferred tool calls end the run with a serializable approval request that a later run resumes. Or stop the run and resume it from its message history, as below.
budgets is read on every request, so replacing it after a refusal continues the work against a larger ceiling. Counters are keyed on name, window, scope and the current period, not the ceiling, so what is spent carries over.
A refusal can land mid-run, after tool calls have run and been paid for. Re-running the prompt would repeat them and their side effects; instead, capture_run_messages holds the partial history, and a run given that history and no new prompt continues from the refused request.
import dataclasses
from decimal import Decimal
from pydantic_ai import Agent, capture_run_messages
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget, SpendLimitExceeded
limits = SpendLimits[None](budgets=[Budget(usd=Decimal('1'), name='daily')])
agent = Agent('openai:gpt-6.1-sol', deps_type=type(None), capabilities=[limits])
async def ask(prompt: str, ceiling: Decimal) -> str:
with capture_run_messages() as messages:
try:
return (await agent.run(prompt)).output
except SpendLimitExceeded:
(budget,) = limits.budgets
limits.budgets = [dataclasses.replace(budget, usd=ceiling)]
resumable = list(messages)
return (await agent.run(message_history=resumable)).output
Assigning budgets skips the constructor’s checks on budget combinations, so keep the same names, windows, and scopes. The new ceiling applies to every run sharing this SpendLimits, and nothing lowers it again. To raise one partition’s ceiling, resolve it from the run with a callable usd or tokens and change the value it reads.
The default InMemorySpendStore keeps counters in the process: it catches a runaway loop inside one worker and does nothing for a budget spread across a queue. RedisSpendStore and PostgresSpendStore share one counter across workers:
from decimal import Decimal
from redis.asyncio import Redis
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget, RedisSpendStore
store = RedisSpendStore(Redis.from_url('redis://localhost'))
limits = SpendLimits(budgets=[Budget(usd=Decimal('100'), window='day')], store=store)
RedisClient is a protocol of the two coroutines the store uses, so any compatible client works and the harness adds no dependency.
Amounts are integer billionths of a dollar, so counters don’t drift with rounding error over many requests, and a key holds up to about $9.22 billion. One script applies every window of a response, so no client sees it half-applied, unless a counter overflows, which keeps the windows already applied. A write that errors has an unknown outcome, since the connection can drop after the write landed, and nothing retries it.
Keys are {prefix}:budget-key. The braces are a Redis Cluster hash tag, which puts all of a store’s keys in one slot so one script can update several, and a cluster keeps them all on one node. An empty prefix, or one containing a brace, is refused. BudgetStatus.key omits the prefix.
Counters an earlier release wrote without the hash tag are still read and added to the total, so upgrading needs no migration. During a rolling deploy, old-release workers miss what upgraded workers wrote, so keep the deploy short, and treat a downgrade as a reset. Nothing refreshes the old key’s expiry, so when it expires the total drops by what it held. The fallback goes away in 0.28.0. Before that, move by hand any window with retain='forever' or a horizon longer than the gap between the two releases.
add_many carries a token identifying the response, and every bundled store applies a token once per key within dedup_retain (see below), recording a marker atomically with the increments (in Redis’s script, in Postgres’s transaction, or under the in-memory store’s lock while its process lives). The token combines the run id and step with a digest of replay-stable response content, usage, and provider identity, excluding clock-derived values and arbitrary provider bookkeeping. It catches recovery that presents an entry without consulting the journal only if the original run and its recovery pass the same run_id to Agent.run; otherwise Pydantic AI creates a fresh id and the store cannot recognise the entry. Ordinary durable replay is covered by the journaled _accrue operation regardless.
Markers cost one small key or row per response per window and are held for dedup_retain (a constructor argument on every bundled store, one hour by default), or the window’s horizon if shorter. A response presented again later is counted again, an over-count rather than an under-count. dedup_retain=None holds no markers and applies every entry. A response counted before the upgrade left no marker, so presenting it again counts it again.
PostgresSpendStore suits a deployment that already runs PostgreSQL (alongside a Postgres-backed durable execution engine, say) and would rather not add Redis:
from decimal import Decimal
import asyncpg
from pydantic_ai_harness import SpendLimits
from pydantic_ai_harness.spend_limits import Budget, PostgresSpendStore
async def build_limits() -> tuple[SpendLimits[None], asyncpg.Pool]:
pool = await asyncpg.create_pool('postgres://localhost/app')
limits = SpendLimits(budgets=[Budget(usd=Decimal('100'), window='day')], store=PostgresSpendStore(pool))
return limits, pool
Call build_limits at startup and close the pool at shutdown; the store does not manage it. It takes the driver-neutral PostgresPool protocol from pydantic_ai_harness.media, which an asyncpg pool satisfies, so the harness adds no driver dependency. Install the driver yourself:
pip install asyncpg
uv add asyncpg
The store creates two tables on first use: {table}_counters and {table}_dedup. table defaults to 'spend' and must be lowercase letters, digits and underscores, start with a letter or underscore, and be at most 47 characters.
Creating the tables needs CREATE on the schema, and workers starting together don’t collide. Afterwards, SELECT, INSERT, UPDATE and DELETE on the tables are enough. There are no migrations: an existing table of either name with a different layout makes the first call fail, so pass table= if the name is taken.
As with Redis, amounts are integer billionths with the same range. One transaction applies every window of a response with its dedup markers, so any failure rolls back the whole response. The store sets the READ COMMITTED isolation level for its writes itself. A connection dropped after the commit was sent leaves the outcome unknown, and nothing retries it.
Windows roll over on the server’s clock, so every worker agrees on when a window ends. Every sweep_every entries it writes (256 by default), a store instance deletes expired counters and markers; a sweep that fails is logged as a warning, not raised. A process that writes fewer entries never sweeps, so lower sweep_every, or delete rows past expires_at on your own schedule. dedup_retain, and an entry’s ttl when you drive the store yourself, must be positive or None.
The default store is built per capability, so two SpendLimits share a counter only if given the same store object. InMemorySpendStore loses its counters and deduplication markers with its worker, so durable workflows that can recover on another worker need a shared store.
Store errors are not swallowed. A read error refuses the request, the safe direction. A write error propagates out of the run after the model has answered and been charged, because a swallowed write would leave the counter low and admit requests that should be refused. To keep the answer instead of the count, wrap the store and decide there.
Any object with get_many and add_many (BatchSpendStore) works, so a DynamoDB counter is a small class, not a fork. Neither method is called with an empty sequence. A custom store must:
- return a total for every key it was handed, keyed by
SpendEntry.key, including keys it skipped as replays. A missing total raisesUserErrornaming this contract, or a non-deterministic scope during durable replay, as the cause. - read a never-written key as zero rather than leaving it out.
- skip an entry whose
tokenwas already applied to that key, or recovery outside the durable journal can count one response twice. - apply the whole call or none of it, or it brings back the split write (day counted, month not) that the batch call exists to prevent.
SpendStore, the single-key get and add pair from 0.17.0, is deprecated. Such a store still works, one window per call, and SpendLimits emits one HarnessDeprecationWarning at construction naming both losses: windows are applied one at a time, and the token is dropped, so recovery that cannot consult the durable journal has no store-side deduplication. get and add on InMemorySpendStore and RedisSpendStore are deprecated too and warn when called. A subclass overriding get or add but not the batch pair is warned at construction: SpendLimits never calls those overrides, so whatever they added (an audit, a mirrored write) stops happening until moved onto get_many or add_many.
When price is unset or returns None, each complete response is priced on its own with genai-prices via ModelResponse.cost(); cache and tier pricing are per request, so pricing summed usage would be wrong. For a response with omitted usage, any known response.usage.cost subtotal is recorded instead.
price covers a model the registry does not know, such as a local deployment or a negotiated rate:
from decimal import Decimal
from pydantic_ai_harness import SpendLimits
SpendLimits(price=lambda response: Decimal('0.002') if response.model_name == 'internal-7b' else None)
price is called first, and a finite, non-negative amount is the complete response price, even when usage is incomplete. Any other amount (negative, NaN or infinite), or an exception from price, fails the run with UserError: a credit would move a budget away from its ceiling, and a NaN or infinity is a broken pricing function. The provider billed the response either way, so its tokens and request count are accrued and on_spend fires first. When one lifecycle committed several provider responses, an error accruing one response (pricing, reporting, or the store write) waits until the rest accrue.
None falls through to the registry. With incomplete usage, a known cost subtotal is recorded but the response stays unpriced, since its full cost is unknown. on_unpriced then applies: 'zero' (the default) increments Spent.unpriced_requests and continues; 'raise' fails the run with UnpricedModelError after recording the subtotal. With 'zero' and a usd budget, UnpricedModelWarning is emitted once per model with no complete price. If callers choose the model, prefer 'raise' or supply price.
Known token totals for incomplete usage are lower bounds, even when price supplies the cost. When a response omits usage and a token budget is configured, SpendLimits emits UsageLimitUnavailableWarning if the run can continue; check the provider’s usage reporting, or promote the warning to an error to stop when the token ceiling cannot be verified.
Under durable execution, price and each budget’s scope and ceiling callables must be deterministic for the same response and run context. A ceiling is read in orchestration, so a changed value can flip a replayed refusal. Pricing runs in orchestration, outside the journaled accrual, so a changed price can make on_spend disagree with the recorded counter or turn a successful recovery into a pricing error. A changed scope selects a different store key than the recorded accrual, which SpendLimits reports as a UserError naming the determinism requirement.
State outlives a run on purpose, so for_run is not overridden: a daily budget that reset every run would not be a daily budget. For per-run isolation use Budget(window='run'), whose key carries the run id.
defer_loading=True is refused: a deferred capability’s hooks do not run until the model loads it, so an exhausted budget would not stop a request and the requests made meanwhile would go uncounted.
SpendLimits accrues every response the provider billed, even one a hook nested inside it rejects or replaces, so its position among capabilities doesn’t change what it counts. A cached response, or one supplied with SkipModelRequest, never reached the provider and is not charged.
Core merges a continuation chain (Anthropic pause_turn, OpenAI background mode) into one response, which on_spend and SpendRecordedEvent report once with its combined usage. The counters instead grow at each segment boundary by what the merged response adds over what is already applied, so price also sees each intermediate response:
- A boundary
pricecannot price adds no USD and the merged response catches up, so pricing errors andon_unpricedapply to the merged response alone. - Tokens add up to the merged response, and USD to the highest amount any boundary was priced at, so a boundary priced above the merged response is not taken back as a credit.
- A later boundary that adds nothing, such as an idle background poll, is not written.
- A run resuming a turn from a history ending in its
'suspended'response is charged only for what was billed beyond it, since the earlier run paid for that response.
So a run window holds what each run billed, and conversation, day, month and total windows hold what the provider billed for the turn, once.
A response a FallbackModel rejected with a fallback_on response handler was billed too. Each one in ModelResponse.failed_attempts is accrued as its own request, ahead of the response carrying it. When every model fails, the attempts on the FallbackExceptionGroup are accrued the same way, even if an error hook recovers. A response the ModelFallback capability rejected is accrued as a failed attempt too, with its parts and provider_url. An attempt that raised before the provider answered reported no usage and is not charged. Spent.requests counts these attempts; core’s RunUsage.requests counts only responses the agent acted on.
price sees an attempt a FallbackModel recorded as a ModelResponse with the attempt’s model, provider, usage and timestamp, but no parts and no provider_url, so a price reading the output or the endpoint must allow for that. When price returns None, the cost core recorded on the attempt is used, unless it is negative or not finite, in which case the registry prices it.
Durable execution. SpendLimits supports Pydantic AI durability capabilities. Its clock read, counter read, and accrual are separate durable operations: Temporal reads the clock in an activity, not in workflow orchestration, and DBOS and Prefect record the same boundaries in their own durable units. On replay, each operation’s recorded result is returned without reading the clock or store again, so the response is accrued once and the window key comes from the recorded clock value. When a continuation chain fails partway, a retry replays the completed segments and their accruals, so only newly requested segments reach the store. A FallbackModel runs its whole chain in one durable unit, and its FallbackExceptionGroup does not cross the durable boundary, so only the rejected attempts it recorded on a response are charged. The ModelFallback capability makes each attempt its own durable model operation and records rejected responses on the workflow side, so they are charged as without durable execution.
Attach the durability capability to the same agent as SpendLimits. Without TemporalDurability, a SpendLimits agent run inside a Temporal workflow reads the clock in workflow orchestration, and the sandbox error is translated into advice to attach durability.
The journal covers replay while its records are available. The store token covers recovery that presents the same SpendEntry without consulting the recorded accrual, applying it once within dedup_retain. A deprecated SpendStore drops the token and cannot provide this second layer, and InMemorySpendStore provides it only within one process, so use a shared BatchSpendStore, such as RedisSpendStore or PostgresSpendStore, when recovery can land on another worker.
exhausted() is a workflow admission check that needs no RunContext:
from collections.abc import Awaitable, Callable
from pydantic_ai_harness import SpendLimits
async def start_if_funded(
limits: SpendLimits[None], tenant_id: str, start_workflow: Callable[[], Awaitable[object]]
) -> None:
if await limits.exhausted(scope=tenant_id):
raise RuntimeError('daily budget exhausted')
await start_workflow()
Prefer it to any(s.exhausted for s in await limits.status(...)): status omits budgets it cannot resolve, so with every budget scoped and no scope given, any() returns False having checked nothing, while exhausted raises UserError naming the budgets that need a scope or a run context. It reserves nothing; the durable operations then account for the workflow’s model responses.
For a ceiling on one run, or on a whole conversation carried with conversation=, Pydantic AI’s own UsageLimits works in-process with no store, and adds input-token limits (cumulative and per request) that SpendLimits lacks. Budget(window='run') instead counts only what each run adds, even when the run continues a conversation. Use Budget(tokens=..., window='run') when the same configuration also needs a longer window, a tenant scope, or a counter shared between processes.
A refusal emits a spend budget exhausted span with spend.budget and spend.window. Accrual emits nothing: a span per model request would double a trace without recording a decision. spend.scope is attached only when RunContext.trace_include_content is set, since a scope is usually a tenant or user id and traces have a wider audience than the application.
Agent.from_spec supports the part of the configuration a spec can express:
- SpendLimits:
budgets:
- {usd: '100', window: day}
- {usd: '2000', window: month, warn_at: 0.8}
on_unpriced: raise
store, price, on_spend, clock, a budget’s scope, and a callable usd or tokens take callables or live objects; a spec naming them is rejected, not ignored.
SpendLimits.from_spec names these fields in its signature, from which Pydantic AI generates the spec’s JSON schema, so an editor following the $schema line completes and validates them. BudgetSpec is the exported entry shape for building a spec in code.
Source: pydantic_ai_harness/spend_limits/.
Bases: AbstractCapability[AgentDepsT]
Accumulate spend per window and refuse a request once a window is exhausted.
from decimal import Decimal
from pydantic_ai import Agent
from pydantic_ai_harness.spend_limits import Budget, SpendLimits
agent = Agent(
'openai:gpt-5.4',
capabilities=[SpendLimits(budgets=[Budget(usd=Decimal('100'), window='day')])],
)
With no budgets the capability only reports through SpendRecordedEvent. Add a
Budget with no ceiling to keep a running total that never blocks.
Once a recorded response spends a window, SpendLimits refuses the next
request. It does not guarantee that spend stays under the ceiling: the request
that crosses the line completes, and concurrent runs can each pass the check
before any of them records anything. Reconcile against the provider’s billing
when exact totals matter.
State lives across runs on purpose, so for_run is left alone: a daily
budget that reset every run would not be a daily budget. Per-run isolation
comes from Budget(window='run'), whose key carries the run id.
Under a durability capability, clock reads, counter reads, and accruals are durable
operations. Their recorded results are replayed without re-entering the store. A
shared store is still required when recovery can move to another worker: the default
InMemorySpendStore loses its counters and deduplication markers with the process.
A deprecated SpendStore also loses token-based deduplication outside the journal
because its single-key add method has nowhere to receive SpendEntry.token.
Windows to accumulate against, and which of them can refuse a request.
Type: Sequence[Budget[AgentDepsT]] Default: ()
Where counters live. The default holds them for the lifetime of the process.
A store implementing only the deprecated SpendStore pair is driven one window per
call through an adapter, which warns once at construction about what that costs.
Type: SpendStore | BatchSpendStore Default: field(default_factory=InMemorySpendStore)
Prices a response before the registry is consulted.
Returning None falls through to genai-prices. This is the way to charge
a self-hosted model, or a negotiated rate the public registry does not know.
An amount must be finite and not negative. Anything else fails the run with
UserError, after the response’s tokens and request count have been recorded:
a credit would move a budget away from its ceiling, and a NaN or an infinity
is a broken pricing function rather than a price.
Under durable execution this callable must return the same result when replayed for the same response. It runs in orchestration after the durable model request, outside the journaled accrual.
Type: PriceFunc | None Default: None
Deprecated callback after each response. Subscribe to SpendRecordedEvent instead.
Durable replay can invoke this callback again after the response’s journaled accrual has run only once, so the callback must be idempotent.
Type: SpendCallback | None Default: None
What to do when a response cannot be priced.
When usage is incomplete, any known cost is still counted and the response
is marked unpriced because its full cost is unknown. Otherwise, 'zero'
counts an unpriced response as free and increments Spent.unpriced_requests,
so the gap shows up instead of disappearing. 'raise' fails the run with
UnpricedModelError. Token totals still accumulate either way; when usage is
incomplete, they are lower bounds.
Type: Literal[‘zero’, ‘raise’] Default: 'zero'
Offer the agent a get_spend tool.
Off by default: a tool costs schema tokens on every request, and most applications want the number on a screen rather than in the model’s context.
Type: bool Default: False
Supplies the time that day and month windows are derived from.
It does not reach a default-constructed store, which keeps its own utc_now for
expiry. Both remain absolute instants, so a custom clock buckets on one and expires on
the other; pass the same callable to the store when that matters.
Type: Callable[[], datetime] Default: utc_now
def __post_init__() -> None
Validate the configuration and adapt store to BatchSpendStore.
@classmethod
def get_serialization_name(cls) -> str | None
Serialization name for agent-spec support.
def get_ordering() -> CapabilityOrdering
Keep the established innermost placement around the model-request lifecycle.
CapabilityOrdering
def get_toolset() -> AgentToolset[AgentDepsT] | None
Offer get_spend when expose_tools is set.
AgentToolset[AgentDepsT] | None
@async
def before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Refuse the request if any budget with a ceiling is already spent.
@async
def wrap_model_request(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
handler: WrapModelRequestHandler,
) -> ModelResponse
Accrue every response the provider billed during the wrapped lifecycle.
Core records each billed response on the request context as the model returns it, so
this sees a response even when a hook nested inside this wrapper rejects or replaces it,
and never sees a response a hook made up without calling the model (a cache hit or
SkipModelRequest).
Billed attempts that did not produce the response, such as responses a FallbackModel
rejected, are accrued too: from ModelResponse.failed_attempts ahead of the response that
carries them, and from the attempts core records on the request context when every model
failed, whether or not a hook then recovered from the error. A response a hook rejected to
make another attempt, as the ModelFallback capability does, is accrued as a failed attempt too.
The segments of a continuation chain are observed too, so the merged response they
produce can be accrued boundary by boundary: see _accrue_response.
@async
def status(
ctx: RunContext[AgentDepsT] | None = None,
*,
scope: str | None = None,
) -> tuple[BudgetStatus, ...]
Where each budget stands.
Inside a run, pass ctx and every budget resolves. Without one, budgets on a
run or conversation window are omitted, since those periods have no meaning
outside a run, a budget whose ceiling is a callable is omitted, since only a run
resolves it, and a budget declaring a scope is omitted unless scope names the
partition to read.
Use exhausted when the answer
gates something.
tuple[BudgetStatus, …]
@async
def exhausted(
ctx: RunContext[AgentDepsT] | None = None,
*,
scope: str | None = None,
) -> bool
Whether any budget is exhausted, raising if some budget cannot be read.
An admission check: it reads the counters and reserves or records nothing, so work started after it is measured only if the agent also carries this capability.
status() omits the budgets it cannot resolve, so any(s.exhausted for s in ...)
returns False without checking anything when every budget is scoped. This raises
UserError instead, naming the budgets that need a scope or a ctx.
@classmethod
def from_spec(
cls,
*,
budgets: Sequence[BudgetSpec] = (),
on_unpriced: Literal['zero', 'raise'] = 'zero',
expose_tools: bool = False,
id: str | None = 'spend_limits',
description: str | None = None,
defer_loading: bool = False,
**unsupported: Any,
) -> SpendLimits[Any]
Build from an agent spec, covering the fields a spec can express.
Every parameter is named because that signature is what core reads to generate
the spec’s JSON schema: build_schema_types drops *args/**kwargs, so a
catch-all signature publishes the bare string 'SpendLimits' and an editor
marks every documented budgets: block as invalid even though it loads.
budgets arrive as mappings and become Budget instances, with usd
accepted as a string so YAML cannot round a price through a float. The
callables and the store have no spec representation and are rejected
rather than dropped. **unsupported keeps that rejection naming the field;
core drops it from the schema.
SpendLimits[Any]
Bases: Generic[AgentDepsT]
One spend window: what it limits, over what period, for whom.
A budget with neither usd nor tokens is a pure counter: it accumulates
and reports, and never stops a run. That is how per-tenant accounting with
no cap is expressed.
Generic in the agent’s dependency type so scope and the ceiling callables are
checked against it: the parameter comes from the Agent the capability is passed
to, so a callable reaching for a field the deps do not have is a type error rather
than an AttributeError on the first request.
from decimal import Decimal
from pydantic_ai_harness.spend_limits import Budget
Budget(usd=Decimal('100'), window='day')
Budget(usd=Decimal('10'), window='day', scope=lambda ctx: ctx.deps.tenant_id)
Budget(window='month', name='accounting') # counts, never blocks
Budget(usd=lambda ctx: ctx.deps.allowance_usd, window='month', scope=lambda ctx: ctx.deps.account_id)
A callable ceiling is resolved from the run alongside scope whenever the budget is read, so
each partition can carry its own allowance. None means no ceiling on that partition, and
zero or less means nothing is allowed. Under durable execution it must return the same value
when replayed with the same run context: it is read in orchestration, so a changed value can
flip a replayed refusal.
Ceiling in US dollars, or a callable resolving it from the run. None means this budget does not limit spend.
Type: Ceiling[Decimal, AgentDepsT] | None Default: None
Ceiling in total tokens, or a callable resolving it from the run. None means this budget does not limit tokens.
Type: Ceiling[int, AgentDepsT] | None Default: None
The period the ceiling applies to.
Type: Window Default: 'day'
Partitions the counter — per tenant, per user, per agent. None counts globally.
Under durable execution this callable must return the same value when replayed with the same run context, because its result is part of the store key.
Type: Callable[[RunContext[AgentDepsT]], str] | None Default: None
Fraction of the ceiling past which BudgetStatus.warning is set. Never blocks.
Type: float | None Default: None
Distinguishes budgets sharing a window and scope. Part of the store key.
Type: str Default: 'default'
How long a store may keep this window’s counter after its last write.
'window default' takes the horizon from window (see _TTLS). A time window
may expire freely once it has rolled over, but run and conversation buckets
never roll over, so their defaults are a compromise between never expiring and
growing the store without bound — and a conversation resumed past the horizon
starts again from zero. Set 'forever' where that matters and the keys are
cleaned up some other way, or a timedelta to pick the horizon outright.
Type: timedelta | Literal[‘window default’, ‘forever’] Default: 'window default'
Whether this budget can refuse a request, rather than only counting.
Type: bool
How long a store may keep this window’s counter after its last write.
Type: timedelta | None
def __post_init__() -> None
Reject configurations that would misbehave rather than fail.
A ceiling of zero or less makes a budget exhausted before anything is
spent, so the first request is refused with no way to tell that from a
real overspend — and usd: 0 in a spec is far more likely to mean “no
limit”, which is what None says. A warn_at on a budget with no ceiling has nothing to be a
fraction of, so it can never fire. Both read as configuration and behave
as breakage, which is why they are errors here rather than surprises
later.
A Budget ceiling: a fixed amount, or a callable resolving one from the run (None for no ceiling).
Default: TypeAliasType('Ceiling', _CeilingT | Callable[[RunContext[AgentDepsT]], _CeilingT | None], type_params=(_CeilingT, AgentDepsT))
What one model response cost, and where every budget stands after it.
The model that produced the response, or None if it reported none.
The response’s usage verbatim, including cache reads, writes, and audio.
Type: RequestUsage
What this response cost. Zero when it could not be priced.
Type: Decimal
Whether usd is a real price or a stand-in zero.
Type: bool
One entry per configured budget, in the order they were declared.
Type: tuple[BudgetStatus, …]
A budget and how much of it is left.
The budget this describes, as configured. usd_limit and token_limit hold its resolved ceilings.
Unparameterised because this is a reading: the dependency type only types
the callables of a Budget, and nothing calls one through a status.
Type: Budget[Any]
The store key it accumulates under. Useful for debugging a scope or window.
Type: str
What the budget’s current window has accumulated.
Type: Spent
The USD ceiling this reading is measured against, resolved for the run when Budget.usd is a callable.
Type: Decimal | None Default: None
The token ceiling this reading is measured against, resolved for the run when Budget.tokens is a callable.
Type: int | None Default: None
None when no USD ceiling applies to this reading (usd_limit is None).
Type: Decimal | None
None when no token ceiling applies to this reading (token_limit is None).
Whether spend has crossed Budget.warn_at. Always False without one.
Type: bool
Whether a further request would be refused.
Type: bool
Everything one window has accumulated so far.
Priced cost. Requests with no resolvable price contribute nothing here.
Type: Decimal Default: Decimal(0)
Total tokens, counted whether or not the request could be priced.
Type: int Default: 0
Model requests recorded against this window.
Every billed request counts, including a response a FallbackModel rejected, so this can be
higher than the run’s RunUsage.requests, which counts the responses the agent acted on.
Type: int Default: 0
How many of requests had no resolvable price, so usd understates them.
Type: int Default: 0
Bases: Protocol
Reads and accumulates the counters behind every window of one response.
add_many returns the state after the increment so an atomic backend can
answer without a second round trip, keyed by SpendEntry.key rather than
positionally so entries sharing a key collapse the way the caller expects.
Both methods take a sequence rather than a single key so a backend that can read or apply the whole set as one unit does, and one that cannot still sees the whole set and can say so.
@async
def get_many(keys: Sequence[str]) -> Mapping[str, Spent]
What each key has accumulated. A key that was never written reads as zero.
@async
def add_many(entries: Sequence[SpendEntry]) -> Mapping[str, Spent]
Apply every entry and return each key’s new total.
One window’s share of one response.
Everything except key defaults to nothing, so a reconciler correcting drift
against an external source can post a usd delta on its own without inflating
the request count.
The window’s store key.
Type: str
Priced cost to add. May be negative, which is how a reconciler corrects drift.
Type: Decimal Default: Decimal(0)
Total tokens to add.
Type: int Default: 0
Model requests to add. Explicit rather than an implied += 1 so a correction
can move the money without moving the count.
Type: int Default: 0
How many of requests had no resolvable price.
Type: int Default: 0
How long the key may be kept after this write. None means indefinitely.
Type: timedelta | None Default: None
Identifies the response this entry came from, so it is applied at most once.
The durable accrual operation handles ordinary replay through its journal. Recovery
without that record can still present the same response to the store. A store that
recognises a token it has already applied to key returns the current total instead
of adding again.
None means “apply unconditionally”, which is what a reconciler posting a delta
wants: two corrections of the same size are two corrections.
Type: str | None Default: None
Bases: Protocol
Reads and accumulates the counter behind one budget window at a time.
Deprecated. Implement
BatchSpendStore instead: it takes
every window of a response in one call, which is what lets a backend apply them
together, and it carries the replay token that keeps a re-executed accrual from
counting twice. SpendLimits still accepts a store of this shape and drives it
through an adapter, one window per call, warning once about what that costs.
The two protocols are separate names rather than two versions of one, because
runtime_checkable tests method presence and not signatures: reusing add and
get would leave nothing able to tell a store that batches from one that cannot.
@async
def get(key: str) -> Spent
What key has accumulated. A key that was never written reads as zero.
Spent
@async
def add(
key: str,
*,
usd: Decimal,
tokens: int,
requests: int,
unpriced: int,
ttl: timedelta | None,
) -> Spent
Add to key and return the result. ttl is how long the key may be kept.
Spent
Counters for the lifetime of one process.
Catches a runaway loop inside the worker it runs in. It does not enforce a
budget across processes and cannot survive durable recovery on a replacement
worker: each process has its own counters and deduplication markers. A shared store such as
RedisSpendStore is for.
Supplies the time expiry is measured against.
Type: Callable[[], datetime] Default: utc_now
Writes between expiry sweeps.
Expiry cannot wait for the next read of a key: a day window produces a new key each day, so yesterday’s is never asked for again. The scan is linear in resident keys, so it is amortised over this many writes rather than run on each one, which bounds dead entries to roughly that many. Lower it where scopes are high-cardinality and memory matters more than the scan.
Type: int Default: 256
How long an applied SpendEntry.token is remembered, or None to apply every entry.
This is the window a replay is recognised in, not the counter’s lifetime: a response replayed later than this is counted again. A remembered token costs one small entry per response per window until it is swept.
Type: timedelta | None Default: DEFAULT_DEDUP_RETAIN
def __post_init__() -> None
Report a subclass whose single-key overrides the batch pair has left unreachable.
def __len__() -> int
How many windows are still live.
Rolled-over entries are excluded whether or not the amortised sweep has reached them
yet, so this counts what is being tracked rather than what happens to be resident.
That is one entry per budget, scope and period — and for a run or conversation
budget the period is an id, so the count grows with traffic until those entries reach
their horizon. Worth watching there and wherever scopes are high-cardinality.
Defining __len__ makes an empty store falsy, so write if store is not None.
@async
def get(key: str) -> Spent
What key has accumulated. Deprecated in favour of get_many; call it with a sequence of keys.
Spent
@async
def add(
key: str,
*,
usd: Decimal,
tokens: int,
requests: int,
unpriced: int,
ttl: timedelta | None,
) -> Spent
Add to key and return the result. Deprecated in favour of add_many; call it with a sequence of entries.
Spent
@async
def get_many(keys: Sequence[str]) -> Mapping[str, Spent]
What each key has accumulated, treating an expired key as absent.
Under the lock, because _live deletes the key it finds expired: unlocked, that
del races the _sweep iteration inside add_many (RuntimeError: dictionary changed size during iteration) and a second concurrent reader (KeyError).
Reachable whenever the guard is shared across threads — run_sync from a pool,
a sync endpoint — and any key is read past its horizon.
@async
def add_many(entries: Sequence[SpendEntry]) -> Mapping[str, Spent]
Apply every entry and return each key’s new total.
The mutation spans no await, so concurrent runs on one event loop cannot
interleave halfway through it and no reader sees some of a response applied and
not the rest. The lock covers the case that is not free: run_sync called from a
thread pool, or a free-threaded interpreter, where a read-modify-write loses
updates in the direction that under-counts spend.
Every entry is worked out before any of them is stored, so a response that fails part-way through — an amount whose arithmetic raises, say — leaves none of its windows applied rather than the ones before the failure. Applying the whole set together is what this method exists for.
The clock is read once, before anything is applied, and a token is remembered only once the counter it stands for has moved. A token remembered ahead of that write would be consumed by a call that then failed, and the retry that could have recorded the response would be skipped as a replay of it.
Spend counters in Redis, so every worker enforces one budget.
One hash per window, holding the four counters as integers.
from redis.asyncio import Redis
from pydantic_ai_harness.spend_limits import RedisSpendStore
store = RedisSpendStore(Redis.from_url('redis://localhost'))
A read and the increment that follows it are separate round trips, so concurrent runs can each observe a budget as unexhausted and push past it together. That is the same overshoot the in-process store has, widened by the number of workers; see the README on what the gate does and does not guarantee.
Any client exposing hgetall and eval.
Type: RedisClient
Namespace for the keys, so a shared Redis stays tidy.
Every key this store writes is {prefix}:... with the braces literal, which is a
Redis Cluster hash tag: the slot is computed from the prefix alone, so all of a
store’s keys land in one slot and a script may take several of them at once.
Applying one response to a day and a month window in one script is what that buys,
and the cost is that a cluster cannot spread this store’s keys across its nodes.
A prefix carrying a brace of its own is refused at construction, since it would move the tag and put two windows of one budget in different slots.
Type: str Default: 'pydantic-ai-harness:spend'
How long an applied SpendEntry.token is remembered, or None to apply every entry.
This is the window a replay is recognised in, not the counter’s lifetime: a response replayed later than this is counted again, because the marker it would have matched has expired. The counter usually lives far longer, since every write extends it.
Each remembered token is one small key per response per window. Raise it where a durable engine may recover long after the fact; lower it where the write rate makes that memory matter more.
Type: timedelta | None Default: DEFAULT_DEDUP_RETAIN
def __post_init__() -> None
Reject a prefix that would break the hash tag it is wrapped in, and report dead overrides.
A brace inside the prefix moves or truncates the tag, so two windows of one
budget would hash to different slots and a cluster would refuse the script that
applies them together. Checked here for the same reason Budget.name is checked
against its separator: the failure otherwise arrives as a CROSSSLOT error on a
model request.
@async
def get(key: str) -> Spent
What key has accumulated. Deprecated in favour of get_many; call it with a sequence of keys.
Spent
@async
def add(
key: str,
*,
usd: Decimal,
tokens: int,
requests: int,
unpriced: int,
ttl: timedelta | None,
) -> Spent
Add to key and return the result. Deprecated in favour of add_many; call it with a sequence of entries.
One window per call, so a response counting against a day and a month budget is
two calls and a failure between them leaves the day counted and the month not.
add_many is one script over every window, which is what closes that.
Spent
@async
def get_many(keys: Sequence[str]) -> Mapping[str, Spent]
What each key has accumulated. An absent hash reads as zero.
Two round trips per key while the pre-hash-tag fallback is in place: the key’s own
hash, and the one an earlier release would have written; see _before_hash_tags.
@async
def add_many(entries: Sequence[SpendEntry]) -> Mapping[str, Spent]
Apply every entry as one script and return each key’s new total.
One unit of work: every window of the response lands or none does, and the script
returns each new total, so the totals need no second read. What does cost a read
is the pre-hash-tag fallback, one per key, until it goes away; see _before_hash_tags.
A failure before the server runs the script — the client cannot connect, the
request never lands — writes nothing. A failure after it does not say which:
the connection can drop once EVAL has already committed, so an error here
means the outcome is unknown rather than that nothing happened. Retrying
therefore risks counting the response twice, which is why
SpendLimits.wrap_model_request does not retry and lets the error end the run
instead. Over-counting a billed response refuses requests early; under-counting
lets requests through past the ceiling.
A SpendEntry.token makes the retry that is safe: a durable engine
re-executing an accrual it already committed finds the marker for it already
written, so the entry is skipped and the current total is returned.
Spend counters in PostgreSQL, so every worker enforces one budget.
One row per window in {table}_counters, holding the four counters as integers, and one
row per applied SpendEntry.token and window in {table}_dedup, both keyed by a SHA-256
digest so a key or token of any length fits the index. Both tables are created on first
use. Takes a caller-owned asyncpg-compatible pool; the store never closes it.
Horizons are measured on the server’s clock, the way Redis measures expiry on its own, so every worker agrees on when a window rolls over and a worker whose clock runs ahead cannot restart a counter another worker is still adding to.
A read and the increment that follows it are separate round trips, so concurrent runs
can each observe a budget as unexhausted and push past it together, as with
RedisSpendStore; see “What the gate guarantees”
in the Spend docs.
def __init__(
pool: PostgresPool,
*,
table: str = 'spend',
dedup_retain: timedelta | None = DEFAULT_DEDUP_RETAIN,
sweep_every: int = 256,
) -> None
Validate the configuration; nothing touches the database until the first call.
An asyncpg-compatible pool. The application owns its lifecycle.
table : str Default: 'spend'
Prefix for the store’s tables, {table}_counters and {table}_dedup.
Lowercase letters, digits and underscores, at most 47 characters, so every
derived name stays inside Postgres’s 63-byte identifier limit.
dedup_retain : timedelta | None Default: DEFAULT_DEDUP_RETAIN
How long an applied SpendEntry.token is remembered, or None to
apply every entry. This is the window a replay is recognised in, not the
counter’s lifetime: a response replayed later than this is counted again,
because the marker it would have matched has expired. Each remembered token is
one small row per response per window until it is swept. Must be positive: a
zero horizon writes a marker that has already expired, so a second entry of the
same response in one call would take it over and count again.
sweep_every : int Default: 256
Entries written by this instance between deletions of expired rows. A day window produces a new key each day, so yesterday’s row is never written again and has to be deleted by a sweep rather than on its next write.
@async
def get_many(keys: Sequence[str]) -> Mapping[str, Spent]
What each key has accumulated. An absent or expired row reads as zero.
@async
def add_many(entries: Sequence[SpendEntry]) -> Mapping[str, Spent]
Apply every entry in one transaction and return each key’s new total.
Every window of the response commits together or none does, and a failure part-way,
such as a counter passing the signed 64-bit range, rolls back the windows before it too.
A connection that drops after the commit was sent leaves the outcome unknown rather than
untried, the same as RedisSpendStore, which is why SpendLimits does not retry.
An entry carrying a SpendEntry.token claims a marker row first, and is skipped when a
live marker for that key and token already exists. Claiming it in the same transaction as
the increment is what makes the order safe: a failed increment rolls the claim back with
it, so the retry that could have recorded the response is not skipped as a replay. A
concurrent claim of the same marker waits on the first transaction and, once that commits,
finds the marker and skips. That wait is READ COMMITTED behavior, so the transaction
sets that level rather than inheriting a stricter default, under which the second writer
would fail with a serialization error instead.
Every marker is claimed before any counter is written, markers in key and token order and counters in key order, so two transactions lock rows in one global order and wait on each other rather than deadlocking. Claiming a marker after a counter instead would let a transaction hold the counter while it waits on another’s marker for the same key, while that one waits on the counter. Entries sharing a key are applied in their given order.
Bases: UsageLimitExceeded
Raised when a Budget is exhausted.
Subclasses UsageLimitExceeded
so an application that already stops on a usage limit stops on a spend limit
too, while code that needs to tell “the daily budget is gone” from “this run
used too many tokens” can catch this type specifically.
Bases: UserError
Raised when on_unpriced='raise' and a complete price is unavailable for a response.
Either the model is absent from the genai-prices registry (a local or
custom deployment), the response carries no model name, or its usage is
incomplete. Incomplete usage can still contribute a known cost subtotal.
Supply SpendLimits.price to price it yourself, or use on_unpriced='zero'
to record any known subtotal and surface the gap as Spent.unpriced_requests.
Bases: UserWarning
Warned once per model when an incomplete or unpriced response leaves a USD ceiling understated.
Only warned under on_unpriced='zero', and only while a Budget carries a
usd ceiling. A response with incomplete usage may add a known cost subtotal,
but the omitted usage leaves its full cost unknown. A response with no registry
price adds nothing in dollars. Known token totals for incomplete usage are lower
bounds.
Deduplicated per model name for the life of the capability instance, so a model with an incomplete or unavailable price reports once rather than once per request.