Skip to main content
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

All fields are optional. Set only the limits you care about — omitted fields are uncapped.

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, UsageLimitError is thrown immediately.
  • A run that stays within limits for its entire lifetime never throws this error.

Agent-level limits

Set usageLimits on the Agent constructor to apply the same caps to every run of that agent:

Per-run limits

Pass usageLimits to agent.run() (or agent.stream()) to override or supplement the agent-level limits for a single run. Per-run limits take precedence.
Per-run limits are useful when the same agent is used for both short and long tasks. Set conservative agent-level defaults and relax them selectively for expensive operations.

Handling UsageLimitError

Import and catch UsageLimitError to respond gracefully when a limit is hit:

UsageLimitError properties

Combining with maxTurns

usageLimits.maxRequests and maxTurns both cap the number of model calls, but they are distinct: Use 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 on RunContext inside tools and result validators via ctx.usage:

Agents

Full Agent constructor options including maxTurns

Troubleshooting

Understanding and catching UsageLimitError