How to limit cost per agent run

PythonNode.js

Monthly caps don't protect you from a single bad run. One 3-hour research loop can exhaust your budget before the cap triggers. AgentBill enforces a ceiling at the invocation level — before any tokens are consumed.

The problem with monthly caps

A monthly cap fires after the damage is done. By the time you get the alert, the run already happened. AgentBill checks the budget before the run starts. If the estimated units exceed your ceiling, the call is blocked immediately — no compute, no cost.

Install

pip install agentbill-sdk

Set a ceiling at client initialization

Pass ceiling when creating the client. Every preflight() call will be blocked if estimated_units exceeds this value.

from agentbill import AgentBillClient

# Block any run estimated at more than 50 units
client = AgentBillClient(api_key="agb_your_key", ceiling=50)
      

Run the preflight check

check = client.preflight(
    agent_id="my_agent",
    estimated_units=10,        # how many units this run is expected to use
    customer_id="user_123"     # optional: per-customer enforcement
)

if not check.approved:
    raise Exception(f"Run blocked: {check.reason}")

# Your agent runs here — budget is confirmed
result = run_agent()

# Record actual units used
client.record(agent_id="my_agent", units=10, customer_id="user_123")
      

Use the @gate decorator (shortest path)

The @client.gate() decorator handles preflight and record automatically. No boilerplate.

@client.gate(agent_id="my_agent", estimated_units=10, customer_id="user_123")
def run_agent(task: str) -> str:
    # preflight runs before this body
    # record runs after this body completes
    return do_the_work(task)
      

Handle blocking errors

from agentbill import AgentBillClient, BudgetExhaustedError, CeilingExceededError

try:
    result = run_agent("analyze this")
except CeilingExceededError:
    return {"error": "run exceeds per-request ceiling"}
except BudgetExhaustedError:
    return {"error": "customer budget exhausted"}
      

Node.js

import { AgentBillClient } from 'agentbill'

const client = new AgentBillClient({ apiKey: 'agb_your_key', ceiling: 50 })

const check = await client.preflight({ agentId: 'my_agent', estimatedUnits: 10 })
if (!check.approved) throw new Error(check.reason)

const result = await runAgent()

await client.record({ agentId: 'my_agent', units: 10 })
      

Get your API key — free tier, no credit card

Related guides

How to add billing to a LangChain agent How to add a spend ceiling to an OpenAI agent How to limit cost per agent run