Learning resourcesReviewed · Pydantic

Pydantic AI Harness Spend guide

Pydantic AI Harness's Spend guide teaches Python agent developers to track and limit model spending, but requests can push spending past a budget. It explains SpendLimits, USD and token budgets, tenant accounting, shared Redis or PostgreSQL counters, pricing gaps and durable recovery.

Researched 15 Nov 2026

In short.

This Pydantic AI Harness guide helps Python agent developers manage model budgets, but it cannot guarantee spending stays below a ceiling. SpendLimits checks recorded spending before requests and accounts for responses afterward, with configurable periods, tenant partitions and shared stores. Its practical value depends on complete provider usage, suitable pricing and reliable counter storage. Runtime correctness, performance and billing accuracy have not been assessed through execution.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage is limited to the complete selected page at https://pydantic.dev/docs/ai/harness/spend/index.md, including its examples, API reference, version warning and deprecation and migration notices. Linked documentation, implementation files, pricing data and license materials are excluded. No code, provider requests, stores or recovery paths were executed; runtime behavior, performance, billing accuracy and installed-version compatibility remain unassessed.

The overview

identity

The resource is the Spend documentation for Pydantic AI Harness at [https://pydantic.dev/docs/ai/harness/spend/index.md]. It combines a feature guide, Python configuration examples, operational warnings and an API reference for SpendLimits, Budget and the bundled spend stores.

assessment

The guide is useful when spending must be tracked across multiple agent runs, tenants or workers. Its strongest feature is its explanation of failure boundaries: budget checks reserve no money, incomplete usage can understate totals, and accounting can fail after a provider has charged for a response. Applications requiring an absolute spending ceiling need additional controls; SpendLimits alone does not provide that guarantee.

users

The primary audience is Python developers building Pydantic AI agents. Beginners get small examples for daily budgets and spending displays, although the guide assumes familiarity with Agent configuration, imports and asynchronous functions. Experienced developers get details relevant to tenant allowances, queue workers, custom prices, database-backed accounting and durable workflows.

capabilities

Budget supports USD ceilings, total-token ceilings or accounting without a ceiling. Multiple budgets can apply simultaneously across run, conversation, day, month and total windows. A scope callable partitions totals by tenant, user or another application-defined key. Warning thresholds report a condition but never block requests.

SpendRecordedEvent reports recorded responses, status() supplies budget readings, and an optional get_spend tool exposes readings to the agent. The tool is disabled by default because its schema adds tokens to requests. Agent specifications support declarative budget settings, but reject live objects and callables such as stores, pricing functions and scopes.

Using it

requirements

The examples use Pydantic AI and pydantic_ai_harness in a Python application. Exact package versions, the minimum Python version and provider authentication instructions are not established by this page.

The default in-memory store needs no shared database but lasts only for its process. Cross-worker accounting requires a shared store. RedisSpendStore accepts a compatible asynchronous Redis client. PostgresSpendStore accepts an asyncpg-compatible pool whose startup and shutdown the application manages; the page explicitly documents installing asyncpg. PostgreSQL table creation requires schema CREATE permission initially, with table-level SELECT, INSERT, UPDATE and DELETE sufficient afterward.

mechanism

Before each model request, SpendLimits reads the applicable counters and refuses the request if a budget is exhausted. After a billed response, it prices the response and adds its usage to the relevant counters. Day and month periods use different keys as time advances, avoiding a scheduled counter reset.

PostgreSQL applies a response's counter updates and deduplication markers in one transaction. Redis uses one Lua script, although the documented integer-overflow exception can leave earlier windows applied. Both stores represent money as integer billionths of a dollar.

Durable execution journals clock reads, counter reads and accrual. Store-side replay protection additionally depends on retained response tokens; recovery outside the journal requires the same run_id. Markers normally last an hour, or a shorter window horizon, so this protection is time-bounded. Event listeners must remain idempotent because replay can deliver reporting events again.

setup

The basic pattern imports Decimal, Agent, SpendLimits and Budget, then passes SpendLimits(budgets=[Budget(usd=Decimal('100'), window='day')]) through the agent's capabilities argument. That configures an example daily budget; it does not purchase provider access or establish the application's actual cost.

Choose a shared store when several processes must count together, and pass the same store to separate SpendLimits instances when they should share totals. Configure explicit scopes for tenant budgets. Set conversation retention deliberately: the default conversation counter horizon is 30 days after its last write, after which a resumed conversation starts from zero. retain='forever' preserves the ceiling but requires another cleanup strategy.

example

The guide illustrates combining a $5 per-run ceiling, a $100 daily ceiling, a $2,000 monthly ceiling with an 80% warning threshold, and a $10 daily tenant ceiling. Each response contributes to every applicable window, while the tenant scope keeps different tenants' totals separate.

If a response pushes the daily total past $100, that response completes and the next request raises SpendLimitExceeded. Several concurrent requests can pass the check before their costs are recorded. These amounts are illustrative configuration values, not fees, measured savings or execution results.

Assessment & evidence

limitations

The crossing request and concurrent requests can exceed a ceiling. Interrupted streams can omit output-token usage, and incomplete usage makes token totals lower bounds. Unknown pricing can also understate USD totals. A warning threshold is a reporting signal; approval before further spending requires application logic.

In-memory counters and replay markers disappear with worker replacement. Store read errors refuse requests, while write errors propagate after the model may already have answered and incurred charges. A connection loss after a database operation can leave its commit outcome unknown; SpendLimits does not automatically retry that write.

Outside a run, status() omits budgets it cannot resolve. Admission decisions should use exhausted(), which raises when required scope or context is missing, but still reserves nothing. Replacing budgets after refusal affects every run sharing that capability and bypasses constructor combination checks. Durable execution also requires deterministic scope and pricing functions and the durability capability attached to the same agent.

reasoning

SpendLimits fits applications whose accounting boundaries extend beyond one agent run. Tenant partitions and shared counters address deployment-wide allowances, while the response-after-request design explains both its usefulness and its overshoot risk. Accurate enforcement depends on the accounting inputs: shared storage cannot compensate for missing usage, unknown prices or counters that expire before a conversation ends.

alternatives

For limits covering only one run, the page recommends Pydantic AI's UsageLimits. It needs no spend store and adds cumulative and per-request input-token limits that SpendLimits does not offer. SpendLimits becomes relevant when longer periods, tenant scopes or shared counters are also required.

Provider usage APIs serve billing reconciliation but report usage after requests have happened. Redis and PostgreSQL are documented shared-storage choices, with PostgreSQL particularly relevant to applications already operating that database. Other products and comparative performance are not assessed.

evidence

The evidence covers the complete documentation page at [https://pydantic.dev/docs/ai/harness/spend/index.md], including its inline examples and API reference. Its supplied source revision is sha256:351f0d828c35d9b2757718dea98467273254e0ba5f38ca074f17628f9e094148.

The page links to implementation code at [https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_ai_harness/pydantic_ai_harness/spend/]. That implementation, other linked pages and the pricing registry are outside the available evidence. The described guarantees are documentation claims; no code was executed and no independent test results are supplied.

Access & freshness

costs

Software pricing, provider rates, database hosting charges and total operating cost are unknown from this page. Shared stores introduce storage and request overhead, including a deduplication marker per response per window; no measured overhead or throughput figures are supplied.

Automatic pricing uses ModelResponse.cost() and genai-prices on individual responses, preserving request-specific cache and tier pricing. A custom price function can handle negotiated rates or private deployments. By default, on_unpriced='zero' continues while recording known subtotals and an unpriced-request count. on_unpriced='raise' fails after recording available usage; it cannot undo the provider charge. Exact totals require reconciliation with provider billing.

rights

The page contains no license text or explicit redistribution grant. Software licensing, commercial-use conditions and permission to redistribute the documentation are therefore unknown from this evidence. The public documentation and linked source repository do not by themselves establish those permissions.

freshness

The supplied capture timestamp is 2026-11-15T11:52:08.303Z. The page gives no publication date or exact package release for the captured behavior. It warns that 0.x APIs may change between minor releases.

Migration-sensitive notices include replacing the deprecated on_spend callback with SpendRecordedEvent and single-key store interfaces with get_many/add_many. A Redis compatibility notice names 0.28.0 as the removal point for legacy-key reads. Installed-version compatibility and the latest release are unknown from this evidence.

actions

Before adoption, confirm the installed API version, provider usage completeness and applicable pricing. Choose shared storage for multiple workers, set retention for long conversations and recovery, and use explicit partition names and scopes. Consider on_unpriced='raise' when incomplete pricing must stop a run.

Validate expected behavior for concurrency overshoot, interrupted streams, store failures and recovery before relying on the limits operationally. Make spend-event consumers idempotent. After a mid-run refusal, resume from captured message history to avoid repeating completed tool calls and their side effects. Assess licensing separately before reuse or redistribution.

Evidence for this report

selected-page.txtselected · checked 2026-11-15