Once an agent works, the next questions are how much it costs and how long users wait. Agent runs can involve dozens of model calls, each re-sending a growing context, so cost and latency grow quickly with task length. Optimising them without hurting quality needs the same discipline as everything else in this track: measure, change one thing, and compare on the benchmark. This lesson covers the right unit of measurement, where tokens and time actually go, and the main levers: fewer steps, smaller contexts, caching, model routing, parallelism, streaming and batch processing.
- Measure cost and latency per successful task, not per call
- Profile where tokens and time are spent in agent runs
- Reduce steps and context with better tools and context policy
- Use caching, routing, parallelism and batching appropriately
- Choose configurations on the quality-cost frontier
The right unit: cost per successful task
Cost per call or per token is misleading for agents. A cheaper model that needs twice as many steps, or fails more often and gets retried, can cost more per completed task. Measure cost per successful task (total spend on a benchmark divided by tasks solved) and time to completion, alongside success rate. A change is only an optimisation if quality holds.
def summarise(runs: list[dict], price_in: float, price_out: float) -> dict:
"""price_* = your provider's price per token for input and output."""
cost = sum(r["input_tokens"] * price_in + r["output_tokens"] * price_out for r in runs)
solved = sum(r["passed"] for r in runs)
secs = sorted(r["seconds"] for r in runs)
return {
"success": solved / len(runs),
"cost_per_success": cost / solved if solved else float("inf"),
"p50_seconds": secs[len(secs) // 2],
"p90_seconds": secs[int(len(secs) * 0.9)],
}Where the tokens go
In a loop, each model call re-sends the whole context. If the context grows by a few thousand tokens per step, total input tokens grow roughly with the square of the number of steps, so long runs are disproportionately expensive. Profile real traces: input versus output tokens, tokens per step over a run, and which layer (system prompt, tools, history, results) dominates. Usually input tokens from accumulated history and tool results dominate, which points at the biggest levers: fewer steps and smaller contexts.
- Fewer steps: task-level tools, better error messages, clearer instructions, and parallel independent calls in one step.
- Smaller contexts: bounded tool results, compaction, just-in-time retrieval, clearing stale tool outputs.
- Shorter outputs: ask for concise reasoning and structured outputs where free text is not needed.
Caching, routing and batching
After reducing how many tokens a run needs, reduce what each token costs. These levers are powerful but each has a failure mode, so evaluate them on the benchmark like any other change and count every attempt, including escalations and retries, in the cost.
| Lever | How | Watch out for |
|---|---|---|
| Prompt caching | Stable prefix first so providers can reuse it | Anything dynamic near the top breaks it |
| Model routing | Smaller model for simple steps or tasks, larger for hard ones | Routing errors; measure end to end |
| Sub-agents on smaller models | Search and summarise with a cheaper model | Quality of returned summaries |
| Batch processing | Asynchronous batch endpoints for evals and offline jobs | Not for interactive use; slower turnaround |
| Result caching | Reuse tool results and outputs for identical inputs | Stale data; key on everything that matters |
def route(task: dict) -> str:
"""Pick a model tier from cheap task features; escalate on failure."""
hard = task["files_touched_estimate"] > 3 or task["type"] in {"debug", "design"}
return "large" if hard else "small"
def run_with_escalation(task):
tier = route(task)
result = run_task(task, model_tier=tier)
if not result.passed and tier == "small":
result = run_task(task, model_tier="large") # count both runs in the cost
return resultRouting deserves particular care. A router that sends a hard task to a small model wastes the small model's attempt and then pays for the large one anyway, so a bad router can cost more than always using the large model. Start with simple, explainable rules based on task features, measure the escalation rate, and only consider a learned router once you have enough labelled runs to train and evaluate it.
Latency
Latency in agents comes mostly from the number of sequential model calls and slow tools, not from any single call. Users also judge speed by how soon they see something useful, so visible progress matters as much as total time.
- Stream model output and progress (current step, task list) so users see work immediately; perceived latency matters as much as total time.
- Parallelise independent tool calls and sub-agents.
- Prefer fast tools: an indexed code search beats scanning files; a precomputed summary beats reading a long document every time.
- Cut wasted steps: loops, re-reading the same file, and retries caused by vague errors.
- Set time budgets and return partial results rather than making users wait indefinitely.
Choosing on the frontier
Plot each configuration's success rate against its cost per success (or latency). Configurations that are worse on both axes than another are dominated and can be discarded; the rest form a frontier of sensible trade-offs. The product decides where to sit on it: an interactive assistant may favour latency, a nightly batch job cost, and a high-stakes workflow quality. Re-run the comparison whenever models or prices change, because the frontier moves.