Billing and consumption
The machine API calls auth-service as your application, with a client_credentials token minted from the application's own secret. It never acts as a user, and it can only read and write the data of your application. Concepts and endpoints are documented in auth-service: Consumption tracking and Stripe integration.
Prerequisites
- A confidential application:
MachineApi(auth)raisesCFG_001withoutclient_secret. - The machine scopes
billing:read,consumption:readandconsumption:write. New confidential applications receive them by default; an application created before that needs a superadmin to set them. A missing scope makes the call raiseTOK_004with the scope indetails["scope"].
from auth_ai import AuthClient
from auth_ai.server import MachineApi
auth = AuthClient(
{
"issuer": "https://auth.example.com",
"client_id": "my-app",
"client_secret": "<client-secret>",
"redirect_uri": "https://app.example.com/auth/callback",
}
)
machine = MachineApi(auth)
Tokens are cached per scope until shortly before they expire, and simultaneous callers share one request to the token endpoint.
Read a user's billing
from auth_ai.server import MachineApi
async def show_billing(machine: MachineApi, user_id: str) -> None:
subscription = await machine.billing.get_subscription(user_id)
if subscription is not None and subscription.is_active:
print(subscription.plan.name, subscription.current_period_end)
usage = await machine.billing.get_usage(user_id)
for feature in usage.features:
# usage_limit -1 is unlimited; remaining is None when unlimited
print(feature.feature_key, feature.used, feature.remaining)
get_subscription returns None when the user holds no subscription. The user_id is the user's sub.
Invoices are keyset-paginated, newest first (limit is 1 to 100):
from auth_ai.server import InvoiceView, MachineApi
async def all_invoices(machine: MachineApi, user_id: str) -> list[InvoiceView]:
invoices: list[InvoiceView] = []
cursor: str | None = None
while True:
page = await machine.billing.list_invoices(user_id, limit=50, cursor=cursor)
invoices.extend(page.items)
if page.next_cursor is None:
return invoices
cursor = page.next_cursor
Report consumption
from auth_ai.server import MachineApi
async def record_export(machine: MachineApi, user_id: str) -> None:
result = await machine.consumption.report(
user_id, "exports", 1, idempotency_key="export-job-8c1f"
)
print(result.aggregate.total, result.metered)
keyis 1 to 64 characters froma-zA-Z0-9.;valueis a finite number, anintor afloat(negative credits back). The SDK validates both, and the user id and the idempotency key, before sending and raisesCFG_001otherwise.aggregate.totalis a decimal string: a running total is not bounded by a double.- Set
idempotency_keyto a stable identifier of the business event (a job id, an order line; at most 200 characters once trimmed). The same key reported twice counts once, which makes retries safe; without one, every call counts.
Counters and metered features
| Plain counter | Metered feature | |
|---|---|---|
| When | The key is any other key. | The key is the featureKey of a metered price on the plan of the user's active subscription. |
metered in the result | False | True |
| Rules | Any finite value. | value must be greater than zero; a report that would pass the plan's cap is refused. |
| Read back with | machine.consumption.list_aggregates(user_id) or .get_aggregate(user_id, key) | machine.billing.get_usage(user_id) |
When the plan's cap is exceeded, auth-service answers with its own error, which the SDK raises as API_001: look at details["apiCode"] (BIL_003 for the cap, BIL_002 for a non-positive value) and details["status"].
from typing import Literal
from auth_ai import AuthAiError
from auth_ai.server import MachineApi
async def record_export(machine: MachineApi, user_id: str, job_id: str) -> Literal["ok", "quota"]:
try:
await machine.consumption.report(user_id, "exports", 1, idempotency_key=f"export-{job_id}")
except AuthAiError as err:
if err.details is not None and err.details.get("apiCode") == "BIL_003":
return "quota"
raise
return "ok"
Reading a key that was never reported rejects: get_aggregate raises API_001 with details["apiCode"] set to CONS_003.
Where to call it
Always from your backend: it needs the application secret. A typical flow is a signed-in request handler that knows session.user_id, performs the work, then reports consumption. Keep the pre-check (get_usage, remaining) as a courtesy to the user and rely on the report's refusal as the authoritative cap.
Call the LiteLLM gateway
Call LLMs and MCP tools through the gateway with the user's own token, handle empty wallets and rate limits, and attribute spend to a session.
Production checklist
What to change before the first real user signs in: stores, locks, secrets, URLs, logout, logging and dependencies.