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.
What it shows
- An agent, "Research summarizer", has a budget: 5,000 model tokens for each day.
- After each model call, the agent reports the tokens and the cost of that call to LumoAuth.
- The answer to each report holds the budget and says whether it is spent. The agent stops when it is.
- An agent that goes on is refused by the server with
429andbudget_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:readandadmin:agents:write. Create it in the portal under Applications & developer tools, API keys.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | For the setup script only: an API key with the scopes admin:agents:read and admin:agents:write. |
AGENT_CLIENT_ID | The client ID of the agent. The setup script prints it. |
AGENT_CLIENT_SECRET | The 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.
- Node.js
- Python
- Go
- Java
- C#
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
agents/budgets/python/budget.py
# The agent reports what each model call used, and stops when its budget
# is spent.
#
# python agents/budgets/python/budget.py
from lumoauth import LumoAuthAgent, LumoAuthRateLimitError
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent = LumoAuthAgent()
budget = agent.get_budget_status()
print(f"before: {budget['tokens_used_today']} of {budget['max_tokens_per_day']} tokens used today")
call = 0
while not agent.is_budget_exhausted():
call += 1
# 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 = agent.report_usage(tokens=2000, cost_usd=0.01)["budget"]
print(f"model call {call}: 2000 tokens reported, {budget['tokens_used_today']} of {budget['max_tokens_per_day']} used")
print("the budget is spent, so the agent stops")
# An agent that goes on is refused by the server: 429 with budget_exceeded.
try:
agent.ask("reports:read")
except LumoAuthRateLimitError as error:
if error.body.get("error") != "budget_exceeded":
raise
print(f"ask reports:read: refused with budget_exceeded, retry after {error.retry_after:.0f} seconds")
python agents/budgets/python/budget.py
agents/budgets/go/main.go
// The agent reports what each model call used, and stops when its budget
// is spent.
//
// go run ./agents/budgets/go
package main
import (
"context"
"errors"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
ctx := context.Background()
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
budget, err := agent.Budget(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("before: %d of %d tokens used today\n", budget.TokensUsedToday, budget.MaxTokensPerDay)
// CheckBudget reads the budget that the agent keeps. A report renews it.
for call := 1; agent.CheckBudget(ctx) == nil; 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.
report, err := agent.ReportUsage(ctx, 2000, 0.01)
if err != nil {
log.Fatal(err)
}
fmt.Printf("model call %d: 2000 tokens reported, %d of %d used\n",
call, report.Budget.TokensUsedToday, report.Budget.MaxTokensPerDay)
}
fmt.Println("the budget is spent, so the agent stops")
// An agent that goes on is refused by the server: 429 with budget_exceeded.
_, err = agent.Ask(ctx, "reports:read", nil)
apiErr, ok := lumoauth.AsAPIError(err)
if !ok || !errors.Is(err, lumoauth.ErrRateLimited) {
log.Fatalf("expected a refusal, got: %v", err)
}
fmt.Printf("ask reports:read: refused with %v, retry after %.0f seconds\n",
apiErr.Body.(map[string]any)["error"], apiErr.RetryAfter.Seconds())
}
go run ./agents/budgets/go
agents/budgets/java/Budget.java
// The agent reports what each model call used, and stops when its budget
// is spent.
//
// java -cp "java/lib/*" agents/budgets/java/Budget.java
import io.lumoauth.LumoAgent;
import io.lumoauth.errors.LumoAuthRateLimitException;
import io.lumoauth.model.AgentBudget;
import java.time.Duration;
public class Budget {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
LumoAgent agent = LumoAgent.fromEnvironment();
AgentBudget budget = agent.budget();
System.out.printf("before: %d of %d tokens used today%n", budget.tokensUsedToday(), budget.maxTokensPerDay());
for (int 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 = agent.reportUsage(2000, 0.01).budget();
System.out.printf("model call %d: 2000 tokens reported, %d of %d used%n",
call, budget.tokensUsedToday(), budget.maxTokensPerDay());
}
System.out.println("the budget is spent, so the agent stops");
// An agent that goes on is refused by the server: 429 with budget_exceeded.
try {
agent.ask("reports:read");
} catch (LumoAuthRateLimitException e) {
System.out.printf("ask reports:read: refused with %s, retry after %d seconds%n",
e.bodyField("error").orElse("?"), e.retryAfter().orElse(Duration.ZERO).toSeconds());
}
}
}
java -cp "java/lib/*" agents/budgets/java/Budget.java
agents/budgets/csharp/Budget.cs
#:package LumoAuth@1.7.0
#:property PublishAot=false
// The agent reports what each model call used, and stops when its budget
// is spent.
//
// dotnet run agents/budgets/csharp/Budget.cs
using LumoAuth;
using LumoAuth.Errors;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
var agent = LumoAgent.FromEnvironment();
var budget = await agent.BudgetAsync();
Console.WriteLine($"before: {budget.TokensUsedToday} of {budget.MaxTokensPerDay} tokens used today");
for (var 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.ReportUsageAsync(2000, 0.01)).Budget;
Console.WriteLine($"model call {call}: 2000 tokens reported, {budget.TokensUsedToday} of {budget.MaxTokensPerDay} used");
}
Console.WriteLine("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.AskAsync("reports:read");
}
catch (LumoAuthRateLimitException e)
{
var error = e.Body?.GetProperty("error").GetString();
Console.WriteLine($"ask reports:read: refused with {error}, retry after {e.RetryAfter?.TotalSeconds:0} seconds");
}
dotnet run agents/budgets/csharp/Budget.cs
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 afteris 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_exceededis in the body of the answer. max_stepsandtimeout_secondsare stored and returned to the agent. LumoAuth refuses nothing on their account: the code of the agent applies them.