AI coding

Estimating Token Cost Before You Send an Agent a Task

Antonio Evans6 min read

A person in a small office holds a clipboard and looks at a large screen.
Key points

Key points

  1. 1Count four things before you send a task: files to read, tests to satisfy, decision points, and output length.
  2. 2Convert each count to tokens with a recorded multiplier, add them, and set a ceiling slightly above the total.
  3. 3When a task breaks its ceiling, split it into smaller subtasks or route it to a cheaper model.
  4. 4The estimate only needs to be close enough to stop a runaway task before it spends more than the work is worth.

Why an estimate beats a bigger context window

Agents have no native sense of task scope before they start. A request that reads as simple in plain language can need a dozen tool calls and several planning cycles, while a complex-sounding request can resolve in a single lookup. Without a pre-execution estimate, the agent commits resources blindly: turn history accumulates, planning overhead dominates, and by the time the system notices, the early decisions that caused the overspend are already made. That asymmetry is documented in practice notes on agentic task complexity, where production coding agents solving software engineering tasks can cost a few dollars per task when unconstrained in this complexity-estimation writeup.

The failure is not only financial. Two distinct failure modes appear as tasks stretch out: mechanical context degradation and semantic goal drift, and each needs a different mitigation as surveyed here. An estimate taken before the first token addresses both, because it decides up front whether the work belongs in one pass at all.

The cost of estimating is tiny compared with the cost of a wrong plan. You are not building a billing system. You are answering one question: does this task fit the budget I would pay for it?

The four counts, and what each one actually measures

Every task exposes four countable facts. You can read them off the ticket, the spec, or the repository before any model runs.

CountWhat you measureFeedsTypical multiplier
Input filesNumber of files the agent must open and readInput tokensFile tokens × 1.3 (annotation overhead)
Test casesNumber of acceptance tests or checks it must satisfyInput and output tokensPer-test round-trip tokens × 1.2
Decision pointsBranches where the agent chooses a pathInput tokens per branchRoughly one planning turn per decision
Required output lengthExpected length of the deliverableOutput tokensWords × 1.33

The word-to-token conversion is the anchor. OpenAI's own guidance states that 1 token is approximately 4 characters, roughly three-quarters of a word, and about 100 tokens map to 75 words per the OpenAI help center. Technical prose and source code push the ratio higher: a usage survey puts standard prose at about 1.33 tokens per word but source code at 1.5 to 2.0 tokens per word in this token usage reference. Record the multiplier you use, because a code-heavy task sized with the prose multiplier will under-estimate.

Two cautions. First, a plain-text token count does not include everything in an API request: message structure, tool schemas, images, and files all add tokens per OpenAI. Second, a request-level token count does not predict how many tokens the model will generate. Input and output must be estimated separately.

Worked example: sizing a refactor before you send it

Imagine you want an agent to refactor a payment module. You count: 12 source files averaging 250 lines each, 14 existing unit tests plus 4 new acceptance tests, 6 decision points (keep or replace the retry logic, which of two interfaces to use, and so on), and a deliverable of a summary plus a patch, which you expect to run 1,200 words.

Input files. Twelve files at 250 lines, roughly 15 words per line, gives 45,000 words. At 1.5 tokens per word for code, that is 67,500 tokens. Apply a 1.3 overhead factor for annotations, tool schemas, and the system prompt, and you get about 87,750 input tokens.

Test cases. Each test run cycle costs a pass over the test files plus the agent's reasoning about the result. Using the browser-agent maintainer's early measurement of roughly 6,500 input tokens and 500 output tokens per test from this discussion, 18 tests at that scale gives about 117,000 input and 9,000 output tokens. That number is for one agent's tests; treat it as an order of magnitude and record your own.

Decision points. Each branch costs a planning turn of roughly 1,000 tokens, so 6 decisions add about 6,000 tokens.

Output. A 1,200-word deliverable at 1.33 tokens per word is about 1,600 output tokens, plus the patch itself, which you size separately from lines changed.

ComponentInput tokensOutput tokens
Files87,7500
Tests117,0009,000
Decisions6,0000
Deliverable01,600
Subtotal210,75010,600

A budget multiplier catches retries and the system prompt again. The usage guidance suggests 1.7 to 2.0 times for retries and overhead per the token usage reference. Apply 1.7 to the subtotal and the working ceiling is roughly 358,000 input tokens and 18,000 output tokens. Set the task ceiling at 360,000 input and 20,000 output. If the task crosses either line, stop it and act.

Turning the estimate into a decision rule

The number is only useful if it triggers an action. Sort the estimate into three bands, and decide before you send.

Under the ceiling, single pass. Send the task to a strong model. Add the ceiling to the request so the agent can self-check.

Moderately over, split. This is where agile story-splitting patterns earn their place with agents. Split vertically across behavior, not horizontally across technical layers, so each slice still delivers something usable per the Humanizing Work guide. A vertical slice contains a bit of every layer and works on its own, which also keeps each sub-task's context small per Visual Paradigm's comparison.

Far over, route. A task that needs hours of sustained execution is the wrong shape for a single strong-model call. A tiered routing scheme puts simple lookups in a direct call, complex reasoning in an orchestrator-worker setup with limited reflection, and deep multi-domain work in full multi-agent orchestration per this routing breakdown. The routing decision should itself be cheap: a classifier on task metadata runs at a fraction of the inference it prevents.

A worked decision: if the ceiling is 360,000 tokens and a new task estimates at 420,000, split it into two slices at about 210,000 each. If it estimates at 1,200,000, route it to a hierarchical decomposition where a planner assigns subtasks and each node gets its own ceiling as described in agent-planning guides.

Give the agent the count and the budget in its instructions

The ceiling only works if the agent knows about it. Spec-driven approaches make this natural: ask the agent to read requirements and write a plan to a file before any code changes, then break the plan into a tracked task list. Writing the plan to disk creates a checkpoint you can review before spend begins per the JetBrains Junie guide.

A practical prompt envelope looks like this:

Budget: 360,000 input tokens, 20,000 output tokens.
Plan first. Read requirements.md and write plan.md before touching code.
Split the plan into tasks.md, one line per task.
If you expect to exceed the budget, stop and report which task broke it.
Do not retry a failed step more than twice.

The last two lines matter more than they look. Agents need stop conditions and execution budgets so that "keep working until done" does not become an unbounded loop, and completion should be verified against observable criteria rather than the agent saying it is done per this agent planning guide.

Where the estimate goes wrong

Three corrections keep the numbers honest.

Context is not linear in turns. Because accumulated history is re-sent on each turn, cost grows faster than task length. The complexity writeup notes that context doubles with each turn due to accumulated history, and all tested frontier models degrade monotonically with context length. Plan for this by capping turns, not just tokens.

Compression has a fidelity trade-off. A learned context manager for frozen agents found that stronger agents benefit from higher-fidelity preservation while weaker agents need more aggressive compression to stay reliable per this AdaCoM paper. If you compress context to fit a ceiling, the model's baseline quality decides how much you can compress before accuracy drops.

Folding beats carrying. Context Folding lets an agent branch into a subtask and fold the result back as a concise summary, matching baseline performance with an active context up to 10 times smaller on long-horizon tasks per this ICML poster. A task that estimates over the ceiling and is split into folded subtasks can be cheaper than the original single pass.

When you are measuring real usage, read the usage field on each response. Chat Completions reports prompt, completion, and total tokens; the Responses API reports input, output, and total per OpenAI. Log those numbers against your estimate and adjust the multipliers monthly. If you would rather route across many models without wiring a separate client for each, Quanta Inference puts text, image, video, audio, and embedding models behind one OpenAI-compatible key.

FAQ

FAQ

How accurate does the estimate need to be?

Accurate enough to change a decision, not to predict a bill. If your estimate is within 20 to 30 percent of actual usage, the ceiling still stops runaway tasks and routes oversized ones correctly. Refine multipliers from logged usage rather than trying to get them right on day one.

Which count matters most?

Usually the input files, because they dominate the input side for code work. For research or analysis tasks, the decision points and output length dominate, because each branch costs a planning turn and long deliverables cost output tokens. Measure your own tasks before assuming which one leads.

Should I estimate in tokens or dollars?

Estimate in tokens first, then convert. Token counts are stable across providers, while dollar rates differ per model and per token category (input, cached input, output) per OpenAI's pricing guidance. Converting at the end lets you compare models without redoing the count.

What do I do when a task exceeds its ceiling mid-run?

Stop it and keep the partial result. Task decomposition makes this cheap: when an agent fails on subtask three, you know where it broke and can rerun that step without replaying the whole workflow per this decomposition guide. Then decide whether to split the remaining work or route it to a cheaper model.

Can I just use a bigger context window instead?

No, for two reasons. Accuracy degrades well before the nominal limit is reached, and cost grows faster than the window because history is re-sent each turn per the complexity writeup. Estimating and splitting work remains cheaper than feeding a longer context to a slower, less reliable run.

Sources

Sources

  1. Agentic Task Complexity Estimation: Budget Tokens Before ...
  2. Long-Horizon Planning and Goal Decomposition in AI Agents
  3. Understanding and counting tokens | OpenAI Help Center
  4. Token Usage Guide 2026: How Many Tokens AI Really Uses
  5. How many tokens does average test consume? #20
  6. The Humanizing Work Guide to Splitting User Stories
  7. User Story Splitting - Vertical Slice vs Horizontal Slice - Visual Paradigm
  8. AI Agent Planning: Task Decomposition, Execution & ...
  9. How to Use a Spec-Driven Approach for Coding with AI
  10. Learning Agent-Compatible Context Management for Long-Horizon Tasks
  11. Scaling Long-Horizon Agent via Context Folding - ICML 2026
  12. Task Decomposition for AI Agents: How to Break Down ...
About the author

About the author

Antonio Evans
Antonio Evans

Antonio Evans is the founder of Quanta Intelligence and a fractional CTO who builds HIPAA-ready AI systems for health and life-science companies. Before that he was technical co-founder of FriendsEAT for twenty years, CEO of Socialdraft, and a data engineer at IBM. Antonio lives with his dog Santino in Lisbon, Portugal.

All articles