Skip to content
FluxMeter
中文

Writing

Python LLM budget caps: wrap(OpenAI()), hierarchy caps, and soft alerts

Add pre-request budget checks with Python wrap(OpenAI()), hard-cap agent runs, and get BUDGET_WARN webhooks before limits hit (v2.7.0, SDK 1.4.0).

2026-07-06 · Budgets · 6 min read

FluxMeter v2.7.0, with Python SDK 1.4.0, closes the gap between “API exists” and “three lines in production.” Path activation means the default Lite path can enforce, alert, and attribute cost without Kafka — and the Python SDK can sit on the OpenAI client itself.

wrap(OpenAI()) — check and track on the hot path

pip install fluxmeter (1.4.0+), then FluxMeter(api_url="http://localhost:8000") for Lite. wrap(OpenAI(), meter, customer_id=...) runs a pre-call budget check and post-call track. BudgetExceededError means the provider was never called.

For streaming, wrap() reserves an estimate and can raise StreamKilledError mid-stream when estimated cost exceeds the reserve — so a long stream is cut off once its estimated cost passes the reserve instead of overspending unnoticed.

Historical note: older SDK modes could target Kafka directly; current repository SDK 2.0.0 is HTTP-only via Custody.

Hierarchy caps — hard max per agent run

POST /budget/{id}/cap with kind span or session sets a hard max spend. Pass parent_span_id or session_id on GET /budget/{id}/check. When spent + estimate exceeds the cap, the response returns reason=hierarchy_cap.

This is the ClipLive-style control: a single clip job stops at its own cap instead of drawing down the whole creator wallet, even if the monthly balance still has room. It is the same failure mode behind runaway agent costs.

Soft alert ladder on Lite ingest

POST /budget/{id}/webhook configures HTTPS delivery. On Lite, BUDGET_LOW, BUDGET_EXHAUSTED, and BUDGET_WARN fire after /ingest without Kafka. BUDGET_WARN fires at 70% and 90% of (initial_balance + topups), with warn_pct and spent_pct in the payload.

Full mode still uses the Kafka webhook-worker for LOW/EXHAUSTED; the WARN ladder is Lite-path today.

Try the path activation demo

Clone the engine repo and run demos/path_activation_demo.py (self-check, optional --live). Or follow the quickstart to run the stack locally, then exercise wrap(), /cap, and /webhook against localhost:8000.