Skip to main content

Overview

Token and cost guards catch runaway agent behavior — infinite loops, unexpectedly expensive model calls, or token budget overruns. They use the token_usage data recorded in each LLM call.

assert_total_tokens_under

Assert that total token usage across all turns stays under a limit:
Sums prompt_tokens + completion_tokens (OpenAI) or input_tokens + output_tokens (Anthropic) across all turns.

Missing token data

By default, turns without token data are included in the count as zero. Pass allow_missing=False to fail if any turn lacks token usage:

assert_cost_under

Assert that estimated cost stays under a USD limit, using per-model pricing:

How pricing works

  • Costs are specified as USD per 1M tokens for input and output separately
  • Model names are matched by longest prefix"gpt-4o" matches "gpt-4o-2024-08-06"
  • Turns with unmatched models emit a warning and are skipped (or fail if allow_unpriced=False)

Example