API Prices Dropped, So Why Did Agent Per-Task Costs Rise?
A new flagship model launched on the API platform with token prices cut by roughly one-third over the previous generation. Yet a third-party re-test showed average per-task cost rising from $2.45 to $2.81, up about 15%. This article explains why: unit price is only the denominator of the real equation, while input token consumption can balloon to roughly 1.7x in long agentic chains. You will learn how API billing actually works, why input tokens nearly double in multi-step agent loops, and how to evaluate models on cost per successful task rather than price per token. It closes with six practical cost-governance levers—context compression, cache-friendly prefixes, tiered routing, output control, budget circuit breakers, and cloud-side elasticity—so you can capture a new model's capability gains without letting the bill eat the savings.
1. Prices Dropped — So Why Did the Bill Go Up?
A new generation of flagship models recently launched on the API platform. Official pricing shows the API token price was cut by roughly one-third compared with the previous generation. Conventional logic says a lower unit price should mean lower cost, yet a recent public re-test by a third-party evaluation organization showed that average per-task cost in its cyber-defense benchmark rose from $2.45 to $2.81, an increase of about 15%. The organization’s name, measurement window, and methodology should be taken from its public disclosures.
The direct cause is not complicated: input token consumption rose to about 1.7x the previous generation—nearly double—canceling out and even outweighing the savings from the price cut.
Per-task cost is fundamentally a multiplication problem:
Per-task cost = Total tokens consumed per task × Applicable unit price
The unit price is set by the model provider, but how many tokens a task actually consumes is determined jointly by the caller’s task design, how context is organized, the agent call chain, and the caching strategy. Many teams fixate on the price list when choosing a model, while overlooking that the numerator is expanding rapidly.
So to judge whether a new model is genuinely cheaper, you cannot look only at “how much per million tokens.” You have to look at “how much it costs to complete the same task.”
2. Billing Structure: What Are You Actually Paying For?
2.1 The Base Unit and Price Components
Large-model APIs typically use the token as the smallest billing unit. For English text, tokens map fairly closely to sub-word pieces rather than whole words; the exact ratio depends on the tokenizer in use. Price is usually composed of three parts:
- Input tokens: everything sent to the model—prompts, system instructions, tool definitions, conversation history, retrieved snippets, and so on.
- Output tokens: everything the model generates, including the response body, tool-call arguments, and, for reasoning models, the internal chain of thought.
- Cache discount: repeated prefix content such as system prompts, tool definitions, and fixed examples. When a context cache is hit, this content is usually billed at a price significantly below the standard input rate.
Across mainstream pricing schemes, the output rate is generally higher than the input rate, often by several times. So in short tasks, “making the model write less” directly lowers the bill. But in long agentic chains, what truly amplifies cost is context that gets fed in again and again.
2.2 Four Variables That Drive Real Cost
- Context length: Long-context capability is now standard on flagship models, but “how much it can read” and “how much it reads every time“ are two different things. The longer the context, the larger the input consumption per call.
- Cache hit rate: Whether the prefix is stable byte-for-byte and whether it sits at the front of the message sequence directly determine how much discount you actually get.
- Call-chain length: Completing a single goal in an agent usually means cycling through “plan → tool call → observe result → replan” over multiple rounds. Each round is an independent request and typically requires feeding the full context again.
- Tier selection: A single model family often offers both a flagship version and a lightweight high-speed version. The former excels at long-chain planning and complex reasoning; the latter offers high throughput, low latency, and a lower unit price, suited to light tasks such as classification, extraction, and formatting.
In billing terms, this can be formalized as:
Cost per request = (Cached input tokens × Hit rate + Uncached input tokens × Miss rate + Output tokens × Output rate) / 1,000,000
2.3 How Does a Single Call Burn Through Tens of Thousands of Tokens?
Many developers have had this experience: a request runs for only a few seconds, yet the bill jumps by tens of thousands of tokens. This usually is not the model “burning money” but an illusion created by how usage is metered: the bill counts the sum of input and output tokens, a substantial portion of which is repeated input of prior context.
| Component | Tokens | Notes |
|---|---|---|
| System prompt | 1,500 | Role definition, output spec, safety constraints |
| Tool definitions | 4,500 | Parameter descriptions for 10 tools, ~450 tokens each |
| Conversation history | 12,000 | Includes the full previous reply and several retrieved results |
| Current user message | 2,000 | Includes a pasted log snippet |
| Chain of thought (output) | 8,000 | Step-by-step analysis from a reasoning model |
| Final reply (output) | 2,000 | The solution and change recommendations |
Summed up, that is 20,000 input tokens and 10,000 output tokens, 30,000 tokens in total. If the history also contains large blocks of code or logs, a total above 40,000 is very common. If a model can output dozens or even hundreds of tokens per second, completing generation within a few seconds is unsurprising—yet the bill records tens of thousands of tokens.
| Token type | Pricing characteristic | Effect on the bill |
|---|---|---|
| Uncached input | Usually close to the standard input rate | The main cost source from repeated reads in long agent chains |
| Cached input | Usually well below the miss rate | A stable prefix can significantly lower per-call cost |
| Output | Usually higher than the input rate | Chain of thought, body text, and tool arguments all count |
One point deserves special caution: the chain of thought produced by reasoning models is usually billed as output too. The longer the chain and the more thorough the reasoning, the more output tokens appear on the bill.
The code below captures this structure so you can compare tiers side by side:
from dataclasses import dataclass@dataclass(frozen=True)class PriceTier:"""CNY / 1M tokens. Sample pricing; refer to the provider's latest price list for actual rates."""name: strin_hit: float # Input (cache hit)in_miss: float # Input (cache miss)out: float # Output (includes chain of thought)currency: str = "CNY"price_note: str = ("Sample pricing, not a live quote; a cache hit typically requires ""the cached content to sit at the front of the message sequence and match byte for byte.")# Structural illustration only: rough magnitude relationship between the# flagship and lightweight high-speed tiers within the same family.TIERS = {"flagship": PriceTier("Flagship", 13.0, 13.0, 68.0),"speed": PriceTier("Speed", 1.0, 1.0, 12.0),}def task_cost(tier: PriceTier, in_hit: int, in_miss: int,out_tokens: int) -> float:"""Cost of a single call, in the same currency as PriceTier."""return (in_hit * tier.in_hit+ in_miss * tier.in_miss+ out_tokens * tier.out) / 1_000_000def effective_cost(tier: PriceTier, in_hit: int, in_miss: int,out_tokens: int, success_rate: float) -> float:"""Actual cost per successful task: lower is better at equal success rates."""return task_cost(tier, in_hit, in_miss, out_tokens) / max(success_rate, 1e-6)if __name__ == "__main__":for name, tier in TIERS.items():print(name,"cost per task: %.4f" % task_cost(tier, 6000, 6000, 5000),"cost per successful task: %.4f" % effective_cost(tier, 6000, 6000, 5000, 0.9))
3. Root-Cause Analysis: Why Do Input Tokens Nearly Double?
3.1 Long Agent Chains: Quadratic Growth from Repeated Reads
When agents tackle complex tasks, they usually follow a loop structure:
while not task_done and step < max_steps:request = build_context(system, tools, history, task)reply = llm(request)history += [reply, tool_result(execute(reply))]step += 1
In a stateless API model, every round must resend all the context accumulated so far. Suppose each round adds k tokens and there are n rounds in total; the cumulative input is roughly:
k × (1 + 2 + ... + n) = k × n(n+1)/2
In other words, input consumption grows quadratically with the number of rounds, and linearly growing tool results get read over and over inside the context. Once the number of steps climbs, the bill inevitably rises. This is often the primary source of the near-doubling of input tokens.
3.2 The Feedback Loop Between Capability Gains and Context Bloat
Capability gains change the shape of token consumption. The data below is drawn from the model provider’s public materials or technical notes; the specific evaluation version, date, and methodology should be taken from the provider’s or evaluator’s disclosures. This article does not use rankings that lack a cited source.
| Capability dimension | Previous generation | New generation | Change |
|---|---|---|---|
| Cyber-defense benchmark score | 41% | 64% | +23 percentage points |
| Composite intelligence index | 44 | 55 | +11 points |
| Terminal coding task pass rate | 13% | 67% | Marked improvement |
| Official 3D modeling benchmark score | — | 92.7% | Provider benchmark |
These gains directly push up token consumption:
- Longer chains of thought: Reinforcement learning rewards a “explore first, then act, then verify” behavior pattern, which raises output tokens.
- Longer execution chains: The model is more willing to proactively call tools, read files, run commands, and check results. This improves task completion but also makes the history context longer and longer.
- Context self-inflation: The more interventions, the more observation results are produced; and a model’s ability to locate key information in a long context can degrade as length grows. Once it misses a clue, it may re-read or re-explore, forming a positive feedback loop of “the longer the context, the worse the results, the more the calls.”
So even though the new model has a lower unit price, per-task cost can be higher: the model spends more tokens to buy stronger capability, and the caller pays for those tokens.
3.3 Safety Alignment: A Hidden Line Item on the Cost Ledger
Before releasing open weights, the new generation of models proactively removed some high-risk training data to reduce the potential for post-release misuse. Official internal testing showed that a control version without this risk reduction achieved a higher success rate on specific attack tests, and that the rate declined in the final version.
This is a responsible trade-off. From an engineering perspective, it also reminds us that model capability is the result of a three-way balance among capability, safety, and cost. For enterprises with high security and compliance requirements, auditable and explainable behavioral constraints are themselves a form of value that must be entered into the total ledger.
3.4 Cache Misses: The Most Overlooked Amplifier
The advantage of the cache hit rate is realized only when a cache actually hits. In practice, the following situations often prevent a prefix that could have hit from being reused:
- A frequently changing timestamp is embedded in the system prompt;
- The tool list comes from iterating over a set, so the call order differs each time;
- Retrieved results are concatenated to the very front of the prompt, ahead of the stable prefix.
Caching mechanisms generally require the cached content to sit at the front of the request and to match byte for byte; any tiny change invalidates the entire prefix, and the call jumps from the “hit rate” back to the “miss rate.”
3.5 A Concrete Calculation: Why Can Costs Still Rise After a Price Cut?
Back to the opening case. The old cost was $2.45, and the new unit price is about one-third lower than the previous generation—that is, the new unit price is about 2/3 of the old one.
If token consumption stayed the same:
New cost = 2.45 × 2/3 ≈ $1.63
But the actual cost was $2.81, which means token consumption has already risen. Let the token consumption multiplier be m; then:
2.81 = 2.45 × 2/3 × mm ≈ 2.81 / (2.45 × 2/3) ≈ 1.72
In other words, actual token consumption is about 1.72x the previous generation. If later context optimization can hold the increase to within 1.5x:
2.45 × 2/3 × 1.5 ≈ $2.45
The cost only just breaks even with the previous generation and does not truly fall. This shows that in agent scenarios, context efficiency has become, alongside the model’s own capability, a core variable that determines the bill.
4. Evaluation Methodology: From “Looking at Price” to “Capability Per Dollar”
4.1 Joint Evaluation of Per-Task Cost and Success Rate
| Tier | Task success rate | Avg tokens/task | Output share | Cost index per task | Cost index per successful task |
|---|---|---|---|---|---|
| A: Flagship | 94% | 180,000 | 10% | 4.50 | 4.79 |
| B: Flagship + context optimization | 94% | 95,000 | 10% | 2.69 | 2.86 |
| C: Lightweight high-speed | 78% | 55,000 | 12% | 0.55 | 0.71 |
The values are illustrative; output share refers to the proportion of output tokens in the total token count.
- Tier A is the most capable, but massive repeated reads saddle it with a high cost;
- Tier B keeps the same capability yet cuts cost to about 60% of the original through context compression and cache optimization alone;
- Tier C has the lowest completion rate, but on simple tasks its “cost per successful task” is actually the lowest.
The conclusion is straightforward: the simpler the task, the more it should be handed to a cheaper model; the more long-chain and high-risk the stage, the more it is worth paying for a stronger model. The key is matching tasks to capabilities correctly.
4.2 Tiered Routing: Matching Each Task to the Right Tier
from enum import Enumclass Tier(Enum):SPEED = "Speed"BALANCED = "Balanced"FLAGSHIP = "Flagship"def route(task: dict) -> Tier:"""Rule-based routing on task features; tune continuously against production data."""score = 0score += min(task.get("steps", 1), 10) * 0.5score += 2 if task.get("needs_terminal") else 0score += 2 if task.get("multi_file_refactor") else 0score += 1 if task.get("security_sensitive") else 0score += 1 if task.get("input_tokens", 0) > 32_000 else 0if score >= 5:return Tier.FLAGSHIPif score >= 2:return Tier.BALANCEDreturn Tier.SPEEDdef route_with_retry(task: dict, max_retry: int = 2):"""Failure escalation example: after repeated failures on the speed tier,automatically upgrade to a higher tier."""tier = route(task)for _ in range(max_retry + 1):result = call_model(task, tier)if result.success:return resultif tier == Tier.SPEED:tier = Tier.BALANCEDelif tier == Tier.BALANCED:tier = Tier.FLAGSHIPreturn result
A more mature approach is to train a lightweight classifier on production logs that predicts each tier’s success rate on similar tasks from historical data, then combines that with price to automatically pick the tier with the lowest “cost per successful task.” Whichever approach you use, follow two principles:
- Rules first: The routing logic must be explainable and able to fall back.
- Failure escalation: After repeated failures on the lightweight tier, automatically escalate to a higher tier and retry.
5. Cost Governance in Practice: Six Actionable Levers
5.1 How to Compress Agent Context
The core of context compression is trimming the coefficient k and the number of rounds n in the quadratic term.
- Sliding window + rolling summary: Keep the most recent few rounds of raw messages and compress earlier history into a structured summary. A task summary records only the goal, completed steps, key conclusions, and to-dos.
- Externalize tool results: Store file contents, command outputs, and retrieved results outside the context—such as in a cache service or object storage—and keep only a summary and reference ID in the context, reading on demand when needed.
- Task timeout circuit breaker: Cap the maximum rounds and maximum token budget per task to prevent endless exploratory loops.
import hashlibfrom dataclasses import dataclass, field@dataclassclass Turn:role: str # "user" / "assistant" / "tool"content: str@dataclassclass RollingSummary:goal: str = ""done: list = field(default_factory=list)pending: list = field(default_factory=list)def compact_history(turns: list[Turn], keep_recent: int = 4,summary: RollingSummary | None = None) -> list[dict]:"""Keep the most recent keep_recent turns as raw messages;compress earlier content into a summary."""summary = summary or RollingSummary(goal=turns[0].content[:120])older, recent = turns[:-keep_recent], turns[-keep_recent:]for t in older:if t.role == "assistant" and "task done" in t.content:summary.done.append(t.content[:80])messages = [{"role": "system","content": "[History Summary] Goal: %s; Done: %s; Pending: %s" % (summary.goal, summary.done[-5:], summary.pending),}]messages += [{"role": t.role, "content": t.content} for t in recent]return messages# Execution-bound example: the caller must set max rounds and a token budget outside the loop.MAX_STEPS = 12MAX_TOKENS = 400_000def should_continue(step: int, used_tokens: int, next_need: int,max_steps: int = MAX_STEPS,max_tokens: int = MAX_TOKENS) -> bool:return step < max_steps and used_tokens + next_need <= max_tokens
5.2 Why Do Cache Misses Happen, and How Do You Make Your Prefix Cache-Friendly?
The key to being cache-friendly is placing the reusable prefix at the very front and guaranteeing byte-for-byte consistency.
- Organize “system prompt → tool definitions → fixed examples → knowledge background” into a stable prefix;
- Move volatile content such as timestamps, user IDs, and random numbers to the end of the message sequence;
- Sort tool definitions, manage prompts with semantic versioning, and actively pre-warm after changes.
import jsonimport hashlibdef stable_prefix_messages(system_prompt: str, tools: list[dict],examples: list[dict], dynamic_ctx: str) -> list[dict]:tools_sorted = sorted(tools, key=lambda t: t["name"])prefix = (system_prompt+ "\n\n<tools>\n"+ json.dumps(tools_sorted, ensure_ascii=False, sort_keys=True)+ "\n</tools>\n\n"+ "".join(json.dumps(e, ensure_ascii=False, sort_keys=True) for e in examples))prefix_hash = hashlib.sha256(prefix.encode()).hexdigest()[:12]return [{"role": "system", "content": prefix},{"role": "system", "content": dynamic_ctx},{"role": "assistant", "content": f"[prefix:{prefix_hash}] Context ready, please process the user request."},]
If the system prompt must contain a timestamp, place it afterward or split it into a separate dynamic segment so it does not break the prefix cache.
5.3 How to Do Context Engineering Well
Long context is not about “cramming everything in.” More robust practices include:
- Load on demand: First list files or directories, then read as needed, rather than injecting everything at once;
- External memory: Write notes, decision records, and intermediate artifacts to external files and maintain them continuously, so the model can retrieve them when needed;
- Sub-agent isolation: Hand information-heavy but conclusion-light work such as retrieval and research to subtasks, and return only the conclusions to the main context.
All three essentially compress n and k in the quadratic input.
5.4 How to Control the Most Expensive Output Tokens
- Define tool parameters with “field name + enum + brief description” to avoid verbose descriptions and repeated content;
- Ask the model to return structured results directly, such as JSON, to reduce pleasantries and explanatory text;
- Explicitly constrain the maximum output length, and write lengthy execution logs and process records to files rather than the reply body.
5.5 Setting Budget Circuit Breakers and Failure Escalation
class BudgetGuard:"""Per-session token budget circuit breaker; instantiate per user/tenant."""def __init__(self, cap: int = 400_000, hard_cap: int = 500_000,degrade_tier: str = "Speed"):self.cap = capself.hard_cap = hard_capself.used = 0self.degrade_tier = degrade_tierdef allow(self, need: int) -> bool:return self.used + need <= self.capdef should_degrade(self) -> bool:return self.used >= self.cap * 0.8def should_stop(self) -> bool:return self.used >= self.hard_capdef next_tier(self, tier: str) -> str:return self.degrade_tier if tier != self.degrade_tier else tierdef commit(self, used: int) -> None:self.used += used
It is advisable to set three types of trigger conditions:
- Budget reaches 80%: Automatically switch to the lightweight high-speed tier, or compress the history context;
- Consecutive failures reach a threshold: For example, after 2 consecutive tool-call failures, escalate to a higher tier and retry;
- Hard limit reached: Stop the task immediately, return a notice, and request human intervention.
At the same time, it is recommended to set quotas and rate limits per API key at the gateway layer, and to attribute token consumption layer by layer across “business line — application — session.” In production, you can integrate logging services and monitoring alerts, and set threshold warnings for metrics such as cache hit rate, average tokens per task, and cost per successful task.
5.6 Aligning Elasticity and Cost with Cloud Resources
When traffic peaks, tight GPU capacity often causes queuing and timeouts, and repeated retries further drive up token consumption. You can optimize resource-side cost with general cloud-native approaches:
- Use a container platform for elastic scaling to avoid resource shortfalls during peaks;
- Use a message queue to smooth out asynchronous tasks and shave peaks, lowering synchronous request peaks;
- Build observable metrics for the timeout, retry, and degradation paths.
It is recommended to focus on monitoring the following metrics:
| Metric | Description |
|---|---|
| Queue timeout rate | Reflects whether resource shortfalls cause task failures or retries |
| Retry count | Retries directly amplify token consumption |
| Token increment from retries | Measures the extra cost from ineffective calls |
| Average cost per task | Reflects whether the elasticity strategy truly reduces cost |
| P95 latency | Avoids sacrificing user experience for cost reduction |
6. Selection Checklist: Do the Math Before You Ship
- Build a private evaluation set: Pick 100–300 use cases close to real business, covering simple Q&A, multi-step tool calls, long-document processing, and other scenarios.
- Measure quality and cost jointly: Record task success rate, average tokens per task, cache hit rate, and cost per successful task at the same time, rather than comparing only leaderboard scores and unit prices.
- Tier by task: Use the flagship for high-value, high-risk, long-chain stages; use the lightweight high-speed version for high-concurrency, low-complexity stages.
- Optimize context first, then consider switching models: In many scenarios, the savings from context compression and cache optimization are no less than those from switching models.
- Design a degradation path: Be able to switch at any time among the flagship, balanced, and lightweight tiers, avoiding the uncertainty of relying on a single model or service.
- Continuously re-check prices and quotas: Keep an eye on changes to pricing adjustments, free tiers, and resource quota policies, and periodically recalculate the total ledger.
Before shipping, it is advisable to check at least the following five metrics:
| Check item | What to focus on |
|---|---|
| Task success rate | Whether it meets the business minimum |
| Average tokens per task | Whether it has clearly ballooned due to long agent chains |
| Cache hit rate | Whether the stable prefix actually hits |
| Cost per successful task | Whether it is lower than the previous approach |
| Circuit-breaker thresholds | Whether there are boundaries for budget, rounds, and failure escalation |
7. Conclusion: As Capabilities Leap Forward, Cost Governance Must Evolve Too
The conclusion up front: in agent scenarios, optimizing context first and only then discussing model upgrades is usually more cost-effective than simply switching to a cheaper, stronger large model. When measuring the effect of cost reduction, do not look only at token unit price; look at least at two metrics: cache hit rate and cost per successful task.
A new generation of flagship models brings stronger capability at a lower unit price, but “unit price” has never equaled “cost.” In long agent chains, context is read repeatedly, chains of thought keep lengthening, and tool results keep accumulating; input tokens can rise to about 1.7x—enough to swallow all the savings from the price cut.
For developers, the mindset to build is this: context efficiency matters just as much as model capability. Only by making the prefix stable, the history lean, the results external, the budget circuit-broken, and the tiers layered can you fully unleash the capability dividend of the new generation of models while keeping them affordable.
