Where the Cost of a Model Call Comes From, and Where It Can Go Wrong

Token, Context, Prefill, Decode, and caching determine an Agent’s cost and latency; hallucination and Prompt Injection determine the floor of its risk. Without understanding these, none of the later architectural trade-offs has a basis.

On this page · 10 sections

I have seen plenty of Agent projects look seriously at the bill for the first time a month after launch, only to discover that a feature that “answers in a few sentences” burns tens of thousands of Tokens (that is, the text units a model processes and bills by) per call. The problem is not that the model is expensive. It is that nobody in the design phase treated the model as a compute resource with a cost, a latency, and failure modes.

Backend engineers know their databases: how an index affects a query, how a connection pool affects throughput. An LLM deserves the same level of understanding. You do not need to know how to train one, but you must know what happens inside a single call.

The Short Version

  • An Agent’s cost accumulates over the entire call trajectory, not over the final sentence of the answer; output Tokens are the most expensive and cached input is the cheapest.
  • The order of the Context is a cost decision: stable content first and changing content last is what lets the Prefix Cache hit.
  • Hallucination comes from the generation mechanism itself; it cannot be eliminated, only verified in tiers by task risk, and the system should be allowed to stop when evidence is insufficient.
  • Message roles are not a permission system: security controls belong in the Runtime, data, action, and audit layers, and tool permissions determine the real consequences of an attack.

The Cost Path of One Inference

The cost path of one Agent inference; open the full-size SVG

On the server side, one call splits roughly into two phases:

  • Prefill: the model reads all the known input in one pass. Input positions can be computed in parallel, so it is relatively fast, but the longer the input, the more work there is, and that directly affects time to first Token (TTFT).
  • Decode: the model generates output Tokens one at a time. Each new Token depends on the ones before it. This is a sequential path that cannot be parallelized, so the longer the output, the higher the total latency.

For an Agent, this path is not walked once. It is walked over and over inside a loop: every tool result is written back into the Context (that is, the full input sent to the model) and triggers another round of Prefill. An Agent’s cost accumulates over the entire call trajectory, not over the final sentence of the answer.

Three Views of Tokens Every Engineer Should Hold

The same Tokens can be read for cost, efficiency, and quality. In the table, focus on the right-hand column: how each view changes the design.

View Core fact Impact on design
Cost Output Tokens are the most expensive, uncached input comes next, cached input is the cheapest Controlling output length often pays better than compressing input; the Context Window is essentially a budget
Efficiency Input adds Prefill work; output adds Decode steps To cut latency, look at output length and reasoning effort first rather than staring only at input
Quality The share of useful information in the Context determines its purity More Tokens does not mean better results; irrelevant material dilutes the model’s attention

The third point is the easiest to overlook. Stuffing every possibly relevant document into the Context looks like “giving the model more information,” but the actual effect is often more expensive, slower, and worse. That is why I spent a whole article in the Harness series on context loading: explaining “how to load context” consumes context too.

Caching: The Order of Your Context Is Money

There are two kinds of cache in inference, and they do completely different things:

  • KV Cache reuses the computed results of earlier Tokens within a single generation, so Decode does not have to recompute the whole history at every step. The inference engine manages it, and the application layer mostly does not need to care.
  • Prefix Cache reuses identical Token prefixes across requests. This one is determined entirely by how the application layer assembles the Context.

The rule for Prefix Cache is simple: only a prefix that is exactly identical from the very beginning can hit. So the order of the Context becomes a cost decision:

  1. Stable content goes first: System rules, tool definitions, project conventions that rarely change.
  2. Changing content goes last: the current task, the latest tool results, dynamic state.
  3. Do not insert anything that changes near the front. A single timestamp at the top of the System prompt is enough to invalidate the cache for everything after it.

On-demand loading of tools and Skills has to be evaluated inside this same frame. Loading less saves Tokens, but if the combination loaded differs every time, the prefix is unstable and the cache hit rate drops instead. The two need to be monitored together with TTFT, rather than optimizing only one of them.

Reasoning: A Short Answer Can Still Be Expensive

Reasoning is the extra computation a model invests before it gives an answer or takes an action. For engineering, there are three easy traps:

  • Visible thinking is not the same as all the reasoning Tokens you are billed for. What is displayed and what is actually consumed may not match; cost has to be taken from the usage settlement.
  • Reasoning effort is a budget knob. Higher effort means higher latency and cost, and the “better result” it buys only holds on tasks that need it.
  • A short answer may have a large amount of reasoning behind it. Estimating cost from output length alone will underestimate it badly.

In practice I treat reasoning effort as part of routing: tasks like classification and extraction run at low effort, and only cross-module solution design runs at high effort, rather than setting it to maximum globally.

Where Capability Comes From Determines How Far You Can Trust It

A model’s behavior comes from several training stages, and each stage leaves a corresponding limitation:

  • Pretraining teaches the model general sequence patterns, but there is no “table of facts queryable by source” in the parameters. The model knows a great deal, yet cannot say where any single piece came from.
  • Supervised fine-tuning shapes the model’s behavior patterns, such as how to emit a tool call. But remember: the model only outputs a piece of text that means “I want to call a tool”; what actually executes the tool and manages state is the Runtime.
  • Preference optimization makes the model lean toward the answers raters chose, and along the way it also learns the surface features raters happen to favor. What it raises is the probability of “looking good.” It provides no guarantee of business correctness.

That last point explains a common phenomenon: the model’s answers keep getting more fluent and better organized, but fluency and correctness are two separate things. Business correctness has to be evaluated on its own.

Hallucination: It Cannot Be Eliminated, Only Governed by Risk

Hallucination is not a defect waiting to be fixed. It comes from the generation mechanism itself: the model is producing a high-probability continuation, parametric knowledge has no source field, and the Context may be missing, stale, or self-contradictory.

So the right question is not “how do we eliminate hallucination,” but “how much room for generation does this task allow, and how strong a verification does it need.” The table answers it by task type: the smaller the room for generation, the stronger the verification.

Task type Room for generation Verification needed
Creative work, drafts, brainstorming Large; divergence is where the value lies Human judgment is enough
Factual Q&A, analytical conclusions Small; must be grounded Verifiable sources and citations
Actions with real consequences Minimal External verification, permission gates, confirmation, and rollback

Two conclusions that are easy to miss:

  • Retrieval can only supplement information; it cannot guarantee correctness, because the material it returns may itself be out of date.
  • When evidence is insufficient, the system should be allowed to stop.

This is why I treat “refusal quality” as a core metric in my RAG system. See RAG Is an Evidence System.

Prompt Injection: Role Labels Are Not a Permission System

An Agent reads web pages, documents, tickets, and tool return values. All of that external content ends up in the same Token sequence as the user’s instructions, and the model has no hard mechanism for telling “this is data” from “this is an instruction.” Message roles (System, User, Tool) only offer a hint about provenance. They cannot perform permission checks.

So security controls have to go back into each layer of the system, rather than resting on the hope of a sterner System Prompt:

  • Model layer: the System Prompt can only lower the probability of being manipulated; it cannot be treated as a guarantee.
  • Runtime layer: identity and permission checks are enforced here, and tools run with least privilege.
  • Data layer: all external content is handled as untrusted input, with an explicit statement of where it is allowed to flow.
  • Action layer: high-risk actions require confirmation and have a rollback path.
  • Audit layer: complete call evidence is retained so that what happened can be reconstructed afterward.

When assessing injection risk, follow it all the way from Source to Sink: a piece of malicious text is not dangerous in itself; what is dangerous is that it can drive a tool with write permission. Tool permissions determine the actual consequence of an attack.

Turning These Facts into Design Constraints

After reading this article, you should at least be able to write down these constraints for your own Agent:

  • The Token budget, reasoning effort, and output length cap for each class of task.
  • The assembly order of the Context, and which content must stay stable in order to hit the cache.
  • The hallucination risk level for each class of task and the matching verification method.
  • The trust level of external content, and the range of tools it can reach.
  • The metrics to monitor: TTFT, generation time per Token, cache hit rate, and total Tokens per task.

The next article covers the first big decision made on top of these constraints: who should hold control.

Note

This article is my notes and second-pass thinking after studying material from an enterprise Agent engineering architecture course (“企业级 Agent 工程架构实战营”). The structure, wording, and diagrams are all rewritten, and the judgments are my own.

Related notes

  • 11 min readWriting

    Agent Architecture: Should the Program or the Model Decide the Next Step

    The difference between Workflow, Autonomous, and Hybrid is not the framework but who decides the next step. This article covers when each pattern fits, how each one fails, and a selection method that starts from task conditions.

  • 13 min readWriting

    LLM Runtime: Which Layer Should Own Rate Limits, Retries, and Routing

    Once the second business, the second provider, and the second tenant show up, calling the SDK directly is no longer enough. This piece covers the responsibility boundary of an LLM Runtime, multi-model routing, reliability under high concurrency, and how to choose an observability approach.

Working on something similar?

I'm always happy to compare notes on distributed systems, delivery, and applied AI.

[email protected]