Skip to content

Lesson 1 of 4 · 3 min read

Optimise an Agent in the Right Order

Free lessonReviewed By the AIAgentInterviews editorial team
Reading position
In this lesson

TL;DR: When an agent is too slow, too expensive or not good enough, the instinct is to change the model. Usually the cause is upstream. Work down a ladder, measuring each rung on the same tasks: cut steps the agent does not need, cut context it re-reads every turn, fix tools so it chooses and uses them correctly the first time, cache the stable prefix, route easy steps to a cheaper model, optimise prompts against a metric, and only then fine-tune or train with reinforcement learning, which need a stable task, a trustworthy grader and a budget to maintain a model. Each rung is cheaper to try and to undo than the one below it.

After this lesson, you should be able to diagnose where an agent's cost and latency come from, order optimisation levers by cost and risk, estimate the effect of a change before making it, and explain when weight changes are and are not justified.

Before you read

Commit to an answer now. The lesson that follows explains it, and having guessed first, even wrongly, makes the explanation easier to remember.

  1. 1A support agent averages 14 model calls and 40,000 input tokens per ticket. The team proposes fine-tuning a smaller model to cut cost. What would you look at first?

Where the cost goes

An agent's cost is roughly the sum over steps of the tokens it reads plus the tokens it writes, and its latency is roughly the sum of step times. Reading dominates in long runs, because every step re-reads the growing history. That is why the first rungs of the ladder are about steps and context, not models.

The ladder

CHEAPEST AND SAFEST FIRST
The optimisation ladder for agents
  1. 1

    1 · Cut steps

    do less

    • Workflow for fixed parts
    • Stop when verified, not when tired
  2. 2

    2 · Cut context

    read less

    • Trim tool results
    • Clear old outputs, compact
  3. 3

    3 · Fix tools

    choose right first time

    • Clear descriptions and errors
    • Fewer, sharper tools per task
  4. 4

    4 · Cache and route

    pay less per token

    • Stable prefix cached
    • Cheap model for easy steps
  5. 5

    5 · Optimise prompts

    search with a metric

    • Instructions and examples
    • Held-out evaluation
  6. 6

    6 · Change weights

    fine-tune or RL

    • Stable task, trusted grader
    • A model to maintain
Measure success, pass^k, tokens and latency on the same task set after every rung.
  1. Cut steps. Turn fixed sequences into code (a workflow), stop on a verified result rather than on the model's say-so, and remove "checking" steps that never change the outcome.
  2. Cut context. Return only the fields a tool result needs, clear stale tool outputs, compact long histories, move exploration into subagents.
  3. Fix tools. Most wasted steps are repeated or wrong tool calls caused by vague descriptions, ambiguous parameters or errors the model cannot act on. Fewer, sharper tools per task also shrink the prompt.
  4. Cache and route. Keep the prefix byte-identical so prompt caching applies, and send classification, extraction and other easy steps to a smaller model, with a check that escalates when it is unsure.
  5. Optimise prompts. With a metric, a training set and a held-out set, an optimiser can search instructions and examples more thoroughly than a person editing by hand.
  6. Change weights. Fine-tuning and reinforcement learning help when a task is stable and narrow, a grader is trustworthy, and the cheaper rungs are exhausted. You then own a model: its evaluation, its upgrades and its drift.

Estimate before you change

A rough model of the run tells you which rung matters. Here a ticket takes eight steps; each step re-reads the history:

def run_cost(steps, prefix, per_step_growth, cached_prefix=False, price_in=3.0, cache_price=0.3):
    total, history = 0.0, 0
    for _ in range(steps):
        p = prefix * (cache_price if cached_prefix else price_in)
        total += p + history * price_in
        history += per_step_growth
    return total / 1_000_000

base = run_cost(steps=8, prefix=6000, per_step_growth=3000)
trimmed = run_cost(steps=8, prefix=6000, per_step_growth=800)
fewer = run_cost(steps=5, prefix=6000, per_step_growth=800)
cached = run_cost(steps=5, prefix=6000, per_step_growth=800, cached_prefix=True)
print([round(x, 4) for x in (base, trimmed, fewer, cached)])
# => [0.396, 0.2112, 0.114, 0.033]

Prices are illustrative units per million input tokens, with cached prefix reads priced at a tenth of normal input; check your provider's actual ratio. Trimming tool results (3,000 to 800 tokens added per step) nearly halves the cost; cutting three steps halves it again; caching the stable prefix cuts what remains by more than two thirds. The run is now about a twelfth of the original cost with the same model, and every change was reversible. Measure success alongside, because trimming too much context can lose the field the model needed.

When changing weights is justified

  • The task is stable: the same kind of input and output for months.
  • There is a trustworthy grader: tests, an end-state check or a calibrated judge, because the training signal is only as good as the grader.
  • The cheaper rungs are done, and what remains is model behaviour: format adherence, a domain's tool-use pattern, latency that only a smaller model can reach.
  • You can maintain it: re-evaluate on each base-model upgrade, retrain when the task drifts, and keep a fallback.

Say it in 30 seconds

"I optimise agents in order of cost and risk. First cut steps, turning fixed sequences into code and stopping on verified results; then cut context by trimming tool results and clearing history; then fix tool descriptions and errors so the model picks right first time; then cache the stable prefix and route easy steps to a smaller model; then optimise prompts against a metric with a held-out set; and only then fine-tune or use reinforcement learning, when the task is stable, the grader trustworthy and I can maintain the model. I measure success, pass^k, tokens and latency on the same tasks after every change, because long-run cost is mostly re-reading context."

Check yourself

Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.

  1. 1Why does reading dominate the cost of long agent runs, and which rungs address it?

  2. 2Name three conditions that justify fine-tuning or RL for an agent.

  3. 3You trim tool results and cost halves, but success drops two points. What do you do?

Practise it as an interviewer asks it

Course lessons that teach this

Related lessons