Cost and Latency per Step
Measure cost and latency step by step in an agent run: see why re-sent history makes later turns cost more, keep model time and tool time apart, price cached input correctly, and lower spend with caching, pruning, model tiering and parallel tool calls.
Contentsand lesson path
On this page
- Why Later Turns Cost More
- Worked Example: Auditing Cost and Latency Across a Four-Turn Run
- Four Ways to Lower the Cost of Each Step
- Practice questions
- Apply it
- Review prompt
Lessons of Agent Tracing & Debugging
- Why Agents Need Traces, Not Just Logs Concept · 15 min
- Lab: Instrumenting the Loop with Spans Lab · 25 min
- Reading a Failed Trace Worked example · 20 min
- Building a Failure Taxonomy from 20 Runs Lab · 25 min
- Cost and Latency per Step Worked example · 15 min
- Check: Find the Faulty Step Knowledge check · 6 questions
What you will learn
- Attribute tokens, cost and latency to each step and identify the slowest and most expensive steps.
01. Why Later Turns Cost More
In a single-turn chat app, cost and latency are easy to estimate: a prompt of known size, an answer of roughly known length, and the provider's per-million-token prices. Latency is roughly the time to the first token plus the time to generate the rest.
An agent loop is different. The model keeps no state between calls, so every new turn sends the whole conversation again: the system prompt, the tool definitions, the user's request, earlier model messages, tool calls and tool results, which are often long.
Each prompt is the previous prompt plus whatever the last turn added. So the prompt size grows roughly linearly with the turn number, and the total input over the session grows roughly with the square of the number of turns. A four-turn run does not use four times the tokens of turn 1; it often uses many times more. In the worked example below, the four turns send 10,700 input tokens in total, 17.8 times the 600 tokens of turn 1. If you do not measure cost per step, an agent planned to cost cents per task can end up costing dollars per task without anyone noticing.
Latency adds up in the same way. A task takes the sum of its model calls, network round trips and tool calls over every turn. If an agent needs eight turns to resolve an issue and each turn spends about three seconds in the model and its tool, the user waits around 24 seconds, and the server holds resources for the whole run.
02. Worked Example: Auditing Cost and Latency Across a Four-Turn Run
Consider a customer support agent processing an account upgrade request. The model is priced illustratively at $2.50 per million input tokens and $10.00 per million output tokens; with caching, cache reads cost $0.25 and cache writes $3.125 per million. Those are multipliers of 0.1x and 1.25x, the standard rates for a short-lived cache at Anthropic (5-minute cache) and at OpenAI for GPT-5.6 and later models (30-minute cache); several current models read cached tokens for 0.05x or less. Check your provider's pricing page for real rates. Telemetry spans capture the exact per-step metrics:
- Turn 1 (search): the model receives 600 prompt tokens (system prompt and user query), writes 40 output tokens that call
search_accounts, costs $0.0019 and takes 820 ms. The search tool runs against the customer index in 120 ms. - Turn 2 (profile): the prompt grows to 1,900 tokens because the search results (customer list and account statuses) are appended. The model writes 60 output tokens that call
get_profile, costs $0.0054 and takes 1,150 ms. The CRM lookup takes 210 ms. - Turn 3 (upgrade): the prompt grows to 3,400 tokens because the full customer profile is appended. The model writes 80 output tokens that call
apply_upgrade, costs $0.0093 and takes 1,680 ms. The billing change takes 450 ms. - Turn 4 (answer): the prompt grows to 4,800 tokens. The model writes 180 output tokens with the final confirmation, costs $0.0138 and takes 2,400 ms.
Cumulative Totals: 10,700 prompt tokens, 360 completion tokens, $0.03035 total cost, and 6.83 seconds total latency, of which 6.05 seconds are model calls and 0.78 seconds are tools. Notice that Turn 4 alone accounted for over 45% of total task expenditure, because it re-reads all the context gathered by the turns before it. The calculator below reproduces these numbers from per-step span data. It keeps model time and tool time apart, so you can see which step is slowest of each kind, and it prices cached input separately: gen_ai.usage.input_tokens includes cached tokens under the GenAI conventions, so the cached part must be subtracted before applying the full rate. Cache writes are gen_ai.usage.cache_write.input_tokens from conventions v0.1.0 on. Older instrumentation still emits the old name gen_ai.usage.cache_creation.input_tokens, and the opentelemetry-semantic-conventions 0.66b2 Python constants package still defines only the old name, so map both when you read spans.
from dataclasses import dataclass
from typing import List
@dataclass
class Rates: # dollars per million tokens (illustrative)
input: float = 2.50
output: float = 10.00
cache_read: float = 0.25 # 10% of input, Anthropic-style
cache_write: float = 3.125 # 125% of input, a short-lived cache write
@dataclass
class StepMetrics:
turn: int
input_tokens: int # gen_ai.usage.input_tokens: includes cached tokens
output_tokens: int
model_ms: float
tool_ms: float = 0.0
cache_read: int = 0 # gen_ai.usage.cache_read.input_tokens
cache_write: int = 0 # gen_ai.usage.cache_write.input_tokens
def cost(self, r: Rates) -> float:
fresh = self.input_tokens - self.cache_read - self.cache_write
dollars = (fresh * r.input + self.cache_read * r.cache_read
+ self.cache_write * r.cache_write + self.output_tokens * r.output)
return dollars / 1e6
def audit_run(steps: List[StepMetrics], rates: Rates) -> None:
total = sum(s.cost(rates) for s in steps)
for s in steps:
c = s.cost(rates)
print(f"turn {s.turn}: ${c:.5f} ({c / total:5.1%}) "
f"model {s.model_ms:>6.0f} ms tool {s.tool_ms:>4.0f} ms")
wall = sum(s.model_ms + s.tool_ms for s in steps)
priciest = max(steps, key=lambda s: s.cost(rates))
slow_model = max(steps, key=lambda s: s.model_ms)
slow_tool = max(steps, key=lambda s: s.tool_ms)
print(f"total ${total:.5f}, {wall:.0f} ms; most expensive: turn "
f"{priciest.turn}")
print(f"slowest model call: turn {slow_model.turn}; "
f"slowest tool: turn {slow_tool.turn}")Save it as step_metrics.py, save the worked example below next to it and run python3 worked_example.py (Python 3.12 or later, standard library only). The second run caches only a fixed 500-token prefix (system prompt and tool schemas), as if one cache breakpoint sat at the end of the tool schemas: turn 1 writes it and turns 2 to 4 read it. The third run uses a cache point that moves with the history instead. Claude's automatic caching (one top-level cache_control field) and OpenAI's implicit caching (the default on GPT-5.6 and later) work this way: each request puts its breakpoint at its last message, so the next turn reads the whole earlier prompt, tool results included, at the cache-read rate and pays the write rate only for the tokens added since. On Claude this works as long as the earlier content does not change and each turn adds fewer than 20 content blocks. The numbers are kept small so the arithmetic is easy to follow. In reality a 500-token prefix would not be cached at all, because providers only cache prefixes above a minimum length (512 tokens on current Claude models, 1,024 on OpenAI GPT-5.6 and later, and more on some older models).
from step_metrics import Rates, StepMetrics, audit_run
no_cache = [StepMetrics(1, 600, 40, 820, 120), StepMetrics(2, 1900, 60, 1150, 210),
StepMetrics(3, 3400, 80, 1680, 450), StepMetrics(4, 4800, 180, 2400)]
print("without caching:")
audit_run(no_cache, Rates())
total_in = sum(s.input_tokens for s in no_cache)
print(f"input over the run: {total_in:,} tokens = {total_in / 600:.1f}x turn 1")
# Same run with a cached 500-token prefix (system prompt + tool schemas):
# turn 1 writes it, turns 2-4 read it.
cached = [StepMetrics(1, 600, 40, 820, 120, cache_write=500),
StepMetrics(2, 1900, 60, 1150, 210, cache_read=500),
StepMetrics(3, 3400, 80, 1680, 450, cache_read=500),
StepMetrics(4, 4800, 180, 2400, cache_read=500)]
print("with a cached 500-token prefix:")
audit_run(cached, Rates())
# Moving cache point: each turn reads the previous prompt from the
# cache and writes the tokens added since then.
moving = [StepMetrics(1, 600, 40, 820, 120, cache_write=600),
StepMetrics(2, 1900, 60, 1150, 210, cache_read=600, cache_write=1300),
StepMetrics(3, 3400, 80, 1680, 450, cache_read=1900, cache_write=1500),
StepMetrics(4, 4800, 180, 2400, cache_read=3400, cache_write=1400)]
print("with a moving cache point:")
audit_run(moving, Rates())without caching:
turn 1: $0.00190 ( 6.3%) model 820 ms tool 120 ms
turn 2: $0.00535 (17.6%) model 1150 ms tool 210 ms
turn 3: $0.00930 (30.6%) model 1680 ms tool 450 ms
turn 4: $0.01380 (45.5%) model 2400 ms tool 0 ms
total $0.03035, 6830 ms; most expensive: turn 4
slowest model call: turn 4; slowest tool: turn 3
input over the run: 10,700 tokens = 17.8x turn 1
with a cached 500-token prefix:
turn 1: $0.00221 ( 8.1%) model 820 ms tool 120 ms
turn 2: $0.00422 (15.5%) model 1150 ms tool 210 ms
turn 3: $0.00817 (30.0%) model 1680 ms tool 450 ms
turn 4: $0.01268 (46.4%) model 2400 ms tool 0 ms
total $0.02729, 6830 ms; most expensive: turn 4
slowest model call: turn 4; slowest tool: turn 3
with a moving cache point:
turn 1: $0.00228 (11.3%) model 820 ms tool 120 ms
turn 2: $0.00481 (24.0%) model 1150 ms tool 210 ms
turn 3: $0.00596 (29.7%) model 1680 ms tool 450 ms
turn 4: $0.00702 (35.0%) model 2400 ms tool 0 ms
total $0.02007, 6830 ms; most expensive: turn 4
slowest model call: turn 4; slowest tool: turn 3Turn 4 is both the most expensive step and the slowest model call; turn 3 has the slowest tool. Caching only the fixed prefix lowers the total by about 10% and leaves turn 4 the biggest cost, because what grows is the tool output appended after that prefix, which this run does not cache. The moving cache point lowers the total by about a third ($0.02007 against $0.03035): each tool result is paid once at the write rate and then read at a tenth of the input price on later turns. Neither run changes the token count. Turn 4 still sends 4,800 tokens, so the context window fills just as fast. The durations are typed in, so they do not show the faster processing a cache hit can give. Predict: if turn 2 returned a 10,000-token dump instead, which run would it hurt most, and why? In a real trace, read these numbers from span attributes (gen_ai.usage.* on model spans, span durations on execute_tool spans) rather than typing them in.
03. Four Ways to Lower the Cost of Each Step
To control compounding costs in long-running agent workflows, teams commonly use four techniques:
-
Prompt caching. Anthropic, OpenAI and Google Gemini all offer it: when the start of a prompt is byte-identical to an earlier request, that part is billed at a reduced rate. Anthropic, and OpenAI for GPT-5.6 and later, bill a short-lived cache write at 1.25x the base input price and a read at 0.1x, with lower read rates on several current models. Let the cache point follow the history, as in the third run, instead of stopping after the fixed prefix. The saving grows on longer runs, because the re-sent history becomes a larger share of each prompt.
-
Pruning and summarising tool results. When a tool returns a large payload, such as a raw JSON database dump or a long HTML page, the runtime should drop the fields the next step does not need before it appends the result. Another option is to have a cheap model condense the result into the facts that matter.
-
Model tiering. Not every step needs the largest model. Use a smaller, cheaper model from your provider's current line-up for simple retrieval turns, and keep the strongest model for the final answer or hard decisions.
-
Parallel tool calls. When the model asks for several independent tool calls in one turn, run them at the same time, so the step takes about as long as its slowest call instead of the sum of all of them.
Combining prefix caching with observation pruning can cut agent cost substantially; measure the effect on your own traces, together with answer quality, before and after each change. At tens of thousands of requests a day, a saving of a cent per run adds up to hundreds of dollars a day, so the effort is usually worth measuring.
04. Practice questions
05. Apply it
Try these controls on an agent you run:
- Keep the system prompt, role text and tool schemas identical at the start of every prompt, and use a cache point that follows the history (Claude automatic caching or OpenAI implicit caching), so earlier turns are read from the cache.
- Do not append raw SQL results or whole HTML pages to the history; keep only the columns or fields the next step needs.
- Record input, output and cache token counts on every model span, so you can find the turn that drives a cost spike.
- Run independent tool calls in parallel, so a turn waits for its slowest call instead of the sum of all calls.
- Set a token budget per step, and stop or compress a turn when the context gets close to it.
06. Review prompt
Using the four-turn example, explain why the total input of a run grows much faster than its number of turns. Then say what prompt caching changes and what it leaves unchanged, what pruning a tool result changes, and when sending a step to a smaller model is worth the risk to answer quality.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.