Metering Tokens
Bill the tokens each call burns, with sub-cent accuracy.
Price the model, meter the call
import larz.ai as ai; ai.enable(app)
app.ai.price("larz-writer", input="$0.50/1M", output="$1.50/1M")
@app.ai_metered("larz-writer", per_minute=30)
@app.post("/api/write")
def write(req):
reply, usage = call_llm(req.json()["prompt"])
app.ai.charge(req, "larz-writer", usage["in"], usage["out"])
return {"reply": reply}@app.ai_metered checks the caller has credit (and enforces a rate limit) before the expensive call runs; app.ai.charge() bills the actual tokens after. Costs accumulate in micro-dollars and debit whole cents as they accrue, so sub-cent calls aren't lost to rounding.
Takeaways
- Guard first (don't do unpaid work), charge after (real tokens).
- Prices take
/1M,/1kor/token. - Out of credit โ a clean 402 before your handler runs.