Skip to content

Use Limitry with agent frameworks

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.

Create the $5-a-day budget for every agent from Give AI agents a budget. Its action is *, so every check for an agent draws from it.

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:

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;
}
}

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.

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:

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;
}
}

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

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;
}
}

A Mastra agent takes an AI SDK model, so it takes the Limitry middleware from Use Limitry with the Vercel AI SDK as it is. Wrap the agent’s model with the agent as the subject:

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.

  • 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 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.

Related: Reservations.