# Give AI agents a budget

> Cap what each of your agents can spend on models and paid tools, stop it cleanly at the cap, and let a person approve more.

Say your product runs AI agents on your customers’ behalf, and each agent calls models and paid tools in a loop. A loop that goes wrong can spend a lot before anyone notices. Give every agent a budget in money, and have the agent check it before every step.

## 1. Create the budget

Count in cents. $5 a day for every agent:

* TypeScript

  ```ts
  import { createClient } from "@limitry/sdk";

  // Uses the LIMITRY_API_KEY environment variable.
  const limitry = createClient();

  const limit = await limitry.limits.create({
    name: "Agent daily budget",
    subject: { kind: "agent" },
    action: "*",
    amount: 500,
    unit: "cents",
    window: "day",
    failMode: "closed",
  });
  console.log(limit.id);
  ```

* Python

  ```python
  from limitry import Limitry

  # Uses the LIMITRY_API_KEY environment variable.
  limitry = Limitry()

  limit = limitry.limits.create(
      name="Agent daily budget",
      subject={"kind": "agent"},
      action="*",
      amount=500,
      unit="cents",
      window="day",
      fail_mode="closed",
  )
  print(limit.id)
  ```

* CLI

  ```bash
  limitry limits create --name "Agent daily budget" --subject '{"kind":"agent"}' \
    --action "*" --amount 500 --unit cents --window day --fail-mode closed
  ```

* curl

  ```bash
  curl -X POST https://api.limitry.com/v1/limits \
    -H "Authorization: Bearer $LIMITRY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"Agent daily budget","subject":{"kind":"agent"},"action":"*",
         "amount":500,"unit":"cents","window":"day","failMode":"closed"}'
  ```

`action` is `*`, so every check you make for an agent draws from the same budget. The fail mode is `closed`, so if your code can’t reach Limitry, the agent stops rather than spending without a count. Limitry stores every cent before it responds, so the budget never goes over, even if a server fails.

For a budget that never resets, such as $20 for one long task, use the window `total` instead of `day`. See [Pools, balances and budgets](/docs/pools-and-budgets/).

## 2. Check before every step

Before each step, whether it calls a model or a paid tool, reserve what it will probably cost with the action `tool`, and commit what the step actually cost:

* TypeScript

  ```ts
  import {
    createClient,
    LimitReachedError,
    UnavailableError,
  } from "@limitry/sdk";

  // Uses the LIMITRY_API_KEY environment variable.
  const limitry = createClient();

  async function step(agentId: string, run: () => Promise<Step>) {
    return limitry.reserve(
      { subject: { kind: "agent", id: agentId }, action: "tool", cost: 10 },
      async (reservation) => {
        const result = await run();
        reservation.cost(result.costCents);
        return result;
      },
    );
  }

  export async function runAgent(agentId: string, task: Task) {
    try {
      while (!task.done) {
        await step(agentId, () => nextStep(task));
      }
    } catch (err) {
      if (err instanceof LimitReachedError) {
        return pause(task, "This agent reached its budget for today.");
      }
      if (err instanceof UnavailableError) {
        return pause(task, "Limitry can't be reached; trying again later.");
      }
      throw err;
    }
  }
  ```

* Python

  ```python
  from limitry import LimitReachedError, Limitry, UnavailableError

  # Uses the LIMITRY_API_KEY environment variable.
  limitry = Limitry()


  def step(agent_id: str, run):
      with limitry.reserve(
          subject={"kind": "agent", "id": agent_id}, action="tool", cost=10
      ) as reservation:
          result = run()
          reservation.cost = result.cost_cents
          return result


  def run_agent(agent_id: str, task):
      try:
          while not task.done:
              step(agent_id, lambda: next_step(task))
      except LimitReachedError:
          return pause(task, "This agent reached its budget for today.")
      except UnavailableError:
          return pause(task, "Limitry can't be reached; trying again later.")
  ```

Once the agent has used up its budget, Limitry says no to the next step before it runs. The agent stops between steps rather than in the middle of one.

Built on an agent framework? The Claude Agent SDK, the OpenAI Agents SDK, LangChain and LangGraph, and Mastra each have a place for this check: see [Agent frameworks](/docs/works-with/agent-frameworks/).

## 3. Let a person approve more

A daily budget resets at midnight UTC. To let an agent go past its cap sooner, a person decides:

* **For one day:** the owner or an admin clicks **Reset** next to the agent on the [Usage](/docs/usage/) page, which resets its budget at once (see [Reset now](/docs/resets/#reset-now)). In test, members can too.
* **For good:** the owner or an admin adds a limit for that one agent, with `subject.id` set. It replaces the `agent` limit with the same action and window, so it can raise that agent’s budget. In test, members can too.
* **Through approvals:** with a `total` budget instead of a daily one, an assistant you connected to Limitry’s MCP server can ask for more credits. The owner or an admin approves or denies the request in the app. In test, members can too. Asking needs a person’s credential, so an agent that checks with a workspace API key can’t ask for itself. The request names the environment the budget is in, and without one the credits go to test. See [Approvals](/docs/approvals/).

## 4. Know when an agent stops

The first time an agent reaches its budget in a window, your webhook endpoints receive [`limit.reached`](/docs/usage/#webhook-limitreached). It carries the agent’s id, so you can tell the person who started it.

Related: [Reservations](/docs/reservations/), [Limit AI spend per user](/docs/guides/limit-ai-spend/).
