Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 71. Cost at scale
  4. 71.4

Lesson 71.4 · 4 of 6 · 4 min read · Reviewed 24 Nov 2026

Cutting cost without losing quality

By the end, you can

  • Apply the main levers that cut cost.
  • Measure quality before and after each change.

The levers

Lever Typical effect Risk
Prompt caching of stable prefixes Large saving on repeated input Low, if prefix order is right
Batch for offline work Discount on work nobody waits for Higher latency
Model routing (71.2) Large saving on easy traffic Quality on misrouted requests
Trimming context and tool results Saves input on every agent step Losing a needed fact
Shorter outputs (format rules, max_tokens) Saves output, often the pricier side Cut-off answers
Lower reasoning effort on easy routes (13.6) Cuts thinking tokens, which are billed as output Worse answers on hard cases; set it per route and check with evals
Fewer retries and loops Removes waste None
Response cache for repeats Skips calls entirely Stale or leaked answers

A method

  1. Find the biggest line. Group cost by feature, model and step type.
  2. Pick one lever that fits that line.
  3. Run evalsEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria. before and after. Compare quality, latencyLatency: The time from sending a request until you get the response, or until the first token arrives when streaming. and cost together.
  4. Roll out gradually (72.2) and watch online signals.

Common wins

  • A timestamp or request id at the top of the system prompt breaks prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency.. Move it to the end.
  • Tools that return whole records when the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. needs two fields. Return less.
  • An agent re-reading a long document on every step. Summarise once, keep notes.
  • Verbose answers nobody reads. Ask for the format you need.

Key points

  • The main levers: prompt caching, shorter prompts and outputs, lower reasoning effort, routing, batching, trimming context, and fewer retries.
  • Change one lever at a time and run your evals; cheaper but worse is not a saving.
  • Start with the biggest line on the bill: find it in your traces.
Hands-on labRuns in the Playground

Fix a prompt that breaks caching

See how a timestamp at the top of a cached prefix stops every cache hit, fix it and check quality held.

You will have: Four simulated calls whose usage shows cache reads after the fix, with a quality check on every answer.

Steps

  1. Run the starter and read the usage lines: every call writes the cache and none reads it.
  2. Move the timestamp out of the cached system block and into the user turn.
  3. Add the quality check: a non-empty answer that ended with end_turn.
  4. Run again and compare cache reads and illustrative input credits with the first run.

Done when

  • Calls 2 to 4 read the prefix from cache.
  • Illustrative input credits drop compared with the starter run.
  • All 4 answers pass the check.

Open in the Playground No API key needed.

Starter code (Python)
# Lever: prompt caching. A timestamp at the top of the system prompt changes the prefix on every call,
# so nothing is ever read from cache. Move it out of the cached prefix and measure again.
import anthropic

client = anthropic.Anthropic()
POLICY = "\n".join(f"Rule {i}: refunds for order type {i % 7} follow section {i % 11} of the returns policy, "
                   f"and the agent must quote the section number in its answer." for i in range(1, 60))
QUESTIONS = ["Can I return a used grinder?", "How long do refunds take?",
             "Do you refund delivery costs?", "Can I swap a damaged milk jug?"]


def ask(n, question):
    stamp = f"Request time: 2026-11-24T10:0{n}:00Z"
    # TODO 1: the timestamp sits at the top of the cached prefix, so the prefix differs on every call.
    #         Keep only the stable text in the system block and move the stamp into the user turn.
    system = [{"type": "text", "text": stamp + "\nYou answer customer questions about returns.\n" + POLICY,
               "cache_control": {"type": "ephemeral"}}]
    return client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=200,
        system=system,
        messages=[{"role": "user", "content": question}],
    )


reads, passed, credits = 0, 0, 0.0
for n, q in enumerate(QUESTIONS):
    m = ask(n, q)
    u = m.usage
    # Illustrative credits per 1,000 input tokens: 1 normal, 1.25 cache write, 0.1 cache read.
    credits += (u.input_tokens + 1.25 * u.cache_creation_input_tokens + 0.1 * u.cache_read_input_tokens) / 1000
    reads += u.cache_read_input_tokens > 0
    text = "".join(b.text for b in m.content if b.type == "text")
    # TODO 2: count the answer as passed when the text is not empty and stop_reason is "end_turn"
    print(f"call {n + 1}: input {u.input_tokens}, cache write {u.cache_creation_input_tokens}, cache read {u.cache_read_input_tokens}")
print(f"cache reads: {reads} of {len(QUESTIONS)} calls")
print(f"input credits (illustrative): {credits:.2f}")
print(f"checks passed: {passed} of {len(QUESTIONS)}")
Show a solution
# Lever: prompt caching. A timestamp at the top of the system prompt changes the prefix on every call,
# so nothing is ever read from cache. Move it out of the cached prefix and measure again.
import anthropic

client = anthropic.Anthropic()
POLICY = "\n".join(f"Rule {i}: refunds for order type {i % 7} follow section {i % 11} of the returns policy, "
                   f"and the agent must quote the section number in its answer." for i in range(1, 60))
QUESTIONS = ["Can I return a used grinder?", "How long do refunds take?",
             "Do you refund delivery costs?", "Can I swap a damaged milk jug?"]


def ask(n, question):
    stamp = f"Request time: 2026-11-24T10:0{n}:00Z"
    # The stable policy is the cached prefix; the changing timestamp goes after it, in the user turn.
    system = [{"type": "text", "text": "You answer customer questions about returns.\n" + POLICY,
               "cache_control": {"type": "ephemeral"}}]
    return client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=200,
        system=system,
        messages=[{"role": "user", "content": f"{stamp}\n{question}"}],
    )


reads, passed, credits = 0, 0, 0.0
for n, q in enumerate(QUESTIONS):
    m = ask(n, q)
    u = m.usage
    # Illustrative credits per 1,000 input tokens: 1 normal, 1.25 cache write, 0.1 cache read.
    credits += (u.input_tokens + 1.25 * u.cache_creation_input_tokens + 0.1 * u.cache_read_input_tokens) / 1000
    reads += u.cache_read_input_tokens > 0
    text = "".join(b.text for b in m.content if b.type == "text")
    passed += bool(text.strip()) and m.stop_reason == "end_turn"  # a tiny quality check, run every time
    print(f"call {n + 1}: input {u.input_tokens}, cache write {u.cache_creation_input_tokens}, cache read {u.cache_read_input_tokens}")
print(f"cache reads: {reads} of {len(QUESTIONS)} calls")
print(f"input credits (illustrative): {credits:.2f}")
print(f"checks passed: {passed} of {len(QUESTIONS)}")
Quick checkYou want to cut cost 30% without hurting quality. What should you do first?
How sure are you?
Pick an answer and how sure you are