# Use Limitry with agent frameworks

> Give each agent a budget in the Claude Agent SDK, the OpenAI Agents SDK, LangChain and LangGraph, or Mastra, and stop it cleanly between steps.

Agent frameworks run the loop: the model thinks, calls a tool, and thinks again. Limitry gives each agent a budget across that whole loop. Each framework has a place to check it, and the agent stops cleanly between steps when the budget runs out.

## 1. Create the budget

Create the $5-a-day budget for every agent from [Give AI agents a budget](/docs/guides/agent-budgets/#1-create-the-budget). Its action is `*`, so every check for an agent draws from it.

## Claude Agent SDK

The Claude Agent SDK caps a run’s spend with `maxBudgetUsd`, and reports what the run cost. Reserve the run’s cap from the agent’s budget, give the agent the same cap, then commit what the run cost:

* TypeScript

  ```ts
  import { query } from "@anthropic-ai/claude-agent-sdk";
  import { createClient, LimitReachedError } from "@limitry/sdk";

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

  export async function runTask(agentId: string, task: string) {
    try {
      // Set aside the run's whole cap, $2, and give the agent the same cap.
      return await limitry.reserve(
        {
          subject: { kind: "agent", id: agentId },
          action: "tool",
          cost: 200,
          ttlSeconds: 3600,
        },
        async (reservation) => {
          const options = { maxBudgetUsd: 2 };
          for await (const message of query({ prompt: task, options })) {
            if (message.type === "result") {
              reservation.cost(Math.ceil(message.total_cost_usd * 100));
              return message.subtype === "success" ? message.result : null;
            }
          }
          return null;
        },
      );
    } catch (err) {
      if (err instanceof LimitReachedError) {
        return "This agent reached its budget for today.";
      }
      throw err;
    }
  }
  ```

* Python

  ```python
  import math

  from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
  from limitry import AsyncLimitry, LimitReachedError

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

  async def run_task(agent_id: str, task: str) -> str | None:
      try:
          # Set aside the run's whole cap, $2, and give the agent the same cap.
          async with limitry.reserve(
              subject={"kind": "agent", "id": agent_id},
              action="tool",
              cost=200,
              ttl_seconds=3600,
          ) as reservation:
              options = ClaudeAgentOptions(max_budget_usd=2)
              async for message in query(prompt=task, options=options):
                  if isinstance(message, ResultMessage):
                      reservation.cost = math.ceil((message.total_cost_usd or 0) * 100)
                      return message.result
              return None
      except LimitReachedError:
          return "This agent reached its budget for today."
  ```

What the run didn’t spend goes straight back to the agent’s budget. For a run longer than an hour, call `reservation.extend()` as it goes.

## OpenAI Agents SDK

The OpenAI Agents SDK calls the model once per step. Check the budget at each call, and commit the tokens it used. In TypeScript, wrap the model. In Python, add run hooks:

* TypeScript

  ```ts
  import {
    Agent,
    run,
    type Model,
    type ModelRequest,
    type ModelResponse,
  } from "@openai/agents";
  import { OpenAIProvider } from "@openai/agents-openai";
  import { createClient, LimitReachedError } from "@limitry/sdk";

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

  // Your prices, in cents per million tokens.
  const priceCents = (response: ModelResponse) =>
    Math.ceil(
      (response.usage.inputTokens * 300 + response.usage.outputTokens * 1500) /
        1_000_000,
    );

  // Reserves before each model call in the run, and commits what it cost.
  class BudgetedModel implements Model {
    constructor(
      private readonly model: Model,
      private readonly agentId: string,
    ) {}

    getResponse(request: ModelRequest) {
      return limitry.reserve(
        {
          subject: { kind: "agent", id: this.agentId },
          action: "tool",
          cost: 10,
        },
        async (reservation) => {
          const response = await this.model.getResponse(request);
          reservation.cost(priceCents(response));
          return response;
        },
      );
    }

    getStreamedResponse(request: ModelRequest) {
      return this.model.getStreamedResponse(request);
    }
  }

  export async function runTask(agentId: string, task: string) {
    const model = await new OpenAIProvider().getModel("gpt-6.2-sol");
    const agent = new Agent({
      name: "Researcher",
      instructions: "Answer with sources.",
      model: new BudgetedModel(model, agentId),
    });
    try {
      const result = await run(agent, task);
      return result.finalOutput;
    } catch (err) {
      if (err instanceof LimitReachedError) {
        return "This agent reached its budget for today.";
      }
      throw err;
    }
  }
  ```

* Python

  ```python
  import math

  from agents import Agent, RunContextWrapper, RunHooks, Runner, TResponseInputItem
  from agents.items import ModelResponse
  from limitry import AsyncLimitry, LimitReachedError

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

  # Your prices, in cents per million tokens.
  def price_cents(response: ModelResponse) -> int:
      usage = response.usage
      return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)

  class AgentBudget(RunHooks):
      """Reserves before each model call in the run, and commits what it cost."""

      def __init__(self, agent_id: str) -> None:
          self.agent_id = agent_id
          self.reservation_id: str | None = None

      async def on_llm_start(
          self,
          context: RunContextWrapper,
          agent: Agent,
          system_prompt: str | None,
          input_items: list[TResponseInputItem],
      ) -> None:
          decision = await limitry.checks.create(
              subject={"kind": "agent", "id": self.agent_id},
              action="tool",
              cost=10,
              mode="reserve",
          )
          if not decision.allowed or decision.reservation is None:
              raise LimitReachedError(decision)
          self.reservation_id = decision.reservation.id

      async def on_llm_end(
          self, context: RunContextWrapper, agent: Agent, response: ModelResponse
      ) -> None:
          if self.reservation_id:
              await limitry.reservations.commit(self.reservation_id, cost=price_cents(response))
              self.reservation_id = None

  async def run_task(agent_id: str, task: str) -> str:
      agent = Agent(name="Researcher", instructions="Answer with sources.")
      try:
          result = await Runner.run(agent, task, hooks=AgentBudget(agent_id))
          return str(result.final_output)
      except LimitReachedError:
          return "This agent reached its budget for today."
  ```

## LangChain and LangGraph

A LangChain agent runs on LangGraph, and its middleware wraps every model call the agent makes. Add one middleware for the budget:

* TypeScript

  ```ts
  import { createClient, LimitReachedError } from "@limitry/sdk";
  import { createAgent, createMiddleware, type AIMessage } from "langchain";

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

  // Your prices, in cents per million tokens.
  const priceCents = (message: AIMessage) =>
    Math.ceil(
      ((message.usage_metadata?.input_tokens ?? 0) * 300 +
        (message.usage_metadata?.output_tokens ?? 0) * 1500) /
        1_000_000,
    );

  // Reserves before each model call the agent makes, and commits its cost.
  const agentBudget = (agentId: string) =>
    createMiddleware({
      name: "LimitryBudget",
      wrapModelCall: (request, handler) =>
        limitry.reserve(
          { subject: { kind: "agent", id: agentId }, action: "tool", cost: 10 },
          async (reservation) => {
            const message = await handler(request);
            reservation.cost(priceCents(message));
            return message;
          },
        ),
    });

  export async function runTask(agentId: string, task: string) {
    const agent = createAgent({
      model: "openai:gpt-6.2-sol",
      tools: [],
      middleware: [agentBudget(agentId)],
    });
    try {
      const result = await agent.invoke({
        messages: [{ role: "user", content: task }],
      });
      return result.messages.at(-1)?.content;
    } catch (err) {
      // LangChain passes a middleware's error on as its `cause`.
      if (err instanceof Error && err.cause instanceof LimitReachedError) {
        return "This agent reached its budget for today.";
      }
      throw err;
    }
  }
  ```

* Python

  ```python
  import math
  from collections.abc import Callable

  from langchain.agents import create_agent
  from langchain.agents.middleware import ModelRequest, ModelResponse, wrap_model_call
  from langchain.messages import AIMessage
  from limitry import LimitReachedError, Limitry

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

  # Your prices, in cents per million tokens.
  def price_cents(response: ModelResponse) -> int:
      tokens_in = tokens_out = 0
      for message in response.result:
          if isinstance(message, AIMessage) and message.usage_metadata:
              tokens_in += message.usage_metadata["input_tokens"]
              tokens_out += message.usage_metadata["output_tokens"]
      return math.ceil((tokens_in * 300 + tokens_out * 1500) / 1_000_000)

  def agent_budget(agent_id: str):
      """Reserves before each model call the agent makes, and commits its cost."""

      @wrap_model_call
      def budget(
          request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
      ) -> ModelResponse:
          with limitry.reserve(
              subject={"kind": "agent", "id": agent_id}, action="tool", cost=10
          ) as reservation:
              response = handler(request)
              reservation.cost = price_cents(response)
              return response

      return budget

  def run_task(agent_id: str, task: str):
      agent = create_agent(
          model="openai:gpt-6.2-sol", tools=[], middleware=[agent_budget(agent_id)]
      )
      try:
          result = agent.invoke({"messages": [{"role": "user", "content": task}]})
          return result["messages"][-1].content
      except LimitReachedError:
          return "This agent reached its budget for today."
  ```

## Mastra

A Mastra agent takes an AI SDK model, so it takes the Limitry middleware from [Use Limitry with the Vercel AI SDK](/docs/works-with/vercel-ai-sdk/#2-add-the-middleware) as it is. Wrap the agent’s model with the agent as the subject:

```ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { wrapLanguageModel } from "ai";

import { aiBudget } from "./ai-budget";

export const researcher = (agentId: string) =>
  new Agent({
    id: "researcher",
    name: "Researcher",
    instructions: "Answer with sources.",
    model: wrapLanguageModel({
      model: openai("gpt-6.2-sol"),
      middleware: aiBudget({ kind: "agent", id: agentId }),
    }),
  });
```

`researcher(agentId).generate(task)` throws the `LimitReachedError` once the agent’s budget runs out.

## What you see

* A step that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices, against the agent’s $5 for the day.
* On the [Usage](/docs/usage/) page, each agent’s spend today.
* An agent over budget stops before its next model call, never in the middle of one, and your code gets the `LimitReachedError`.

To let a person approve more for an agent, see [Give AI agents a budget](/docs/guides/agent-budgets/#3-let-a-person-approve-more).

Related: [Reservations](/docs/reservations/).
