عامل‌ها، حاکمیت، حقوق و صورتحساب · فصل ۱ — Catalog، Authority، Memory، Failure و Cost · 285

Agent Cost Metering

Design a cost-metering contract that preserves per-run and per-request usage evidence, binds usage to a dated price snapshot and model/provider/tier, separates measured usage from calculated cost, allocates shared workflow cost explicitly, records retry/tool/external charges, enforces warning/stop/escalation budgets without inventing missing usage, and produces an auditable unit-cost decision for the agent workflow. می‌تواند برای «Agent Cost Metering» authority، memory/failure boundary و escalation/evidence را در یک agent محدود تعریف کند.

Agent Cost Metering — fa-IR

Lesson summary

Design a cost-metering contract that preserves per-run and per-request usage evidence, binds usage to a dated price snapshot and model/provider/tier, separates measured usage from calculated cost, allocates shared workflow cost explicitly, records retry/tool/external charges, enforces warning/stop/escalation budgets without inventing missing usage, and produces an auditable unit-cost decision for the agent workflow.

می‌تواند برای «Agent Cost Metering» authority، memory/failure boundary و escalation/evidence را در یک agent محدود تعریف کند.

This lesson produces

می‌تواند برای «Agent Cost Metering» authority، memory/failure boundary و escalation/evidence را در یک agent محدود تعریف کند.

Who it is for

Foundation

Use a field map, one worked scenario and explicit state vocabulary before independent construction.

Repair

Identify the failed evidence dimension, use the smallest mutated fixture and rerun only the affected gate.

Experienced

Compress definitions; require trade-off defense, counterexample analysis and changed-context transfer.

Prerequisites

An agent run can be technically successful and still be economically wrong. A single total_tokens number does not tell you which requests used which model or tier, whether cached input had a different rate, whether tools or retries added charges, which price snapshot was effective, or how shared workflow cost was allocated.

The artifact for this lesson is Agent Usage, Cost & Budget Control Ledger v1. Its purpose is not to manufacture an invoice. It creates an auditable cost state from visible synthetic evidence and refuses to call a cost exact when decisive usage or price evidence is missing.

First rule: usage evidence and monetary cost are different layers.

Route orientation and owned boundary

AGN-007 owns metering, dated price binding, allocation, unit-cost and budget-state evidence. AGN-006 owns failure/retry reconciliation; AGN-008 owns contract-suite scope and service commitments. This lesson records retry cost units, but it does not decide whether a failed action should be retried.

Foundation learners use the field map and baseline fixture. Experienced learners may skip definitions, but they must pass the same exactness, provenance, allocation and budget gates.

Mental model: five layers, never one total

Keep five layers separate:

  1. Measured usage — request count, input/cached/output/reasoning detail, tools and external usage.
  2. Price provenance — model, provider, tier, currency, price snapshot and effective date.
  3. Cost calculation — deterministic calculation from measured units and dated unit prices.
  4. Allocation — an explicit rule for shared workflow cost; never a silent split.
  5. Budget control — prior consumption, warning/stop thresholds, escalation and audit.

The final label must be no stronger than the weakest decisive layer. Missing adapter detail can produce an estimate or review state, not fabricated exactness.

Foundations: current FACT versus local DESIGN

The current OpenAI Agents SDK documents run-level request/input/output/total-token tracking and per-request usage entries. It also documents cached-token and reasoning-token detail, and notes that preserving provider-specific usage can matter when an application must distinguish an omitted field from a reported zero.

Current OpenAI model documentation publishes prices by model and token category; some tool-specific capabilities use other billing units. Those pages are volatile vendor facts. The synthetic prices in this lesson are intentionally not real vendor prices.

MAKNOW's rules for allocation, warning/stop thresholds and escalation are local design. External documentation cannot approve a business allocation policy.

Deep explanation of the ledger

The critical contract has 23 dimensions: run_id, request_id, model_id, provider_id, processing_tier, usage_source, input_tokens, output_tokens, total_tokens, price_snapshot_id, price_effective_at, measured_cost, allocation_rule_ref, allocated_cost, unit_of_work, unit_cost, budget_id, budget_limit, budget_consumed, cost_state, missing_usage_state, price_staleness_state, and audit_ref.

The lab adds visible supporting fields so the calculation can be reproduced. Important gates are:

  • total_tokens = input_tokens + output_tokens; cached input is a subset of input and reasoning detail is a subset of output.
  • The price snapshot must match the measured model/provider/tier/currency and must be effective for the run.
  • Complete usage plus current prices can support EXACT; partial usage cannot.
  • Shared cost requires an explicit rule, weight and denominator. 50/50 is acceptable only when it is explicitly the chosen rule and evidence—not because two agents happen to exist.
  • Retry, tool and external-provider costs must change the cost calculation when their chargeable evidence changes.
  • Budget consumption, warning and stop states are recomputed after allocation; a stop state requires escalation.

Worked examples

1. Traceable baseline

A synthetic run records three requests, 120k input tokens including 20k cached, 30k output tokens, tool usage, one retry charge and one external-provider charge. The dated synthetic price snapshot matches the model/provider/tier. Known direct cost is calculated, a shared-cost pool is allocated by an explicit 60/100 weight, and unit cost is derived from two completed units of work. The final state is review-ready only if the reported numbers match the recomputation.

2. Changed model, old price snapshot

Change model_id but keep model_price_model_id and the previous monetary result. The result is HOLD, even if all arithmetic still adds up. Correct arithmetic with the wrong price authority is not an exact cost.

3. Transfer with missing adapter detail

The price snapshot changes, a second agent shares the workflow, and one adapter omits detailed usage. Preserve missing_usage_state=MISSING_PARTIAL, use a bounded estimate/review state, apply an explicit allocation rule, and recompute. Never copy the old exact cost and never silently divide by two.

Failure modes

  • Token-total shortcut: treating total tokens as exact monetary cost.
  • Current-price oracle: applying today's price to an older run without a dated basis.
  • Context mismatch: using the right number with the wrong model/provider/tier.
  • Zero-versus-omitted confusion: treating a missing provider field as a measured zero.
  • Silent allocation: assigning all shared cost to one owner or dividing it equally without a rule.
  • Retry blindness: adding retries, tools or external usage while leaving cost unchanged.
  • Budget drift: reporting old budget consumption after a new allocated cost.
  • Baseline oracle: reusing the previous exact result after provider price or workflow sharing changes.

Alternatives and trade-offs

You can meter at request, run, agent, workflow or customer-allocation level. Finer granularity improves diagnosis but adds storage and reconciliation overhead. A normalized SDK usage object is simpler across providers; preserved raw usage is stronger when provider-specific field presence matters. A conservative estimate can be operationally safer than pretending incomplete data is exact.

The lesson does not prescribe one universal allocation method. Direct attribution, weighted activity, explicit equal split and another governed rule can all be valid in different systems. What is forbidden is unrecorded allocation.

Experienced bridge

If token accounting is familiar, answer these four questions instead of rereading definitions:

  1. Can every chargeable unit be traced to a run/request and usage source?
  2. Does every unit price match the model/provider/tier and effective time?
  3. Is every shared cost assigned by an explicit rule with reproducible weights?
  4. Would the budget state change if one retry, tool charge, or missing usage record changed?

If any answer is unknown, EXACT is too strong.

Guided and independent practice

Inspect derived_text/tables/AGN-007-T1.csv, then run:

python -B lab/AGN-007-LAB1/learner/run_checks.py

For independent practice, hide the expected decision labels and create one new case where a provider changes price and another adapter omits one usage detail. Preserve the unknown rather than filling it with a guess.

Verification evidence

Passing evidence is not a screenshot of a vendor dashboard. It is a reproducible ledger whose token identities, price context, arithmetic, allocation, unit cost and budget state can be recomputed from visible fields. The lab must reject model/price mismatch, missing usage labeled exact, stale price labeled exact, changed retry/tool/external charges with unchanged cost, and invalid budget states.

No hidden model reasoning is needed to reproduce the result.

Assessment and transfer

Assessment covers boundary retrieval, baseline application, mutation diagnosis and transfer. In transfer, the provider price changes, a second agent shares part of the workflow and one adapter omits detailed usage. Rebuild the price binding, missing-usage state, allocation, unit cost and budget state from the new evidence.

Copying the baseline exact cost fails transfer even when the final number appears plausible.

References and freshness

  • OpenAI Agents SDK — Usage: current run/per-request usage fields and raw-usage preservation behavior.
  • OpenAI API model/pricing documentation: current model/token-category pricing surfaces; rates are volatile and must be snapshotted for real metering.
  • Frozen Lesson Bible lesson://AGN-007: local MAKNOW authority for exactness, allocation and budget-state design.

Recheck vendor usage/pricing semantics by 2026-10-18 or earlier on material change. Synthetic lab unit prices are teaching data, not current vendor rates or accounting advice.

Assessment

There is no answer key in this lesson pack; answer it yourself and mark honestly. "Needs review" sends the lesson to your review queue.

AGN-007-S1 retrieval

Why are measured usage and monetary cost separate evidence layers?

lesson ✗AI ✗notes ✗

AGN-007-S2 application

Build the baseline Agent Usage, Cost & Budget Control Ledger from visible synthetic evidence.

lesson ✗AI ✗notes ✗

AGN-007-S3 diagnosis

Change model_id but keep the old price snapshot and exact cost. What fails first and why?

lesson ✗AI ✗notes ✗

AGN-007-S4 transfer

Recompute after a provider price change, shared workflow and one adapter with partial usage; do not reuse baseline exact cost.

lesson ✗AI ✗notes ✗
Assessment rubric

Passing work must: (1) keep AGN-007 scope separate from retry reconciliation and contracts, (2) bind usage to dated model/provider/tier price context, (3) preserve missing/stale evidence as non-exact, (4) use an explicit shared-cost allocation rule, (5) recompute unit cost and budget state, and (6) rebuild transfer from changed evidence. Any fabricated exact cost is a critical failure.

References & freshness

OpenAI Agents SDK — Usage
·
OpenAI API — Models and pricing surfaces
·
Frozen Lesson Bible AGN-007
·

Case studies

Lab files

این Lab کاملاً آفلاین و synthetic است؛ هیچ API key، billing account، network یا داده واقعی لازم نیست.

python -B run_checks.py را اجرا کنید. evaluator صحت usage، اتصال به price context تاریخ‌دار، allocation صریح، unit cost، budget و transfer را بررسی می‌کند. قیمت‌ها صرفاً آموزشی هستند.