Skip to main content

Give an agent a budget

Limit the calls, the tokens and the cost of an agent for each hour, day and month, and stop it at the limit.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoJavaC# / .NET

What it shows​

  1. An agent, "Research summarizer", has a budget: 5,000 model tokens for each day.
  2. After each model call, the agent reports the tokens and the cost of that call to LumoAuth.
  3. The answer to each report holds the budget and says whether it is spent. The agent stops when it is.
  4. An agent that goes on is refused by the server with 429 and budget_exceeded.

LumoAuth does not see the model calls of an agent. Token limits and cost limits therefore count only the usage that is reported. Limits on calls need no report: LumoAuth counts the Ask API calls, the tool checks, the token requests and the just-in-time requests itself.

Before you start​

  • Check that your plan includes agent budgets in the plans matrix.
  • An agent in the registry with a budget, and its client ID and secret. The setup script registers the agent and prints both values. In the portal, the budget is on the edit page of the agent, under Budget and limits.
  • The setup script needs an API key with the scopes admin:agents:read and admin:agents:write. Create it in the portal under Applications & developer tools, API keys.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor the setup script only: an API key with the scopes admin:agents:read and admin:agents:write.
AGENT_CLIENT_IDThe client ID of the agent. The setup script prints it.
AGENT_CLIENT_SECRETThe client secret of the agent. The setup script prints it once.

The setup script registers the agent with its budget, through the Admin API. Run it again before each run of a program: it registers the agent again, with an unused budget.

node agents/budgets/setup.mjs
setup.mjs
// Registers the agent of the recipe, "Research summarizer", with a budget of
// 5,000 model tokens for each day, and prints its client ID and secret.
//
// node agents/budgets/setup.mjs
//
// Run it again to start with an unused budget: the script deletes the agent
// and registers it again, because usage cannot be set back.
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { call, list, printEnv } from '../../_lib/admin.mjs';

const name = 'Research summarizer';

for (const old of (await list('/admin/agents')).filter((a) => a.name === name)) {
await call('DELETE', `/admin/agents/${old.agentId}`);
}

const agent = (
await call('POST', '/admin/agents', {
name,
description: 'Reads reports and writes summaries with a language model.',
identityType: 'client_secret',
capabilities: ['reports:read'],
// Usage counts in UTC windows. Other keys limit calls and cost, for each
// hour, day and month.
budgetPolicy: { max_tokens_per_day: 5000 },
})
).data;

console.log(`Agent "${name}" (${agent.agentId}) has the budget ${JSON.stringify(agent.budgetPolicy)}`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: agent.clientSecret });

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization.

agents/budgets/js/budget.mjs
// The agent reports what each model call used, and stops when its budget
// is spent.
//
// node agents/budgets/js/budget.mjs
import { LumoAgent, LumoAuthRateLimitError } from '@lumoauth/agent';

// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();

let budget = await agent.budget();
console.log(`before: ${budget.tokens_used_today} of ${budget.max_tokens_per_day} tokens used today`);

for (let call = 1; !budget.exhausted; call++) {
// The model call is here. LumoAuth does not see it, so the agent reports
// the tokens and the cost that the model provider returned.
({ budget } = await agent.reportUsage({ tokens: 2000, costUsd: 0.01 }));
console.log(`model call ${call}: 2000 tokens reported, ${budget.tokens_used_today} of ${budget.max_tokens_per_day} used`);
}
console.log('the budget is spent, so the agent stops');

// An agent that goes on is refused by the server: 429 with budget_exceeded.
try {
await agent.ask('reports:read');
} catch (error) {
if (!(error instanceof LumoAuthRateLimitError) || error.body?.error !== 'budget_exceeded') throw error;
console.log(`ask reports:read: refused with budget_exceeded, retry after ${error.retryAfter} seconds`);
}
node agents/budgets/js/budget.mjs

Check the result​

Output
before: 0 of 5000 tokens used today
model call 1: 2000 tokens reported, 2000 of 5000 used
model call 2: 2000 tokens reported, 4000 of 5000 used
model call 3: 2000 tokens reported, 6000 of 5000 used
the budget is spent, so the agent stops
ask reports:read: refused with budget_exceeded, retry after 81458 seconds
  • retry after is the number of seconds until the spent window ends. For a daily limit, that is the start of the next UTC day.
  • Run a program again without the setup script. It stops at its first request, because a token request also counts against the budget.
  • Open Audit logs in the portal and filter by the event type agent.budget_exhausted. The report that spent the budget is there.
  • The edit page of the agent shows the calls, the tokens and the cost under Usage in the current windows.
  • Your services can learn about a spent budget from the webhook event agent.budget_exhausted.

Limits​

  • A report tells LumoAuth about usage that has happened, so LumoAuth always accepts it. The third model call of the program therefore ends above the limit.
  • An agent reports its own usage, so an agent with a defect can leave usage out. A component that you trust, such as an AI gateway, can report for the agent with POST /admin/agents/{agentId}/usage.
  • The server refuses with the error of a rate limit: the SDKs raise their rate limit error, and budget_exceeded is in the body of the answer.
  • max_steps and timeout_seconds are stored and returned to the agent. LumoAuth refuses nothing on their account: the code of the agent applies them.