Skip to content
Claude Task Budgets: Cap Agent Token Spend in Python — ContentBuffer guide

Claude Task Budgets: Cap Agent Token Spend in Python

K
Kodetra Technologies··9 min read Intermediate

Summary

Give Claude agents a token countdown so long agentic loops finish gracefully instead of burning your bill.

The new-model wave that landed at the end of June 2026 (Claude Sonnet 5 on the 30th, Opus 4.8 already shipping, OpenAI's GPT-5.6 preview) all point the same direction: agents that run for minutes or hours, calling tools, thinking, and re-planning. That is great for capability and terrifying for your invoice. A single agentic loop that goes sideways can quietly spend a million tokens before you notice.

Anthropic's answer is a beta feature called task budgets. Instead of hoping your agent behaves, you hand it a token budget for the whole loop. The model watches a live countdown and paces itself: it prioritizes the important work early and wraps up gracefully as the budget runs low, rather than getting chopped off mid-action by a hard limit.

This guide shows you exactly how to wire task budgets into a Python agentic loop, how the countdown actually counts (it is not what you send in the payload), how to size a budget from real measurements, and the sharp edges that will bite you if you skip the docs. Every code sample matches the Messages API shape as of the task-budgets-2026-03-13 beta.


What a task budget actually does

A task budget tells Claude how many tokens it has for a full agentic loop: thinking, tool calls, tool results, and final output all count. The model sees a budget-countdown marker that the server injects on every turn, and it uses that signal to decide what to do next. As the remaining budget shrinks, the model does less exploration and moves toward finishing.

Two things surprise people. First, the budget is advisory, not enforced. It is a soft target, not a hard wall. The only hard ceiling on a single request is still max_tokens. Second, the countdown counts what Claude sees and generates, not the size of the JSON payload you POST. Because your client resends the full conversation history every turn, your payload grows, but already-seen messages are not charged against the budget a second time.

One important compatibility note before you build: task budgets are in beta on Claude Fable 5, Claude Mythos 5, Claude Opus 4.8, and Claude Opus 4.7. They are not supported on Claude Sonnet 5, Sonnet 4.6, or Haiku 4.5, and not on Claude Code or Cowork surfaces. Use them directly through the Messages API on a supported model.

Prerequisites

  • Python 3.9+ and the official SDK: pip install -U anthropic (use a version that supports the beta client, 0.40+).
  • An Anthropic API key exported as ANTHROPIC_API_KEY.
  • Access to a supported model. Examples here use claude-opus-4-8; claude-opus-4-7, claude-fable-5, and claude-mythos-5 also work.
  • The beta header task-budgets-2026-03-13 on every request that sets a budget.
  • Basic familiarity with the tool-use loop (assistant returns tool_use, you run the tool, you send back a tool_result).

Step 1: Set a task budget

The budget lives inside output_config alongside effort, and you opt in with the beta header. The task_budget object has three fields: type (always "tokens"), total (tokens for the whole loop), and an optional remaining (used only when you carry a budget across a rewrite of context).

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

with client.beta.messages.stream(
    model="claude-opus-4-8",
    max_tokens=128_000,                 # hard per-request ceiling
    output_config={
        "effort": "high",               # depth per step
        "task_budget": {                # breadth across the loop
            "type": "tokens",
            "total": 64_000,
        },
    },
    messages=[
        {"role": "user", "content": "Review the codebase and propose a refactor plan."}
    ],
    betas=["task-budgets-2026-03-13"],
) as stream:
    response = stream.get_final_message()

print(response.usage)

The minimum accepted total is 20,000 tokens. Anything smaller returns a 400 error. Think of effort and task_budget as orthogonal dials: effort tunes how deeply Claude reasons per step, the budget tunes how much total work it does across the whole loop.

Step 2: Understand the countdown (it is not your payload size)

This is the part that trips up almost everyone. The countdown reflects tokens Claude has processed in the current agentic loop: thinking, tool calls, tool results, and generated text. It does not re-count the history you resend on every follow-up request. So a budget of 100,000 does not deplete just because your third request ships 13,000 tokens of conversation.

Here is the same three-turn loop laid out so you can see payload size and budget spend diverge. The budget only decrements by what is new to Claude that turn.

TurnPayload you sent (approx input)Counted against budget this turnBudget remaining after
1~20 tokens5,000 (thinking + tool_use)~95,000
2~7,800 (turn 1 history + tool result)6,800 (2,800 tool result + 4,000 gen)~88,200
3~13,000 (full history + 2nd tool result)7,200 (1,200 tool result + 6,000 text)~81,000
Total~20,820 sent across requests19,000 counted against budget-

The turn-1 user message went out three times and the turn-1 assistant message twice, but each was counted once. Practical takeaway: set a generous budget and let the model self-regulate against the server-side countdown. Do not try to mirror it client-side, and do not decrement remaining on every turn while resending full history, or the model sees an under-reported budget and quits early.

Step 3: Measure a baseline before you pick a number

Do not guess the budget. Run a representative sample of tasks without a budget, record total token spend per task, and start your budget near the p99 of that distribution. This helper runs an agentic loop to completion and sums what Claude generates each turn.

def run_task_and_count_tokens(messages, tools, run_tools):
    """Run an agentic loop to completion, return total tokens Claude spent."""
    total_spend = 0
    while True:
        with client.beta.messages.stream(
            model="claude-opus-4-8",
            max_tokens=128_000,
            messages=messages,
            tools=tools,
            betas=["task-budgets-2026-03-13"],
        ) as stream:
            response = stream.get_final_message()

        # output_tokens covers text + thinking + tool calls generated this turn.
        total_spend += response.usage.output_tokens

        if response.stop_reason == "end_turn":
            return total_spend

        # Append the assistant turn and your tool results, then keep looping.
        messages += [
            {"role": "assistant", "content": response.content},
            {"role": "user", "content": run_tools(response.content)},
        ]

Note that usage.output_tokens does not include the tool-result tokens you feed back in, and those also count against the server-side budget. If you want client-side tracking to match the countdown closely, add the token count of the tool_result blocks you append. For sizing a budget, the output-token sum is usually a good enough proxy.

Step 4: Worked example, a budgeted security-audit agent

Let's build a small but real agentic loop: an agent that audits a repo using a single bash tool, with a 100,000-token budget. The loop executes tool calls locally and feeds results back until Claude stops with end_turn.

import subprocess, anthropic

client = anthropic.Anthropic()

TOOLS = [{
    "name": "bash",
    "description": "Run a read-only shell command in the repo and return stdout.",
    "input_schema": {
        "type": "object",
        "properties": {"command": {"type": "string"}},
        "required": ["command"],
    },
}]

def run_tools(content_blocks):
    results = []
    for b in content_blocks:
        if b.type == "tool_use" and b.name == "bash":
            out = subprocess.run(
                b.input["command"], shell=True,
                capture_output=True, text=True, timeout=30,
            ).stdout[:8000]  # keep tool results bounded
            results.append({
                "type": "tool_result",
                "tool_use_id": b.id,
                "content": out or "(no output)",
            })
    return results

messages = [{
    "role": "user",
    "content": "Audit this repo for obvious security issues and report findings.",
}]

while True:
    with client.beta.messages.stream(
        model="claude-opus-4-8",
        max_tokens=64_000,
        tools=TOOLS,
        output_config={
            "effort": "high",
            "task_budget": {"type": "tokens", "total": 100_000},
        },
        messages=messages,
        betas=["task-budgets-2026-03-13"],
    ) as stream:
        resp = stream.get_final_message()

    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason == "end_turn":
        print(resp.content[-1].text)
        print("usage:", resp.usage)
        break

    messages.append({"role": "user", "content": run_tools(resp.content)})

Notice the budget is set once, on the first request, and never touched again. The server keeps the countdown; the client just runs tools and loops. A representative final turn looks like this:

Findings (3):
1. package.json pins lodash 4.17.4 (CVE-2019-10744, prototype pollution). Bump to >=4.17.12.
2. src/api/auth.js builds a SQL string with template literals from req.query.id -> injection risk.
3. .env with a live STRIPE_SECRET_KEY is committed to the repo. Rotate and add to .gitignore.

usage: Usage(input_tokens=214, output_tokens=6183, ...)

Because the budget was comfortably larger than the work, Claude explored freely and still finished well under 100,000 tokens. If you had set the budget to 22,000 for the same multi-file audit, you would likely see it scope down hard or stop with a partial report. More on that in the pitfalls.

Step 5: Carry a budget across compaction with remaining

If your loop compacts or summarizes earlier turns between requests, the server loses track of how much budget was already spent. Only then do you pass remaining, so the countdown continues instead of resetting to total.

# Only when you rewrite/compact context between requests:
output_config = {
    "effort": "high",
    "task_budget": {
        "type": "tokens",
        "total": 128_000,
        "remaining": 128_000 - tokens_spent_so_far,
    },
}

For the common case where you resend the full uncompacted history every turn, omit remaining entirely and let the server do the counting. Mutating remaining on every request also invalidates prompt caching, because the changing value breaks the cached prefix.

Common pitfalls and gotchas

  • Treating the budget as a hard cap. It is advisory. Claude may overshoot slightly to finish an action cleanly. For a real ceiling on cost or latency, keep a sane max_tokens as the enforced limit and use the budget as the target to pace against.
  • Setting a budget below 20,000. The minimum total is 20,000 tokens; smaller values return a 400 error. There is no way around it.
  • A budget that is too small for the task. If Claude sees a budget clearly insufficient for the work (say 20k for a multi-hour coding job), it may refuse, aggressively scope down, or stop early with a partial result. If you see refusal-like behavior after adding a budget, raise the budget first before touching anything else.
  • Decrementing remaining while resending full history. The model then sees an under-reported budget and wraps up sooner than it should. Set the budget once and leave it alone unless you are compacting context.
  • Expecting the remaining budget in the response. The countdown is visible only to the model. There is no task_budget field in usage, and no SDK accessor. Track spend yourself by summing usage across the loop.
  • Mutating the budget and wondering why caching broke. The countdown marker is injected server-side per turn. Changing remaining client-side alters the cached prefix and busts the cache.
  • Forgetting max_tokens headroom at high effort. At xhigh or max effort, set max_tokens to at least 64k so the model has room to think and act each request; the budget spans many requests but max_tokens caps each one.
  • Using an unsupported model. Task budgets are silently irrelevant on Sonnet 5 / Sonnet 4.6 / Haiku 4.5 because they are not supported there. Use Opus 4.8, Opus 4.7, Fable 5, or Mythos 5.

Quick reference

ItemValue / behavior
Where to set itoutput_config.task_budget
Beta headertask-budgets-2026-03-13
Fieldstype ('tokens'), total, remaining (optional)
Minimum total20,000 tokens (below = 400 error)
What it countsthinking + tool calls + tool results + output
EnforcementAdvisory soft hint, not a hard cap
Hard ceilingmax_tokens (per request)
Response fieldNone; countdown is model-only
When to pass remainingOnly when compacting/rewriting context
Supported modelsOpus 4.8, Opus 4.7, Fable 5, Mythos 5
Not supportedSonnet 5, Sonnet 4.6, Haiku 4.5, Claude Code, Cowork

Next steps

  • Run your top 3 agentic workflows without a budget, log per-task token spend, and set budgets at the p99.
  • Pair task budgets with the effort parameter: drop subagents to low or medium effort, keep the orchestrator at high, and cap the whole loop with one budget.
  • Add client-side usage summing to compare your tracked spend against how the model actually paced itself.
  • For a hard ceiling, wrap the loop with a max_tokens value and an outer request counter as a kill switch.
  • Read the official task budgets and effort docs on platform.claude.com before shipping to production.

Task budgets are a small API addition with an outsized effect: they turn 'hope the agent stops' into 'the agent knows when to stop.' As models get more autonomous through the second half of 2026, that countdown is one of the cheapest guardrails you can add.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,617 newsletter subscribers.

Also get