Build the cost guardrails before the loop runs long.
1. Set a task budget for the whole loop. Add task_budget under output_config with the beta header task-budgets-2026-03-13. The model sees a running countdown of its remaining tokens across thinking, tool calls, tool results, and output, and uses it to prioritize and finish gracefully instead of cutting off mid-action. Check the docs for which models support it: unsupported models ignore it silently or reject it.
2. Pair it with effort, not instead of it. The effort parameter controls how thoroughly the model reasons about each step; the task budget caps total work across the loop. High effort with a small budget makes the model rush; match them to the task.
3. Know what the budget does not tell you. The countdown is visible only to the model. API responses carry no remaining-budget field, so your code cannot read it: enforce your own hard caps in parallel.
4. Enforce hard caps in code. Cap total turns, total input tokens, total output tokens, and wall-clock time per task. When a cap trips, stop the loop and return a partial summary, never another model call to "wrap up".
5. Clear stale context as the loop grows. Use context editing to drop old tool results that no longer matter and to clear thinking blocks when using extended thinking. Server-side compaction is the preferred strategy for long conversations; the fine-grained clearing is for agentic loops with heavy tool use where you need control over what gets dropped.
6. Log usage per turn. Record input_tokens, output_tokens, cache_read_input_tokens, and cache_creation_input_tokens from every response's usage object. Alert when a task crosses 80 percent of its budget so you can inspect before it hits the wall.