← All writing

Paying for inference only where it counts

Cache the expensive step, size the effort to the task, and let cheap math decide when a model is needed at all.

Most of the cost of an AI feature comes from calls that didn't need to happen, or didn't need that much model. Across my three projects I ended up using the same few habits to keep that down. None of them are clever; they're the kind of thing that's easy to skip in a prototype and expensive to skip in production.

1. Don't call the model when math can answer

The cost bot in secure-landing-zone reads AWS Cost Explorer every day and posts to Slack when spend jumps. Finding the jump is plain statistics: a service is flagged when yesterday's cost is at least three standard deviations above its trailing 14-day mean, and the increase is at least $5.

def detect(series, z_threshold=3.0, min_delta_usd=5.0, min_history=7):
    ...
    if delta < min_delta_usd:
        continue   # a $0.02 -> $0.30 jump is a huge z-score but not worth a page

Only when something is flagged does the model get called, to explain the numbers: likely causes for that AWS service and the first thing to check. On a quiet day the bot makes no model call at all. Detection stays cheap, deterministic and unit-tested; the model does the part it's good at, which is writing.

If the model call fails, the bot posts the raw numbers instead. An alert without prose beats no alert.

2. Cache the translation, not the answer

The market-pulse screener turns a question into a query spec. That's the slow, paid step, and the same question always produces the same spec. So the spec is cached in Valkey, keyed by a hash of the normalised question:

PROMPT_VERSION = "v1"  # bump when the system prompt changes

def key(self, question):
    digest = hashlib.sha256(normalise(question).encode()).hexdigest()[:32]
    return f"spec:{PROMPT_VERSION}:{digest}"

Two details make this safe:

  • Results are never cached. The spec is re-run against live data every time, so a cached screen still shows current prices.
  • The prompt version is in the key. Change the prompt and old translations stop being used, without flushing anything by hand.

The cache is also treated as optional. If Valkey is down, requests still work; they just cost more.

3. Cache the prompt you send every time

Both the triage agent and the screener send a long, fixed system prompt on every call. Marking it for prompt caching means repeated calls read it from the provider's cache, which is billed at a fraction of the normal input price. The catch is that the prompt has to stay byte-for-byte identical, so anything that changes per request (the alert, the question) goes after it, in the user message.

4. Match the effort to the job

Not every call needs the model's deepest reasoning. I set it per feature:

  • Triage agent: high. It's investigating an incident over several turns, and a wrong root cause costs more than the tokens.
  • Screener: low. Filling a ten-field form is not hard.
  • Cost bot: low. It's explaining numbers it was handed.

The agent reads its setting from config (TRIAGE_EFFORT), so you can try a cheaper level and check it against the evals before keeping it.

5. Put a ceiling on every call

Limits are cost controls too. The agent stops after 12 turns. Tool output is capped at 20,000 characters, so one huge log can't fill the context. The screener's limit is capped at 100 rows. Each feature has a worst-case cost you can work out, which is what you want before it runs unattended.

The pattern underneath

All five come from the same rule I used everywhere in these projects: the model explains, code decides. Code finds the anomaly, writes the SQL, enforces the limits and decides when to call the model. The model gets the narrow job it's best at. That makes the system safer, and it makes the bill smaller and easier to predict.