UsageLimits lets you set hard caps on how much an agent may consume during a single run. When a limit is exceeded, the SDK throws a UsageLimitError before the next model request, stopping the run cleanly.
The UsageLimits interface
When limits are checked
The SDK checks usage limits before each model request in the turn loop. This means:- The check runs after tool results are appended but before sending the next prompt.
- If the current usage already meets or exceeds a limit,
UsageLimitErroris thrown immediately. - A run that stays within limits for its entire lifetime never throws this error.
Agent-level limits
SetusageLimits on the Agent constructor to apply the same caps to every run of that agent:
Per-run limits
PassusageLimits to agent.run() (or agent.stream()) to override or supplement the agent-level limits for a single run. Per-run limits take precedence.
Handling UsageLimitError
Import and catch UsageLimitError to respond gracefully when a limit is hit:
UsageLimitError properties
| Property | Type | Description |
|---|---|---|
limitKind | "requests" | "inputTokens" | "outputTokens" | "totalTokens" | Which limit was exceeded |
current | number | The usage value at the point of failure |
limit | number | The configured cap that was hit |
message | string | Human-readable description, e.g. "Usage limit exceeded: totalTokens reached 10000 (limit: 10000)" |
Combining with maxTurns
usageLimits.maxRequests and maxTurns both cap the number of model calls, but they are distinct:
| Setting | Throws | Checked |
|---|---|---|
maxTurns | MaxTurnsError | After the turn loop — stops the agent when the turn count is reached |
usageLimits.maxRequests | UsageLimitError | Before each model request — stops the agent when the request count is met |
maxTurns as a structural safety net and usageLimits.maxRequests when you want to track requests against a quota.
Accessing usage inside a run
The current cumulative usage is available onRunContext inside tools and result validators via ctx.usage:
Agents
Full Agent constructor options including maxTurns
Troubleshooting
Understanding and catching UsageLimitError