Sub topic 12
Controlling cost and latency
This chapter assumes you have the classify function from the earlier chapters and know that LLM APIs bill per token. It shows where the cost and delay of a classifier come from and how to reduce both without losing accuracy.
Where the cost comes from
Each call costs roughly this:
cost = input_tokens × input_price + output_tokens × output_priceIn a classifier, the input is the instructions, label definitions, few-shot examples, and the message. The output is a short JSON object. The input is usually much larger than the output, so the fixed part of the prompt is repeated on every call.
Latency works the same way. It grows with input length and, more steeply, with the number of output tokens. Retries add a full extra call each time.
The main levers
| Lever | Effect | Risk |
|---|---|---|
| Shorter label descriptions and fewer examples | Fewer input tokens | Accuracy may drop, so re-run evaluation |
| Terse output format (label and confidence only) | Fewer output tokens | None if you do not need explanations |
| Smaller, cheaper model | Lower price and faster responses | More errors on ambiguous items |
| Rules before the LLM | Skips the call for easy items | Rules can be wrong with full certainty |
| Caching repeated messages | No call for duplicates | Stale answers if labels change |
| Fewer retries (`max_attempts`) | Lower worst-case cost | More fallbacks to `other` |
Also set a maximum output length on your API call. A reply that rambles costs money and time, and it will fail JSON parsing anyway.
A cascade with a cache
A cascade tries the cheapest method first and moves to the next only when needed. The code below checks a cache, then regular-expression rules, then the LLM. It uses classify from the validation chapter.
import hashlib
import re
RULES = [
(re.compile(r"\b(refund|invoice|charged twice)\b", re.I), "billing"),
(re.compile(r"\b(reset (my )?password|cannot log in|can't log in)\b", re.I), "account"),
]
_cache = {}
def rule_label(text):
for pattern, label in RULES:
if pattern.search(text):
return label
return None
def classify_cheaply(text, call_llm):
key = hashlib.sha256(text.strip().lower().encode("utf-8")).hexdigest()
if key in _cache:
return _cache[key]
label = rule_label(text)
if label is not None:
result = (label, 1.0, "rule")
else:
label, confidence = classify(text, call_llm)
result = (label, confidence, "llm")
_cache[key] = result
return resultThe third value in the result records which stage answered. You need it to measure savings.
Check that savings do not cost accuracy
A cheaper pipeline is only better if accuracy holds. Run the evaluate function from the evaluation chapter on the same labeled set before and after each change. Compare accuracy and the confusion matrix, not only the total cost. A rule that sends every message containing "refund" to billing will misroute "Your refund policy page has a bug."
Track these numbers in production:
- The share of items answered by cache, rules, and the LLM.
- Average and 95th percentile latency per stage.
- Average tokens per LLM call.
- The retry rate.
A rising retry rate is a cost problem and also a sign that the prompt or the model output format has drifted.
Exercise
Exercise
A system handles 10,000 messages per day. Rules answer 40% of them. The rest go to the LLM at $0.002 per call. What is the daily LLM cost with and without the rules? What does a 25% cache hit rate on the remaining messages do to the cost?
Show answer
Without rules, 10,000 × $0.002 = $20 per day. With rules, 6,000 messages reach the LLM, so 6,000 × $0.002 = $12 per day. A 25% cache hit rate on those 6,000 removes 1,500 calls, leaving 4,500 calls, or $9 per day.