Cut your LLM bill without downgrading your model

I measured a 32-task agent workload over this blog's archive, then applied five fixes one at a time. Same answering model, 91% lower modelled cost, and the receipts to check it.

A row of white digital electricity meters mounted on salmon-pink utility boxes (Photo: Connor Scott McManus / Pexels)
A row of white digital electricity meters mounted on salmon-pink utility boxes (Photo: Connor Scott McManus / Pexels)

The short answer

Measure tokens per step first, then fix five leaks: a cache-friendly prompt, routing search turns to a small model, async discounts, trimmed context and hard loop limits. On a 32-task agent workload this cut modelled cost from $1.50 to $0.13 (91%) with the same answering model.

Key takeaways

  • Log tokens per step, not per month: in the test workload, search turns were 75% of the bill and four runaway tasks were 62% of it.
  • A timestamp at the top of the prompt made default caching 20% more expensive than no caching; moving it cut cost 64%.
  • Routing only the search turns to GPT-6 Luna, while GPT-6.2 Sol still writes every answer, cut another 48%.
  • Background mode's 8-hour window is 40% off and works for multi-turn agents; Batch is 50% off but built for independent requests.
  • Trimming top-k and unused tools saved 17.5%; aggressive history compaction saved 4.5% more but lost a two-hop answer.
  • Loop limits saved only 2.7% at the end of the stack but turned four MaxTurnsExceeded crashes into honest answers.

Most of an LLM bill is waste you can measure and remove without touching the model that writes your answers. On a 32-task agent workload over this blog’s own archive, five fixes (a cache-friendly prompt, routing the search turns, an async discount, trimmed context and loop limits) took the modelled cost from $1.50 to $0.13, a 91% cut, with the same answering model and every answerable question still answered.

Before you copy that number into a slide: read the next box. I’m going to be very precise about what was measured and what was calculated, because “we cut costs 91%” posts without receipts are how this industry got its reputation.

Receipts, and their limits. Everything below ran on my test box on 27 November 2026. The corpus (11 published theforloops posts, 164 chunks, 39,190 tokens), the retrieval, which search found the evidence, how many turns each task took, and every input token count are real, counted with tiktoken’s o200k_base tokenizer. There was no LLM API key on the box, so no request went to a model. The agent’s decisions are scripted, output tokens are fixed assumptions, cache hits follow OpenAI’s published caching rules, and costs are measured tokens, modelled cost at OpenAI’s published prices on 27 Nov 2026. The last section lists what a live run would add.

What was the test workload?

A small, boring, very common thing: an archive Q&A agent. A reader asks a question, the agent calls a search_posts tool, reads the chunks it gets back, searches again if it has to, then answers with citations.

Piece What I used
Corpus 11 published theforloops posts, fetched from the CMS API, chunked to ~300 tokens
Tasks 32: 24 single-hop lookups, 4 two-hop comparisons, 4 questions the archive can’t answer
Retrieval BM25 (rank_bm25), top 5 chunks per search in the baseline
Agent policy Scripted: tries each task’s search queries in order until all evidence chunks are in context, then answers. Unanswerable tasks keep searching
Turn limit 10, the OpenAI Agents SDK default max_turns
Answering model gpt-6.2-sol ($2 input, $10 output per 1M tokens, Standard tier)
Prompt 1,103-token developer prompt (rules plus this blog’s style guide), 8 tool definitions (679 tokens)
Output assumptions 120 reasoning tokens plus the call JSON per search turn; 300 reasoning + 180 visible tokens per answer; 60 visible for “not found”

The baseline has one deliberate, extremely common mistake: the developer prompt starts with Current time: ... | request_id: .... I’ve shipped that line. You probably have too.

Step 0: measure tokens per step, not per month

A monthly invoice tells you that you spent money. A per-step log tells you where. This is the wrapper I’d put around every Responses API call in a live system. The field names (cached_tokens, cache_write_tokens) come from OpenAI’s prompt caching guide:

import json, time
from openai import OpenAI

client = OpenAI()
PRICES = {  # USD per 1M tokens, Standard tier, OpenAI pricing page, 27 Nov 2026
    "gpt-6.2-sol": dict(inp=2.00, cached=0.10, write30=2.50, out=10.00),
    "gpt-6-luna":  dict(inp=0.10, cached=0.01, write30=0.125, out=0.50),
}

def step_cost(model, u, discount=0.0):
    p, d = PRICES[model], u.input_tokens_details
    cached = d.cached_tokens or 0
    written = getattr(d, "cache_write_tokens", 0) or 0
    ordinary = u.input_tokens - cached - written
    usd = (ordinary * p["inp"] + cached * p["cached"]
           + written * p["write30"] + u.output_tokens * p["out"]) / 1e6
    return usd * (1 - discount)

def logged_create(run_id, step, log_path="llm_usage.jsonl", discount=0.0, **kwargs):
    t0 = time.time()
    resp = client.responses.create(**kwargs)
    u = resp.usage
    row = dict(run_id=run_id, step=step, model=kwargs["model"],
               latency_s=round(time.time() - t0, 2),
               input=u.input_tokens,
               cached=u.input_tokens_details.cached_tokens,
               cache_write=getattr(u.input_tokens_details, "cache_write_tokens", 0),
               output=u.output_tokens,
               reasoning=u.output_tokens_details.reasoning_tokens,
               tool_calls=sum(1 for o in resp.output if o.type == "function_call"),
               usd=round(step_cost(kwargs["model"], u, discount), 6))
    with open(log_path, "a") as f:
        f.write(json.dumps(row) + "\n")
    return resp

My harness writes the same fields to JSONL for every simulated request. The baseline log said three things I wouldn’t have guessed from an invoice:

  • Search turns, not answers, are the bill. 70 of the 98 requests were “what should I search for?” turns, and they cost $1.12 of the $1.50 (75%).
  • Four tasks out of 32 ate 62% of the money. The four unanswerable questions searched until they hit the 10-turn limit and then crashed with MaxTurnsExceeded. That’s 40 requests, $0.93, and zero answers.
  • Output is the small part. Even with generous reasoning assumptions, output was $0.23 (16%). This workload is input-heavy, like most agent loops, because every turn resends the growing history.

The before/after table

Hands sorting a stack of paper receipts next to a calculator on a wooden desk (Photo: kaboompics / Pexels)
Every token is a line on the receipt. Photo: kaboompics / Pexels

Cumulative, in the order of this post. “Good outcomes” counts answerable questions answered with the evidence in context, plus unanswerable questions correctly answered with “not in the archive”.

Configuration Requests Input tokens Cache reads Cache writes Output tokens Cost, 32 tasks Change vs previous row Per 1,000 tasks Good outcomes
Baseline 98 505,165 0 505,165 23,247 $1.4954 n/a $46.73 28/32
+ 1. Prompt caching that hits 98 504,185 399,698 104,487 23,247 $0.5337 −64.3% $16.68 28/32
+ 2. Route search turns to a small model 98 504,185 393,918 110,267 23,247 $0.2783 −47.9% $8.70 28/32
+ 3. Async discount (background, 8h) 98 504,185 393,918 110,267 23,247 $0.1670 −40.0% $5.22 28/32
+ 4. Context trimming 99 330,880 259,072 71,808 23,402 $0.1378 −17.5% $4.31 28/32
+ 5. Loop limits 75 150,178 101,734 48,444 20,060 $0.1341 −2.7% $4.19 32/32

And each technique applied alone to the baseline, because savings don’t add up the way slide decks say they do:

Technique alone Cost, 32 tasks vs baseline
1. Prompt caching that hits $0.5337 −64.3%
2. Model routing $0.4348 −70.9%
3. Async discount $0.8972 −40.0%
4. Context trimming $1.0637 −28.9%
5. Loop limits $0.7540 −49.6%

Loop limits save half the bill on their own and 2.7% at the end of the stack. That isn’t a contradiction. Once caching and routing have made each runaway turn nearly free, killing the runaway turns saves pennies. What step 5 buys in the stack is the last column: four crashes turned into four honest answers.

Step 1: prompt caching that actually hits

Every request in the baseline starts with a different timestamp, so no two requests ever share a prefix. Here’s the bit I didn’t expect: on GPT-5.6 and later, OpenAI’s caching is on by default in implicit mode, and every request writes its prefix to the cache at 1.25x the normal input rate. A prefix that never matches gets written every time and never read.

So the broken baseline isn’t just missing a discount. It pays a surcharge. With caching switched off entirely, the same 98 requests cost $1.2428. With caching on and a timestamp at the top, they cost $1.4954, 20% more for the privilege of caching nothing.

The fix is moving the dynamic line, not deleting it. OpenAI’s guide is explicit: put stable instructions and tools first and dynamic content at the end. It also says that on GPT-6.2 models, top-level instructions are appended after the input and billed uncached on every request, so reusable instructions belong in the first developer message:

resp = logged_create(
    run_id, step,
    model="gpt-6.2-sol",
    tools=TOOLS,  # same list, same order, every call
    input=[
        {"role": "developer",
         "content": [{"type": "input_text", "text": DEV_PROMPT}]},  # stable, cacheable
        {"role": "user",
         "content": f"[context] date={today} task={task_id}\n{question}"},  # dynamic bits live here
        *history,
    ],
    prompt_cache_options={"mode": "implicit", "ttl": "30m"},
)

Saving: −64.3% ($1.4954 to $0.5337). 79% of input tokens became cache reads at $0.10 per million instead of $2.00. The cache-read rate for gpt-6.2-sol is 0.05x input, and reads within an agent loop are the cheapest tokens you’ll ever buy.

My model assumes every request lands inside the 30-minute cache lifetime, which is fair for one back-to-back run. If your requests are hours apart, OpenAI now sells a 12-hour lifetime at a 2.5x write rate:

Step 2: route the search turns, keep the answering model

The title promise is “without downgrading your model”, so here’s the line: the model that writes the answer never changes. What moves is the 70 turns where the agent only decides what to search for next. I gave those to gpt-6-luna ($0.10 input, $0.50 output) with two tools, search_posts and ready_to_answer. When Luna calls ready_to_answer, the same history goes to gpt-6.2-sol with tools switched off:

model, tool_choice = "gpt-6-luna", "auto"
for turn in range(MAX_TURNS):
    resp = logged_create(run_id, turn, model=model, input=history,
                         tools=SEARCH_TOOLS, tool_choice=tool_choice)
    calls = [o for o in resp.output if o.type == "function_call"]
    if any(c.name == "ready_to_answer" for c in calls):
        model, tool_choice = "gpt-6.2-sol", "none"  # the answer is written by the big model
        continue
    if not calls:
        return resp.output_text
    history += run_tools(calls)

Saving: −47.9% on top of caching ($0.5337 to $0.2783), or −70.9% on its own. One interaction to know about: cache entries are per model, so Sol’s answer turn can’t read the prefix Luna just cached. Cache reads dropped from 399,698 to 393,918 tokens. Routing still wins by a mile, but the log shows the tax.

What my harness can’t tell you is whether Luna writes search queries as well as Sol. My scripted agent used the same queries for both, so this row assumes equal query quality. That’s exactly the assumption to test before you ship it (more in the quality traps). If you want routing without hand-rolled code, the gateways in the Agent Builder’s Stack (LiteLLM, OpenRouter, Vercel AI Gateway) all do it.

Step 3: batch it, or let it wait in the background

The classic advice is “use the Batch API, it’s 50% off”. That’s true, and it’s built for independent requests you can submit together: evals, classification, embedding a repository. An agent loop isn’t that. Turn 2 depends on turn 1, and a Batch job only promises completion within 24 hours, per turn.

For multi-turn work that can wait, OpenAI’s own guide points to background mode with a discounted completion window: 30% below Standard for a 2-hour target, 40% below for 8 hours, and follow-up requests in the same run qualify too. It’s in public beta on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra and GPT-6 Luna.

resp = client.responses.create(
    model="gpt-6.2-sol", input=history, tools=TOOLS,
    background=True,
    service_tier="default",  # discounted windows require Standard processing
    background_options={"completion_window": "8h", "continuation_id": run_id},
)
# wait for the response.completed webhook (or poll client.responses.retrieve(resp.id)),
# run the tool, then send the follow-up with the same window and continuation_id

Saving: −40.0% ($0.2783 to $0.1670). I applied the 40% to every token rate, cache reads and writes included. The guide says the discount applies to “model token rates”, so check your first invoice on that point. I also ran the Batch alternative (50% off, but I assumed zero cache reads, since I couldn’t find a guarantee that parallel batch requests hit each other’s cache). With steps 1, 2, 4 and 5 it came to $0.1383, within a rounding error of the background version. Pick by latency, not by price.

Two catches from the docs. Standard requests can’t reuse cache entries created by 2h or 8h background requests, so don’t mix the two on the same prefix. And “nightly” is the honest use case: this is for evals, report generation and back-office agents, not a chat window.

Step 4: trim the context you resend

Every turn resends everything. Two cheap trims:

TOP_K = 3                    # was 5: fewer chunks per search
TOOLS = [SEARCH_POSTS]       # was 8 tools; this agent only ever calls one

Saving: −17.5% ($0.1670 to $0.1378), or −28.9% alone. It’s the smallest cumulative win because caching already made the repeated prefix cheap. Trimming mostly removes new tokens (tool outputs), which are the ones you pay full price or write rates for.

Quality check, measured: with top 3 instead of top 5, every answerable question still got its evidence, but one task (small vs large publisher traffic) needed an extra search because its evidence chunk ranked fourth. One extra request, still cheaper overall.

A trap the numbers caught: the stable prefix (tools plus developer prompt) shrank from 1,790 to 1,235 tokens. OpenAI only caches prefixes of at least 1,024 tokens. Trim the developer prompt a little more and you’d fall off that cliff and lose caching for every first turn.

I also tried the “smart” trim: compacting older search results down to their top chunk once a new search arrives. It saved another 4.5% ($0.1316) and broke a two-hop question. The compaction threw away the first half of the evidence, my scripted agent never got it back, and the task ran into the turn limit. A real model might search again, which costs the turns you were trying to save. Editing history also breaks the cache from the first changed token, and on GPT-6.2 it drops the reasoning that followed the edit:

Step 5: put a leash on the loop

The baseline’s four unanswerable questions show the most expensive pattern in agent systems: the agent can’t find something, so it keeps looking until a framework stops it. The OpenAI Agents SDK’s default max_turns is 10, after which it raises MaxTurnsExceeded. You pay for all ten turns and the user gets an error.

Two rules fixed it: stop when a search returns nothing new (the loop is going in circles), and cap searches at four. When the loop guard trips, return a fixed reply from code. No model call.

NOT_FOUND = "I couldn't find that in the theforloops archive."
MAX_SEARCHES = 4

seen, searches, tool_choice = set(), 0, "auto"
for turn in range(MAX_TURNS):
    resp = logged_create(run_id, turn, model=model, input=history,
                         tools=TOOLS, tool_choice=tool_choice)
    calls = [o for o in resp.output if o.type == "function_call"]
    if not calls:
        return resp.output_text
    for call in calls:
        hits = index.search(json.loads(call.arguments)["query"], k=TOP_K)
        fresh = {h.id for h in hits} - seen
        seen |= {h.id for h in hits}
        searches += 1
        if not fresh:
            return NOT_FOUND                 # going in circles: stop from code
        history += tool_output(call, hits)
    if searches >= MAX_SEARCHES:
        tool_choice = "none"                 # one last turn: answer with what you have

If you’re on the Agents SDK, error_handlers={"max_turns": ...} gives you the same graceful exit instead of an exception.

Saving: −2.7% in the stack ($0.1378 to $0.1341), −49.6% alone, and good outcomes went from 28/32 to 32/32. No answerable task needed more than three turns, so a cap of four searches cut nothing legitimate in this workload.

The honest caveat: my scripted agent repeats its last query verbatim, so “nothing new” fired fast. A real model rephrases, so in a live run the cap does more of the work and the model writes the “not found” reply itself. I ran that variant too. It costs $0.1662, more than step 4. So the realistic range for the full stack is $0.134 to $0.166 per 32 tasks, an 89-91% cut either way.

What not to cut: the quality traps

  • Don’t cut the evidence. Trimming that drops the chunk the answer depends on doesn’t save money. It moves the cost into retries or wrong answers. Measure recall at your new top-k (mine stayed at 28 of 28, with one extra search) before you celebrate. Long context isn’t free on quality either: the “Lost in the Middle” study found models use information at the start and end of long inputs better than information in the middle, which is an argument for trimming noise, not evidence.
  • Don’t route blind. Routing papers like RouteLLM report costs cut by more than 2x “without compromising the quality of responses” in some cases, but that’s with a trained router and an evaluation set. Run your eval on the routed turns specifically. A cheap model that writes worse queries makes the big model answer from worse evidence, and you won’t see it in the cost log.
  • Don’t edit history to save tokens without measuring the cache. Compaction and rewriting old messages break the cached prefix from the first changed token, and on GPT-6.2 they also drop the reasoning after the edit. My compaction variant saved 4.5% and lost a two-hop answer.
  • Don’t make the turn cap your only safety net. A cap that’s too tight cuts legitimate multi-hop work, and a cap that only throws an exception still bills you for every turn. Look at your turn distribution first (mine: 26 tasks in 2 turns, 2 in 3, 4 runaways at 10), then set the cap above the legitimate tail.
  • Don’t push interactive traffic into async windows. A 40% discount on a reply that arrives in eight hours is a 100% loss of the user.
  • Don’t judge by cost per request. Judge by cost per good outcome. Here it went from $53.41 per 1,000 good outcomes to $4.19, partly because the denominator grew. That’s the metric I argued for in harness engineering: cost per accepted outcome, failed runs included.

A monthly cost-review routine

Thirty minutes, first Monday of the month, with the per-step log open:

  1. Cache hit rate by route: cached tokens ÷ input tokens, grouped by agent and model. A drop usually means someone added a timestamp, reordered tools or changed reasoning settings. All three break the prefix.
  2. Write-to-read ratio: if cache writes are close to cache reads, you’re paying the 1.25x write rate for prefixes nobody reuses. Use explicit breakpoints, or move the dynamic content.
  3. Top 10 most expensive runs: read them. Runaway loops and giant tool outputs show up here first.
  4. Turn distribution: p50, p95 and max turns per task. Re-check that your cap sits above the legitimate tail.
  5. Spend by turn type: search/planning turns vs answer turns. If planning turns are still on your biggest model, that’s the next routing candidate.
  6. Async candidates: any scheduled job still on Standard tier is money left on the table.
  7. Price sheet diff: models and rates change monthly (in the last six weeks OpenAI added 12-hour caching and discounted background windows). Re-run your cost script against the current page.
  8. Eval on every change: each change ships with the same eval set, scored on good outcomes, not just cost.

On Anthropic the levers are the same with different multipliers: 5-minute cache writes cost 1.25x input, 1-hour writes 2x, reads 0.1x on most models, and the Batch API is 50% off input and output. Anthropic says those multipliers stack.

What would a live run add?

Real output and reasoning token counts (mine are fixed guesses; output was 16% of the baseline bill, so this moves the absolute numbers more than the percentages). Real cache behaviour, including hidden system tokens, cache evictions and whether batch requests share cache. Whether Luna’s search queries are as good as Sol’s. Real latency for the 8-hour window. And the exact GPT-6 tokenizer: tiktoken doesn’t map GPT-6 models yet, so my counts use o200k_base, the GPT-5-era encoding.

The full harness is about 250 lines of Python: corpus loader, BM25 index, the cache model (OpenAI’s documented implicit-mode rules: 1,024-token minimum, writes at the latest eligible message, longest matching prefix wins, entries per model), the scripted agent and per-request JSONL logs. If you run the live version with the wrapper above, I’d love to see how far your numbers land from mine.

Same model, same answers, a tenth of the bill. The waste was never in the model. It was in the loop around it, which is good news, because the loop is the part you own. It’s also why efficiency is becoming a product feature.

Frequently asked questions

Does OpenAI prompt caching cost extra?

On GPT-5.6 and later, cache writes cost 1.25x the normal input rate for the default 30-minute lifetime (2.5x for 12 hours) and reads cost 0.05x to 0.1x. Caching only saves money when later requests reuse the same prefix; a prefix that changes every request is written every time and never read.

Can I use the Batch API for an AI agent?

Only awkwardly. Batch suits independent requests and promises completion within 24 hours, so a multi-turn agent would wait up to a day per turn. For agent loops that can wait, OpenAI's background mode with a 2-hour or 8-hour completion window gives 30% or 40% off and applies to follow-up requests.

Is model routing the same as downgrading my model?

Not if you route the right turns. In this workload only the turns that decide what to search for moved to a smaller model; the final answer was always written by the original model. You still need an eval on the routed turns, because worse search queries mean worse evidence.

What is a sensible max_turns limit for an agent?

Set it from your own turn distribution, a little above the longest legitimate task. Here every answerable task finished within three turns, so a four-search cap cut nothing legitimate. The OpenAI Agents SDK defaults to 10 turns and raises MaxTurnsExceeded unless you add an error handler.

Are the numbers in this post from a live API run?

No. Input tokens, retrieval and turn counts were measured on a real workload, but no API key was available, so output tokens are fixed assumptions and costs are modelled from OpenAI's published prices and caching rules on 27 November 2026.

Sources

  1. API pricing OpenAI
  2. Prompt caching guide OpenAI
  3. Batch API guide OpenAI
  4. Background mode and discounted completion windows OpenAI
  5. Models: GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Terra, GPT-6 Luna OpenAI
  6. OpenAI Agents SDK: Running agents (max_turns, error handlers) OpenAI
  7. openai-agents-python run_config.py (DEFAULT_MAX_TURNS = 10) GitHub / OpenAI
  8. 12-hour prompt caching announcement OpenAI Developers on X
  9. Discounted background completion windows announcement OpenAI Developers on X
  10. GPT-6.2 reasoning items tied to conversation history OpenAI Developers on X
  11. Claude API pricing (prompt caching and Batch multipliers) Anthropic
  12. RouteLLM: Learning to Route LLMs with Preference Data arXiv (Ong et al., 2024)
  13. Lost in the Middle: How Language Models Use Long Contexts arXiv (Liu et al., 2023)
  14. tiktoken OpenAI / GitHub
  15. rank_bm25 GitHub

Found this useful?

Clap (up to 50×) so more people find it.

Written by

Noaman

Markdown version