Sub topic 12
Controlling cost and latency
This chapter assumes you have read the earlier chapters. It uses the classify function, the LABELS dictionary, and the evaluate function from them. You should be comfortable with Python and with the idea of tokens. A token is a chunk of text, roughly three-quarters of a word in English, and it is the unit that LLM providers bill and that models process.
A classifier that works is not yet a classifier you can run at scale. Every message sent through the router costs money and takes time. This chapter shows how to estimate both, which levers reduce them, and how to check that a cheaper setup has not become a worse one.
Where cost and latency come from
Cost and latency come from the same place: how many tokens go in, how many come out, and how many calls you make.
- Input tokens are the prompt: instructions, label definitions, few-shot examples, and the message itself.
- Output tokens are the reply. Providers usually charge more per output token than per input token. Output is also slower, because the model generates it one token at a time.
- Calls multiply everything. A retry is a second full call, so it doubles the cost and the wait for that item.
Latency has two parts you can influence. The first is per-call time, which grows with the prompt length, the output length, and the model size. The second is the waiting that happens around calls: running items one after another, retrying, and queuing behind rate limits.
The prompt from the prompt-design chapter puts the fixed parts (instructions and labels) first and the message last. That ordering helps later in this chapter.
Estimate before you optimize
Write the estimate down as a function first. The numbers will show you which lever is worth pulling.
def estimate_daily_cost(
items_per_day,
input_tokens,
output_tokens,
price_in_per_million,
price_out_per_million,
retry_rate=0.0,
):
calls = items_per_day * (1 + retry_rate)
per_call = (
input_tokens * price_in_per_million
+ output_tokens * price_out_per_million
) / 1_000_000
return calls * per_call
# The prices are placeholders. Use your provider's current price list.
print(estimate_daily_cost(100_000, 400, 20, 0.50, 2.00))
print(estimate_daily_cost(100_000, 400, 20, 0.50, 2.00, retry_rate=0.05))This prints 24.0 and then 25.2. The 5 percent retry rate adds 5 percent to the cost. A prompt that frequently yields invalid JSON costs more than its per-call price suggests.
The main levers
| Lever | What it reduces | Risk |
|---|---|---|
| Rules before the LLM | Calls | Rules that are too broad misroute items |
| Cache for repeated text | Calls | Stale answers after the labels change |
| Smaller or cheaper model | Cost and per-call time | Lower accuracy on ambiguous cases |
| Shorter prompt | Input tokens | Lost definitions or examples hurt accuracy |
| Shorter output | Output tokens and time | No room for explanations or extra fields |
| Concurrency | Total wall-clock time | Rate limits, bursts of errors |
| Prompt prefix caching | Input cost and time on the fixed part | Provider-specific, and the prefix must stay identical |
Do not apply these blindly. Each one can lower accuracy, so you decide whether to keep it by running the evaluation from the evaluation chapter.
Skip the LLM when you can
The cheapest call is the one you do not make. The routing-strategies chapter introduced cascades. Here is the cost view of one: try cheap, high-precision rules first, and send only the leftovers to the model.
Here is a rules layer wrapped around classify:
import re
RULES = [
(re.compile(r"\b(refund|invoice|charged twice)\b", re.I), "billing"),
(re.compile(r"\b(reset (my )?password|can't log in)\b", re.I), "account"),
]
def rule_label(text):
for pattern, label in RULES:
if pattern.search(text):
return label
return None
def cascade(text, call_llm):
label = rule_label(text)
if label is not None:
return label, 1.0, "rule"
label, confidence = classify(text, call_llm)
return label, confidence, "llm"The source tag ("rule" or "llm") matters. Log it, so you can later measure what share of traffic each layer handles and how accurate each layer is.
Rules need the same scrutiny as the model. A rule for "refund" will misroute "I do not want a refund, I want the app fixed". Run the rules over your labeled set on their own and check that their precision is high before you trust them to skip the model. A rule that fires on 30 percent of traffic at 85 percent accuracy can cost more in rework than it saves in tokens.
Cache repeated messages
Support queues contain many near-duplicates: auto-generated emails, templated forms, and users who submit twice. Cache by a hash of normalized text.
import hashlib
def normalize(text):
return " ".join(text.lower().split())
def make_cached_classifier(call_llm):
cache = {}
def cached(text):
key = hashlib.sha256(normalize(text).encode("utf-8")).hexdigest()
if key in cache:
return cache[key]
result = classify(text, call_llm)
if result[1] > 0.0:
cache[key] = result
return result
return cachedThe if result[1] > 0.0 check is deliberate. classify returns ("other", 0.0) when it gives up after bad output. If you cached that, a temporary glitch would turn into a permanent wrong answer for that text. Cache only real results.
Two more cautions. First, a cache entry is only valid for the prompt and model that produced it, so include a prompt version in the key, or clear the cache when you change the labels or prompt. Second, an in-process dictionary disappears on restart and is not shared across workers. For production use an external store with an expiry time.
Run items concurrently
Calls to an LLM spend most of their time waiting on the network. Threads let you overlap that waiting, so 1,000 items do not take 1,000 times the latency of one.
from concurrent.futures import ThreadPoolExecutor
def classify_many(texts, call_llm, workers=8):
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(lambda t: classify(t, call_llm), texts))pool.map returns results in input order, so results[i] belongs to texts[i]. Concurrency improves throughput for batch work. It does not improve the latency of a single message, which is what a user waiting on a live chat feels.
Raising workers has a ceiling. Providers enforce rate limits, and exceeding them causes errors that trigger retries, which add load and cost. Start low and raise the number while watching the error rate. Use a timeout on every call, so one slow response cannot hold up a worker indefinitely.
Shorten what you send and what you get back
Output. Output tokens are the expensive and slow ones, so keep the reply small. The JSON format from the structured-output chapter is already compact. Avoid asking for a free-text explanation in production unless a human reads it. If you need a reason for debugging, request it only on the evaluation run, not on every call. Set a low maximum output length, so a misbehaving reply is cut off instead of billed in full.
Input. Count what each part of the prompt costs. Few-shot examples are the usual culprit, because they are repeated on every call. Test removing each example and see whether accuracy on your labeled set actually drops. Keep the examples that fix real errors and drop the ones that do not. Likewise trim long messages. A support email with a 3,000-word quoted thread rarely needs all of it, and truncating to the first few hundred words after removing quoted replies often loses nothing.
Prefix caching. Some providers discount or speed up the part of a prompt that is identical across calls. Your instructions, labels, and examples are identical every time, and the message comes last. Keep that order, and do not put timestamps or request IDs at the top of the prompt, since any change in the prefix breaks the match. Check your provider's documentation for the minimum prefix length and the discount.
Try a cheaper model, and measure it
A smaller model is often the largest single saving. Classification into a handful of clearly defined labels is an easier task than open-ended writing, so a smaller model may do well. Do not assume it. Run the same labeled set through both models:
def compare_models(examples, call_cheap, call_strong):
cheap_acc, cheap_conf = evaluate(examples, call_cheap)
strong_acc, strong_conf = evaluate(examples, call_strong)
print(f"cheap: {cheap_acc:.1%}")
print(f"strong: {strong_acc:.1%}")
return cheap_conf, strong_confCompare the confusion counts as well as the accuracy. A cheaper model that loses two points overall but fails mostly on the other label may be fine. One that starts confusing billing and account is not.
A related cascade uses the cheap model first and escalates to the stronger model only when confidence falls below a threshold. This works only if the cheap model's confidence is trustworthy, which you must check against the labeled set, as the confidence chapter described.
Decide with cost per correct item
Compare options by a single number: total cost divided by the number of correctly routed items. A cheap setup that sends 20 percent of items to the wrong queue pushes work onto humans, and human minutes usually cost far more than tokens. Include the handling cost of human triage in your comparison. A slightly pricier option with fewer escalations can be the cheaper system overall.
Latency budgets in practice
Decide what latency each path needs before you optimize:
- Interactive (a user waits for routing): use rules, the cache, a small model, and a short output. Set a timeout and a fallback, such as sending the item to
human-triageif the call takes too long. - Batch (overnight backlog): latency per item does not matter. Use concurrency, a cheaper model, and batch endpoints if your provider offers a discount for them.
Retries deserve a limit in both modes. The default of two attempts in classify caps the worst case at twice the per-call cost and time. Adding more attempts rarely helps, since a prompt that fails twice will often fail again, and each extra attempt adds delay.
Exercise
Your router handles 100,000 messages per day. Each call uses 400 input tokens and 20 output tokens. Prices are $0.50 per million input tokens and $2.00 per million output tokens. Rules handle 40 percent of messages without calling the model. What is the daily model cost after adding the rules, and why should you still evaluate the rules separately?
Show answer
Calls drop to 60,000. Cost per call is (400 × 0.50 + 20 × 2.00) / 1,000,000 = $0.00024. So the daily cost is 60,000 × 0.00024 = $14.40, down from $24.00. You should still evaluate the rules separately because they decide 40 percent of traffic without the model. If their precision is low, they misroute many items, and the cost of fixing those errors can exceed the $9.60 saved.
Exercise
A cached classifier stores every result, including the ("other", 0.0) fallback returned when the model gave invalid JSON twice. What goes wrong, and what is the fix?
Show answer
A temporary failure becomes permanent for that text, because every later identical message gets the cached fallback without a new model call. The fix is to cache only results with confidence above zero, as in make_cached_classifier, and to include a prompt version in the key so old entries do not survive a prompt change.