Education › Evals & Harness › Stage 5: Building & improving harnesses

Optimising cost, latency and quality

Model routing, caching, parallel tool calls, shorter context and the trade-offs between them.

Advanced ~40 min read Module 19 of 20

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.

After this module you can
  • 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.

Comparing configurations by cost per success
python
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.

LeverHowWatch out for
Prompt cachingStable prefix first so providers can reuse itAnything dynamic near the top breaks it
Model routingSmaller model for simple steps or tasks, larger for hard onesRouting errors; measure end to end
Sub-agents on smaller modelsSearch and summarise with a cheaper modelQuality of returned summaries
Batch processingAsynchronous batch endpoints for evals and offline jobsNot for interactive use; slower turnaround
Result cachingReuse tool results and outputs for identical inputsStale data; key on everything that matters
A simple router with an escalation path
python
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 result

Routing 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.

Hands-on practice

Halve the cost without losing quality

  1. Run your benchmark and record success, cost per success, p50 and p90 time.
  2. Profile tokens per step and per layer from traces; find the biggest consumer.
  3. Apply one lever (bounded results, compaction or caching-friendly ordering) and re-run.
  4. Add a small-model route with escalation for easy tasks and re-run, counting both attempts.
  5. Parallelise independent read-only tool calls and measure latency change.
  6. Plot all configurations on success versus cost per success and pick one from the frontier.
Cheat sheet

Optimising cost, latency and quality — at a glance

Main things to focus on

  • Measure cost per successful task and time to completion.
  • Input tokens grow fast with steps; fewer steps and smaller contexts win.
  • Stable prefixes for caching; routing with escalation.
  • Batch endpoints for evals and offline work.
  • Stream and parallelise for latency.
  • Pick from the success versus cost frontier; re-check when things change.

Measure

cost / tasks solvedCost per success
p50 / p90 secondsTime to completion
tokens per step over the runContext growth
tokens per layerBiggest consumer

Fewer tokens

bounded tool resultsSmaller history
compactionLong runs
task-level toolsFewer steps
concise structured outputsFewer output tokens

Cheaper tokens

prompt cachingStable prefix
route small -> escalate largeModel tiers
cheaper sub-agentsSearch, summarise
batch API for evalsOffline work

Faster

stream progressPerceived latency
parallel readsWall-clock
indexed searchFast tools
time budget + partial resultBounded waits

Common pitfalls

  • Optimising price per token while cost per success rises.
  • Routing to a small model without counting escalations.
  • Dynamic content at the top of the prompt defeating caching.
  • Optimising latency by cutting verification steps.
  • Not re-running comparisons when models or prices change.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →