@agentium/core. Agentium keeps the provider’s usage evidence, the applicable price rule, and the result of each assessment.
A successful model answer can have unknown cost. A failed answer can still have known usage and cost. Check execution, usage, and pricing status separately.
Track an Agent
Setcost: true once. Each run returns its usage and cost snapshot. You do not need a wrapper function or a manual flush to read the result.
Install @agentium/core and openai, and set OPENAI_API_KEY. This example makes a paid provider request.
cost: true uses an in-memory tracker and the bundled catalog. Pass a configuration object to select storage, prices, or a budget. Pass an existing costTracker when several components must share one tracker; do not set both options.
result.costs.total is a decimal string when pricing is complete, or null when usage, context, or rates are missing. knownSubtotal contains the amount that could be priced. A snapshot with status: "unavailable" means the accounting store could not be read; both amounts are null. The model answer is preserved.
A run snapshot includes its child work and has an asOf time when available. Later background work can add usage. Use tracker history queries when you need session totals, pages of evidence, repricing, or reconciliation.
Use budget controls to limit new work. Use the migration guide when replacing earlier synchronous summaries.
Stream the answer
The terminalfinish chunk carries the same cost snapshot. Read it after the text chunks:
Follow one call
An operation is the requested activity. An attempt is an observable provider request within that operation. A retry gets another attempt ID. A router or parent summary does not add another charge for its child’s work.Use four token categories
Canonical input is the sum of ordinary input, cache read, and cache write. Canonical output includes reasoning. The provider-reported total is retained separately so discrepancies remain visible.
For example, OpenAI input 19 and output 16, including 9 reasoning tokens, produces 35 total tokens. The 9 reasoning tokens do not create another output charge.
Anthropic’s ordinary input excludes its separate cache read and write counters. Its normalizer adds those counters to form canonical input. Applying OpenAI’s subtraction rule directly to Anthropic’s ordinary input would be incorrect.
Read and write example
These are synthetic rates for a reproducible example, not a provider tariff. Input is 15,000 tokens. It contains 12,000 read tokens and 2,000 written tokens. Output is 500 tokens, including 100 reasoning tokens.
If the write rate is missing,
knownSubtotal is "0.047", total is null, and the write charge explains the missing rate. An explicit zero rate is different from a missing rate.
Build a custom tariff and record usage
Complete synthetic example: this makes no provider request. Install@agentium/core, typescript, and tsx, save the code as cost-example.ts, then run npx tsx cost-example.ts.
provider.generate() outside an accounting context is not tracked. Use an Agent, or wrap direct work with withAccountingContext() and the matching metered helper.
In a real adapter, derive usage from the provider’s documented counters. List required-but-unknown meters instead of omitting them. Keep retry IDs distinct. Repeated delivery of the same observation must reuse its ID and content; different content with the same ID is a conflict.
The calculator creates charges from measurements and required coverage. Each charge keeps its quantity, billed quantity, unit, currency, rule snapshot, catalog version, and evidence paths. Missing information produces a reason such as missing_usage, missing_rate, or missing_context.
Select the applicable price
Rules match the billing provider, exact model or resource, API, time, and required billing context. A compatible API wire format does not establish the biller’s prices. Azure deployment names and gateway aliases need explicit mappings.
The bundled catalog is a dated estimate. It does not fetch prices on the request path. Supply a pinned catalog or contract rules when the built-in coverage does not match your use.
Provider catalog in 4.11
Agentium 4.11.0 adds exact Responses tariffs for GPT-6.1 Sol Ultrafast, Gemini Argon GenerateContent tariffs, and corrected Decisions cache accounting. Decisions divides inclusive input into ordinary input, cache reads, and cache writes. For 1,000 input tokens containing 800 cache-read and 100 cache-write tokens, the remaining 100 are ordinary input. At the verified standard rates, the total is$0.0000305; output is not charged. Missing cache details remain unknown. Historical assessments retain their original rule snapshots and are not rewritten.
New GA rules start at their recorded verification instant. Argon’s announced date-only price transition has a conservative unpriced interval where the effective timezone is unknown. The catalog’s existing expiry still applies before any future rule can be used. Unsupported regions, tiers, models, and stale catalogs continue to produce incomplete estimates rather than guessed charges.
Set account billing facts once
Some providers do not return the account plan or billing region. Set these facts in the Agent configuration when your application knows them:pricePlan: "free" does not itself establish a zero price; a matching free-tier rule is still required.
Track other billing units
Measurements also support requests, seconds, characters, images, and storage quantities. Use the provider’s billing unit and evidence. Elapsed wall time, returned image count, or tool execution alone does not prove a charge. Session or account minimums require grouped billing. Add distinct contributions first, then round the group once. Two 20-second operations in one session at USD 0.01 per started minute produce one USD 0.01 group charge. Per-request rounding would instead produce USD 0.02. Allocated shares are reporting views and must not be added to the original group charge. Provider-reported amounts, list-price estimates, and invoice reconciliation describe different views of the same spend. Keep their inclusion scopes and currencies separate.Record a reported amount
UserecordReportedCost() when a provider returns a money amount or when you import an invoice. Supply a stable assessment ID, the target attempt or billing group, the currency, the included meters, and the source evidence.
"0.072", the provider amount USD "0.05", and the invoice amount USD "0.04". Query each view separately. Their sum is not the cost of the call. Replaying the same ID and content does not add another charge.
An imported amount applies only to its stated scope. Do not describe an account invoice as one attempt’s price. Include credits only in the invoice view. A reported amount does not fill missing token counters.
Allocate a shared charge
Allocate a complete group assessment when several runs share one bill. Use stable operation IDs and a named allocation policy. The following function splits a known group charge equally between two operations:"0.01" group, each run receives USD "0.005". The tenant total stays USD "0.01". Use queryAllocations() to inspect the shares. Allocation records refer to an exact assessment; if later usage changes that assessment, create shares for its replacement.
Call finalizeGroup(targetId, { tenantId, confirmedFinal: true }) only after you have confirmed that the billing interval is final. Finalization writes a new assessment. It does not delete the earlier evidence. Recreate allocations for the new assessment if needed.
Store evidence and read history
Use an accounting store for observations, usage revisions, immutable assessments, selected views, and reservations. The default in-memory store does not survive restart. Session memory storage does not automatically persist cost accounting. Queries are tenant-scoped and use cursor pagination for records. Do not treat a single page as all history. Keep ISO timestamps and decimal strings when exporting data. Retain only bounded usage metadata and safe billing context; prompts, full responses, and credentials do not belong in the cost store. A failed accounting write after a successful provider request must retry the write with the same IDs. It must never repeat the provider request. Keep the accounting failure visible and useflush() to settle pending writes.
Use events without duplicate spend
Canonical usage and assessment events include stable record IDs and revisions. A revised assessment replaces the selected cost; it does not append another copy of the full charge. The legacycost.tracked event is a replacement run-total projection for complete known cost. Do not sum successive replacement totals. Do not combine canonical attempt charges, allocated group shares, and parent totals as if they were separate purchases.
See observability for traces and metrics. Telemetry delivery is not the authoritative accounting store.
Check coverage
Provider formats, tariffs, and hosted tools change. A normalizer or price rule is supported only for its declared API and tested schema. Missing usage, unknown modes, ambiguous modality splits, custom gateway terms, and unsupported paid-tool meters remain partial or unpriced. InspectMODEL_USAGE_CAPABILITIES for model adapters and BUILTIN_ACCOUNTING_CAPABILITIES for embeddings, reranking, images, voice, and tools. These declarations describe usage evidence. Price coverage is separate and still requires a matching catalog rule.
Use the generated cost reference for exact exported types, budget controls for admission policy, and v4.5 migration for compatibility limits.
Use asynchronous canonical budget checks
After canonical accounting has been used, the legacy string-argumentcheckBudget(runId), checkInProgressBudget, isBudgetExceeded and estimateRemaining helpers throw even when observed usage is complete. Use await tracker.checkBudget(accountingScope, bound) and asynchronous queries for canonical accounting decisions. See 4.9 compatibility.