Advanced about 5 h
The picture
01
Measure
cost per task
02
Cache
prompt, semantic
03
Route
cheap first
04
Shorten
outputs, prompts
05
Budget
alerts, caps
Think in unit economics
Per-request price is a misleading number. What matters is cost per successful task: total spend divided by tasks that actually met the quality bar, including retries, escalations and failed attempts.
def cost_per_success(runs):
total = sum(r["cost_usd"] for r in runs)
wins = sum(r["success"] for r in runs)
return total / wins if wins else float("inf")
A cheap model that succeeds 60 percent of the time can cost more per success than a pricier one at 95 percent.
Levers, in rough order of payoff
- Send less. Retrieve instead of dumping; trim history; compress tool outputs; remove prompt boilerplate.
- Reuse more. Prompt caching for the stable prefix; response caching for repeated requests; semantic caching for near-duplicates (with care).
- Route. Cheap model first, escalate when needed.
- Generate less. Output tokens cost several times input tokens: ask for concise formats, set
max_tokens, return structured fields instead of prose. - Skip the model. A deterministic fast path, a rule, a lookup, handles a surprising share of traffic.
- Batch non-urgent work for a discount.
- Self-host or distil only once volume justifies the operational cost.
A model cascade
def cascade(task, models=("small", "large"), threshold=0.8):
for i, name in enumerate(models):
out = call(name, task)
ok, conf = validate(out), confidence(out) # schema check, plus logprobs or a verifier
if ok and conf >= threshold:
return out, name
return out, models[-1] # best effort from the strongest model
Pick the confidence signal carefully: schema validity, a verifier, agreement across samples, or token log-probabilities. Tune the threshold on your evaluation set by plotting cost against accuracy and choosing the knee.
Caching, carefully
import hashlib, json
def cache_key(model, messages, params):
return hashlib.sha256(json.dumps([model, messages, params], sort_keys=True).encode()).hexdigest()
- Exact response cache: safe when temperature is 0 and inputs repeat.
- Semantic cache: returns an answer for a similar earlier question. Fast and cheap, but it can return a wrong answer for a question that only looks similar. Use a high similarity threshold, scope it per tenant, never cache personalised or time-sensitive answers, and measure the false-hit rate.
Latency
- Stream output; users judge speed by time to first token.
- Parallelise independent calls (retrieval and a classifier, several tool calls).
- Shorten the critical path: run guardrails and retrieval concurrently.
- Trim prompts: prefill time grows with input length.
- Set timeouts and hedged retries for the slow tail, and watch p95 and p99, not the mean.
Budgets that fail safe
class Budget:
def __init__(self, usd_limit, token_limit):
self.usd_left, self.tok_left = usd_limit, token_limit
def charge(self, usd, tokens):
self.usd_left -= usd; self.tok_left -= tokens
if self.usd_left < 0 or self.tok_left < 0:
raise BudgetExceeded("run stopped: budget exhausted")
Enforce a budget per run (so a looping agent stops), per user or tenant (so one customer cannot drain the account), and globally with alerts at 50, 80 and 100 percent. Prefer to refuse politely over silently degrading.
Watch for denial of wallet
Attackers or bugs can generate huge inputs and loops. Rate-limit, cap input size and tool-call count, and alert on cost anomalies.
Common mistakes
- Optimising price per token while accuracy quietly falls.
- A semantic cache with a loose threshold.
- Alerting on monthly invoices instead of live spend.
Exercises
- Build a two-model cascade and plot the cost-accuracy frontier on 100 test items.
- Add per-run and per-user budgets, and test that a looping agent is stopped.
You are done when you can…
- Compute cost per successful task, not only per request
- Implement a cascade that escalates to a stronger model on low confidence
- Set per-user and per-run budgets that fail safe