Cutting my AI assistant's bill by 68%

Prompt caching, a local database behind the tools, and two model tiers, measured against real usage logs.

#llm#claude#homelab#cost

MiAi is the personal platform I run at home: a FastAPI service over Postgres/Timescale, a React front end, and modules for health, wealth and career. Running through all of it is an assistant built on the Claude API. It reads my training history, answers questions about my data, and designs strength workouts that it pushes to my Tonal.

An assistant like that can get expensive quickly. Each turn re-sends a long system prompt, a dozen tool definitions and the whole conversation so far. If you also paste the user's data into the prompt "so the model has context," the bill grows with every row in the database. I built three cost controls into MiAi from the start. This post walks through each one and then checks them against the token counts MiAi logs for every reply.

Updated December 6: two days later I re-checked the numbers with more conversations logged. Caching still saves 69%, but a growing conversation had started to eat into it. See the update for what I found and fixed.

$3.21actual spend, 52 API calls
$10.12same calls, all Opus, no cache
$6.91saved (68%)

The standard setup, and what I built instead

The usual first version of an assistant has one model for everything (the biggest, to be safe), no caching, and context stuffing: the app gathers whatever data might be relevant and puts it in the prompt. It is simple and it works. It is also the most expensive way to call an LLM, because you pay the full input price for the same tokens over and over.

Standard architecture compared with MiAi's cost-optimized architecture Left: every request sends the system prompt, tools, history and pasted data to Opus at full input price. Right: requests go to Sonnet by default, escalate to Opus for workout design, read a cached prefix, and fetch small tool results from local Postgres. Standard one model · no cache · data pasted into the prompt MiAi two tiers · cached prefix · tools over local Postgres Your message EVERY REQUEST SENDS Tool definitions full price System prompt + knowledge index full price Whole conversation so far full price Pasted user data workouts, vitals, accounts, notes… grows with the database ~300k tokens/turn (estimate) Opus every turn $4 in / $20 out Cost drivers Same prefix billed at full input price, every call Simple chat priced like hard planning Measured on MiAi's 52 calls (no data pasting): $10.12 Your message REQUEST Tools + system + index cache, 1 h Earlier turns + tool steps cache, 5 min New message only full price cache read: $0.20 per million tokens Sonnet chat, Q&A, lookups $2 in / $10 out Workout design? recommend_workout called → escalate no yes Opus workout plans only $4 in / $20 out Local Postgres health · wealth · career · ~16 MB stays on my server tool call small result (~160 chars avg) Result Repeated prefix billed at the cache-read rate Opus only where it earns its price · data fetched on demand $3.21
Figure 1. The standard pattern compared with MiAi. Prices are per million tokens. The $10.12 and $3.21 figures come from the same 52 logged calls, repriced. The 300k-token figure for pasted data is an estimate, not a measurement.

Lever 1: prompt caching

Every Messages API request is processed as one long sequence in a fixed order: tools → system → messages. Prompt caching lets the API store the processed state of a prefix of that sequence and reuse it on later requests. You mark where a cacheable prefix ends with a cache_control breakpoint. A later request that starts with byte-for-byte the same prefix reads it from the cache instead of processing it again.

The pricing makes this the biggest single lever. A cache read costs a small fraction of normal input. A cache write costs a bit more than normal input:

Per million tokensSonnet 5.5Opus 5.5
Input (uncached)$2.00$4.00
Cache write, 5-minute TTL (1.25×)$2.50$5.00
Cache write, 1-hour TTL (2×)$4.00$8.00
Cache read$0.20$0.20
Output$10.00$20.00

On Opus 5.5 a cache read costs 5% of normal input. Once a prefix is written, every later request that reuses it pays about one-twentieth of the normal input price for those tokens.

Two breakpoints, two lifetimes

MiAi uses two of the four breakpoints a request allows:

  1. An explicit 1-hour breakpoint on the static prefix. The tool definitions, the system prompt and the knowledge-base index together come to about 9,000 tokens, and they don't change between turns. I talk to the assistant in bursts, often 5 to 60 minutes apart. A 5-minute entry would expire between most turns and be rewritten each time. The 1-hour TTL costs 2× to write instead of 1.25×, but it survives the gaps.
  2. Automatic caching on the conversation tail. A top-level cache_control on the request moves the breakpoint to the last block every time. Within one turn the assistant may make several tool calls, and each step re-sends the whole history. With the moving breakpoint, each step reads everything before it from the cache.
# prompt.py: the static prefix gets the 1-hour breakpoint
def system_blocks(index):
  return [{"type": "text", "text": SYSTEM},
          {"type": "text", "text": index,
           "cache_control": {"type": "ephemeral", "ttl": "1h"}}]

# agent.py: automatic caching follows the growing conversation
request = dict(model=model, system=system, tools=TOOLS, messages=messages,
             cache_control={"type": "ephemeral"},   # 5-minute, moves forward
             ...)

Order matters: an entry with a longer TTL has to come before one with a shorter TTL. A 1-hour prefix followed by a 5-minute tail is allowed. The reverse is not.

The break-even arithmetic

A 5-minute entry pays for itself on the second request: 1.25× (write) + 0.1× (read) is less than 2× uncached. A 1-hour entry needs a third request: 2× + 2 × 0.05× on Opus is less than 3×. A typical turn in MiAi involves 2 to 4 API steps, and my conversations run several turns, so both entries clear break-even easily.

Silent invalidators

The cache matches bytes, not meaning. Anything that changes the prefix, such as a timestamp in the system prompt, a reordered tool list or JSON serialized with keys in a different order, turns a cache read into a fresh write. Nothing returns an error. The only symptom is usage.cache_read_input_tokens dropping to zero.

MiAi hit exactly this. Message blocks were stored in a Postgres jsonb column, and jsonb re-sorts object keys on write. When the history was replayed, the bytes no longer matched what had been cached, so every turn rewrote the conversation. Switching the column to plain json, which keeps key order, fixed it. The bug wasted about 31,000 tokens, roughly $0.15, before I noticed. It was cheap only because I was logging usage per message and checked it.

That logging is the key point. Every assistant reply in MiAi stores the full usage object (input, output, cache read, cache write broken down by 5-minute and 1-hour TTL) next to a computed cost_usd. Without it I would never have seen the bug, and I couldn't have written this post.

Lever 2: keep the data local and let tools fetch it

The assistant does not get my data in its prompt. It gets tools. query_health, the career_* tools, the wealth tools and consult_knowledge all run SQL against the Postgres instance on my own server and return only the rows the question needs. The model decides what to look up, and the database does the filtering.

The difference in volume is large. Across the logged calls, 32 tool results reached the model, totalling 5,051 characters, about 1,300 tokens. Behind those tools sit roughly 16 MB of local data: health 5.4 MB, career 1.6 MB, wealth 1.1 MB, and 7.8 MB of core tables.

The context-stuffing alternative never ran, so I can't measure it. As a rough illustration: the health data alone is about 4,900 rows. Serialized into a prompt that is on the order of 300,000 tokens, about $0.60 per turn on Sonnet before output, against roughly $0.06 for an average MiAi turn today. Over the same 52 calls that would be on the order of $30. Treat that number as an estimate of scale, not a measurement.

There are benefits beyond cost:

  • Privacy. Only the few rows a question needs leave my network, not the whole database.
  • Cache stability. Pasted data changes whenever a new workout syncs, which would invalidate the cached prefix on every turn. Tool results land at the end of the conversation, after the breakpoint.
  • Accuracy. The model reads a precise query result instead of searching for one number in a 300k-token dump.

Lever 3: two model tiers

Most of what I ask the assistant is ordinary: what did I lift last Tuesday, how is my resting heart rate trending, what's due this week. That doesn't need the most capable model. Designing a strength workout does. It has to balance muscle readiness, recent volume, equipment changes and the vetted training guidance in the knowledge base, and a weak plan is worse than none.

MiAi splits the work along that line:

  • Sonnet 5.5 (MIAI_COACH_MODEL) handles every turn by default, at half of Opus's input and output price.
  • Opus 5.5 (MIAI_COACH_PLAN_MODEL) takes over when planning starts. As soon as a step calls a planning tool, the rest of that turn runs on Opus.

The escalation has one guard. If Sonnet tries to call recommend_workout itself, MiAi discards that draft and re-issues the same request on Opus, so every stored workout plan comes from Opus. The discarded step is still saved as a cost-only row, so its spend shows up in the totals.

if model != PLAN_MODEL and "recommend_workout" in names:
  # The chat model drafted a plan: drop it and re-run this step on Opus.
  model = PLAN_MODEL
  save_cost_only_row(usage, cost)   # the discarded draft is still counted
  continue

There is a trade-off. Caches are per model, so the first Opus step in a turn can't read Sonnet's cache and writes its own copy of the prefix. Workout requests are a small share of turns, and the 1-hour entry on the Opus side is then reused across a planning session, so the cost is small. But a design that switched models on every turn would lose much of its caching benefit.

December 6 correction: "the cost is small" held only while conversations were short. The first Opus step writes the whole conversation history to its cache, not just the prefix, and by December 6 that history was over 100,000 tokens. The update below covers the fix.

The numbers

MiAi has logged 52 API calls with full usage data so far (December 3–4): 36 on Opus, 16 on Sonnet. To isolate each lever I repriced exactly the same token counts under different assumptions. "No cache" means every cache-read and cache-write token billed as normal input.

Cost of the same 52 API calls under four setups $0 $5 $10 All Opus, no cache $10.12 Two tiers, no cache $7.56 All Opus, cached $3.90 Actual (both) $3.21
Figure 2. The same 52 calls repriced under each setup, drawn to scale. Prices come from MiAi's pricing table, which matches Anthropic's published rates for these models.
SetupCostLever isolatedSaved
Actual: two tiers, caching on$3.21——
Two tiers, no caching$7.56Caching$4.36 (58%)
Caching on, every call on Opus$3.90Model tiers$0.69 (18%)
Every call on Opus, no caching$10.12Both$6.91 (68%)
Data pasted into every prompt~$30+Local DB (estimate)not measured

Caching did most of the work. About 2.3 million input tokens were cache reads or writes. Billed as normal input they would have cost $4.36 more.

The tier saving understates the steady state. On the 16 Sonnet calls, the tiering saved 44%. It looks small overall only because Sonnet became the chat model partway through December 3, so most of the 36 Opus calls are chat from before the switch. From now on, only workout design runs on Opus, so the tier saving on future usage should land near that 44%.

Update, December 6: the conversation kept growing

Two days after I first wrote this post, I re-ran the same analysis with 10 more calls logged. The headline held up:

PeriodCallsActualAll Opus, no cacheSavedCache hit rate
December 3–4 (above)52$3.21$10.1268%78%
December 610$1.37$4.4569%70%
All time62$4.57$14.5769%76%

The percentage hid a trend. MiAi keeps one running conversation per area until I start a new topic, and I never had. The cached history had grown from 64,000 tokens on December 3 to 98,000 on December 4 and 115,000 on December 6. Most of it was old tool results: Tonal movement searches and health queries from days earlier that Claude didn't need anymore.

A cache miss means rewriting the whole history, and a bigger history makes every miss cost more. Three misses made up 82% of December 6's spend:

TimeWhat happenedCost
09:26First message after a day and a half away. The cache had expired, as expected.$0.28
09:27Escalated to Opus for a workout. Caches are per model, so Opus wrote all 102,000 tokens of history.$0.58
09:41Six minutes after my previous message, just past the 5-minute TTL.$0.26

The 1-hour prefix did its job. At 09:41 the tools and system prompt were still read from cache; only the history had expired.

The obvious fix was the wrong one. Moving the history to the 1-hour TTL would have caught the 09:41 miss. I repriced all 62 calls that way and it came out more expensive, $5.50 instead of $4.57, because every history write would cost 2× instead of 1.25×. The writes outnumber the misses it saves.

The real fix is to keep the history small. I made two changes to MiAi:

  1. Compact at cold starts. When I come back after more than 5 minutes, the history cache has expired anyway, so the next request has to write it in full regardless. That's the free moment to shrink it. Earlier sessions are replayed in compact form: old tool results become a one-line placeholder ("call the tool again if you need this data"), old data snapshots and old reasoning are dropped, and my words, Claude's answers and the record of which tools ran all stay. The cut-off point is worked out from the saved message timestamps, so the next warm turn computes the same cut-off and sends exactly the same bytes. Compacting never breaks a warm cache.
  2. Give Opus a compact history. When a turn moves to Opus for workout design, Opus gets earlier turns in compact form and the current turn in full. I considered asking a model to write a summary, but that's another API call, and its output would differ every time. Compacting is free, deterministic and cacheable.

To check the effect without spending anything, I replayed the real conversation through Anthropic's token-counting endpoint, which is free and also confirms the API accepts the compacted history:

111,899tokens, full history
36,668tokens, compacted (67% smaller)

Applied to December 6's calls, that would have cut the day from $1.37 to about $0.61, 55% less, on top of what caching already saved. The Opus escalation alone drops from $0.58 to about $0.25. That's an estimate: it only shrinks history from before that day, so the real saving should be a little larger. The next few days of usage logs will show the real number.

The lesson: a cache hit rate tells you how often you reuse tokens, not how many tokens you're carrying. If the thing you cache keeps growing, the misses get more expensive even when the hit rate looks fine.

Caveats

  • Small sample. Two days and 52 calls. The dollar amounts are small, and the percentages are what will carry forward.
  • Repricing, not A/B testing. The counterfactual costs reprice the same token counts. A real no-cache run would have the same tokens, so for caching the comparison holds. For tiers, Opus might write shorter or longer answers than Sonnet, which I haven't measured.
  • The local-database figure is an estimate. The context-stuffing version was never built.
  • Prices are list prices from MiAi's pricing table, checked against Anthropic's published rates for Sonnet 5.5 and Opus 5.5.

What I'd tell someone building their own

  1. Log usage on every call from day one. Every number in this post comes from that column. It also caught the cache bug.
  2. Put stable content first and mark it. Tools, then system prompt, then reference material, with a breakpoint at the end. Pick the TTL from the real gap between your requests.
  3. Watch cache_read_input_tokens. If it reads zero on a repeat request, something in your prefix is changing: timestamps, key order or tool order.
  4. Give the model tools, not dumps. A query that returns 200 characters beats a prompt that carries 300,000 tokens, on cost, privacy and accuracy.
  5. Use the expensive model only for the expensive task, and make the escalation deterministic in code rather than leaving it to the cheaper model to decide.
  6. Bound what you cache. Watch the size of the cached history, not just the hit rate. Trim it when the cache is cold anyway, the same way every time, so warm requests keep hitting.

MiAi runs on a home server: FastAPI, Postgres/Timescale, React, and the Claude API (Sonnet 5.5 and Opus 5.5).