Howwise RSS
AI & Automation9 min read

Reduce LLM API Costs: An Impact-Ordered Playbook

Short answer

To reduce LLM API costs, measure cost per conversation first, then apply levers in order of impact: prompt caching, response caching, model routing, history management, prompt trimming and output limits. Gate each change with a quality eval.

Key takeaways
  • Input tokens dominate chatbot spend because the system prompt, retrieved context and full history are resent every turn, so cumulative cost grows roughly with the square of conversation length.
  • Log input, output, cached tokens, model and latency per request, then find the top 10% of conversations driving spend before changing anything.
  • Prompt caching, response caching and model routing usually give the largest savings, often 30 to 60% each on the traffic they apply to.
  • Ship one change at a time behind a golden set of 100 to 300 real conversations, and track resolution rate and escalations next to cost.
  • Per-user rate limits, max turns and retry caps prevent a single bot or runaway agent from wiping out your savings.

Why does my LLM API bill keep growing?

In a chatbot, each turn sends the system prompt, tool definitions, retrieved context and the entire prior conversation again. Turn 1 is cheap. Turn 10 re-reads nine earlier exchanges. The cost of a whole conversation is the sum of every turn's input, so it grows roughly with the square of the number of turns.

Output tokens are billed at several times the per-token rate of input tokens, commonly 3x to 5x. But a typical answer is a few hundred tokens while the input is thousands, so input usually still dominates the bill. Long answers and reasoning-style outputs are the exception.

The formula to keep in mind, per request: cost = (uncached_input x input_price) + (cached_input x cached_price) + (cache_write x write_price, where the provider charges one) + (output x output_price). Every lever below attacks one of those terms: fewer tokens, cheaper tokens, or fewer calls.

How do I measure cost per conversation before changing anything?

Optimizing without a baseline means you cannot tell a real saving from a quiet quality loss. Log one row per model call, tagged with a conversation ID, a user ID (hashed), a feature or prompt name, and the model. Most provider responses include a usage object with input, output and cached token counts, so you only need to record it.

Providers disagree on what the input count means. OpenAI-style usage (`prompt_tokens`) includes cached tokens, so you subtract them to get the fresh part. Anthropic's `input_tokens` excludes cache reads (`cache_read_input_tokens`) and cache writes (`cache_creation_input_tokens`), which are reported separately and priced differently. The code below converts both into one convention: `fresh` never includes cached or cache-write tokens.

Then aggregate. Compute cost per conversation, and also cost per resolved conversation (cost divided by conversations the user did not escalate or abandon). The second number stops you from celebrating cheap conversations that simply failed.

Sort conversations by total cost and look at the top 10%. Long-tail conversations, a single oversized prompt, a looping agent or a spam bot often explain a majority of spend, and fixing them beats tuning the average.

import time, json

PRICE = {  # USD per 1M tokens: fill in your own current rates
    "big":   {"in": 3.00, "cached": 0.30,  "write": 3.75, "out": 15.00},
    "small": {"in": 0.15, "cached": 0.015, "write": 0.15, "out": 0.60},
}

def normalize_usage(provider, usage):
    """One convention for every provider:
    fresh, cached and cache_write are DISJOINT counts, so
    total input = fresh + cached + cache_write."""
    if provider == "anthropic":
        # input_tokens EXCLUDES cache reads and cache writes
        return {"fresh": usage["input_tokens"],
                "cached": usage.get("cache_read_input_tokens", 0),
                "cache_write": usage.get("cache_creation_input_tokens", 0),
                "out": usage["output_tokens"]}
    # OpenAI-style: prompt_tokens INCLUDES cached tokens, so subtract them
    cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
    return {"fresh": usage["prompt_tokens"] - cached,
            "cached": cached,
            "cache_write": 0,
            "out": usage["completion_tokens"]}

def log_call(conv_id, feature, provider, model, usage, started):
    p = PRICE[model]
    u = normalize_usage(provider, usage)
    cost = (u["fresh"] * p["in"] + u["cached"] * p["cached"]
            + u["cache_write"] * p["write"] + u["out"] * p["out"]) / 1e6
    print(json.dumps({
        "conv": conv_id, "feature": feature, "model": model,
        "fresh": u["fresh"], "cached": u["cached"],
        "cache_write": u["cache_write"], "out": u["out"],
        "latency_ms": int((time.time() - started) * 1000),
        "cost_usd": round(cost, 6)}))
Tip: Map usage fields once in a wrapper like normalize_usage, because names and meanings differ by provider: subtracting cached tokens from Anthropic's input_tokens gives a wrong, sometimes negative, fresh count. Keep the price table in config, not code, so a price change does not rewrite history.

Which lever should I pull first to reduce LLM API costs?

To reduce LLM API costs efficiently, match the lever to the cost driver your logs revealed. The savings ranges below are rough planning figures that depend on your traffic mix, not guarantees. Measure each one on your own data.

LeverCost driver it fixesTypical saving on affected spendEffortQuality risk
Provider prompt cachingLarge static prefix resent every turn30-60% of input costLowNone
Response cache (exact + semantic)Repeated FAQ-style questionsUp to 100% on hits; 10-40% hit rate is commonMediumMedium (stale or wrong matches)
Model routing / cascadeSimple intents on an expensive model40-80% on routed trafficMediumMedium
History window + rolling summaryLong conversations, quadratic growth20-50% on long chatsMediumMedium (lost details)
Prompt and RAG trimmingBloated system prompt, 10-20 chunks10-30% of inputLowLow to medium
Output limits, concise styleVerbose answers, needless reasoning10-30% of output costLowMedium (truncation)
Batch APIOffline jobs: tagging, summaries, evalsAbout 50% on those jobsLowNone
Rules, buttons, deflectionTrivial queries that need no LLM100% on deflected turnsLowLow

How do prompt caching, response caching and routing work?

Provider prompt caching bills a repeated prefix at a steep discount, roughly 50 to 90% off depending on provider. It matches on an exact prefix, so order matters: static content first (system prompt, tool definitions, few-shot examples), then conversation history, then the variable parts (retrieved chunks, the new user message). Caches also have a minimum prefix size (often around 1,000 tokens) and a short TTL measured in minutes, refreshed on each hit. Some providers, Anthropic for example, also charge a premium to write a cache entry, so a prefix that is never reused can cost more than no caching.

The classic cache-breaking mistakes are a timestamp, request ID, user name or A/B flag near the top of the prompt, tool definitions that are reordered between calls, and injecting RAG chunks before the history. Any change in an early token invalidates everything after it. Verify by checking the cached token count in the usage object, not by assuming.

Response caching skips the model entirely. An exact-match cache keyed on a normalized question (lowercased, trimmed) is safe and cheap. A semantic cache embeds the question and returns a stored answer if cosine similarity passes a threshold, usually 0.92 to 0.97. Start high, because a false hit serves a confidently wrong answer.

Never cache personalized answers (order status, account data) or time-sensitive ones (prices, availability). Add a TTL and tag each entry with the source document version, so editing a doc evicts the answers built from it.

def cached_answer(question, user_ctx):
    if user_ctx.personalized or is_time_sensitive(question):
        return None
    key = normalize(question)
    if hit := exact_cache.get(key):
        return hit
    vec = embed(key)
    match = vector_index.nearest(vec)       # (answer, score, doc_version)
    if match and match.score >= 0.95 \
       and match.doc_version == current_doc_version(match.topic):
        return match.answer
    return None
Warning: Tune the semantic threshold against labeled pairs of questions that look alike but need different answers, such as 'cancel my plan' versus 'cancel my order'. A threshold chosen by feel is the most common source of wrong cached answers.

How do I reduce token usage in a chatbot without losing quality?

Model routing sends easy work to a small model and escalates hard work, with price gaps between tiers often 10x to 50x. Route by rules first (intent labels, known FAQ topics), then a small classifier, then confidence: let the cheap model answer, and escalate if it returns low confidence, fails schema validation or says it lacks context. This cascade pays for itself when most traffic is easy, but each escalation costs both calls, so track the escalation rate.

Then shrink what remains, in this order:

  1. Window the history: keep the last 4 to 8 turns verbatim and replace older turns with a rolling summary written by a cheap model. Store hard facts (names, order numbers, constraints, decisions) in a separate structured memory that is always included, because summaries lose exact identifiers.
  2. Trim RAG: retrieve top 3 to 5 chunks instead of 10 to 20, sized at a few hundred tokens each, with a reranker if recall drops. Strip HTML, navigation and boilerplate before indexing.
  3. Tighten the system prompt: dedupe repeated instructions, cut examples that teach the same behavior, and keep two or three diverse few-shot examples instead of ten. Prefer compact formats over verbose prose.
  4. Limit output: instruct concise answers, use structured output with short keys for machine-read results, add stop sequences, and skip chain-of-thought for simple classification or extraction. Set max_tokens only as a safety cap well above normal length, since cutting an answer mid-sentence is worse than paying for it.
  5. Remove round trips: merge tool calls that always occur together, and cap agent loops and retries (for example 5 steps, 2 retries) so a failure cannot spiral.
  6. Move non-urgent jobs such as nightly summaries, tagging and eval runs to the batch API for about 50% off, and use a cheaper embedding model if retrieval quality holds on your test set.

What does a before and after cost per conversation look like?

Illustrative assumptions: 8 turns per conversation, 1,500 token system prompt and tools, 2,000 tokens of RAG per turn (10 chunks), 60 token user messages, 250 token answers. Prices are example values: $1 per 1M input tokens, $0.10 cached, $4 per 1M output.

Baseline input is 8 x 3,500 static tokens, plus history of 310 x (0+1+...+7) = 8,680, plus 480 user tokens, so 37,160 input tokens. Output is 2,000 tokens. Cost: $0.0372 + $0.0080 = $0.0452 per conversation.

StepWhat changedCost per conversationCumulative saving
BaselineNone$0.04520%
Prompt cachingSystem prompt and history cached (about 20,700 tokens at 10% price), RAG moved after history$0.026641%
RAG trim10 chunks to 4 (saves 9,600 tokens)$0.017062%
Routing40% of turns go to a model 20x cheaper$0.010577%
Response cache15% of conversations answered from cache$0.008980%
Tip: Note the order. Caching and routing carry most of the saving here, while history summarization barely matters at 8 turns. On conversations of 30 or more turns the quadratic history term dominates and windowing moves up the list. Rebuild this table with your own logged numbers.

How do I prove quality did not drop, and keep spend under control?

Build a golden set of 100 to 300 real, anonymized conversations that cover your intents, including hard cases, long conversations and known failures. Replay them through the current and candidate setups, or run the candidate in shadow mode on live traffic and compare outputs without showing them to users.

Score with an LLM judge using a fixed rubric (correct, grounded in the retrieved sources, complete, tone), a judge model at least as strong as your production model, and pairwise comparison with randomized order to limit position bias. Spot check 10 to 20% by hand, especially every case the judge rated worse.

Track quality metrics beside cost: resolution rate, thumbs-down rate, escalation to human, hallucination rate on a sampled audit, and cost per resolved conversation. A saving that raises escalations usually costs more than it saves.

Roll out one change at a time, to 5 to 10% of traffic first, with a feature flag that rolls back instantly. Changing three levers at once makes any regression impossible to attribute.

Add guardrails so the bill cannot spike again: per-user and per-IP rate limits, a maximum turns per conversation, daily spend alerts at fixed thresholds, a hard monthly cap per tenant, and bot detection or CAPTCHA on public endpoints. Agent loops need step and retry limits, as noted above. For deeper background, see our related articles on the token cost of conversation history and RAG versus fine-tuning costs.

Warning: Do not ship cache or routing changes without the eval gate. These are the levers most likely to silently serve wrong answers, and the savings look great right up until users complain.

Common questions

How much can I realistically cut my LLM bill?

Many production chatbots cut 40 to 80% by combining prompt caching, routing and trimming, but results depend on how repetitive your traffic is and how much of it is simple. Compute the figure from your own logs rather than assuming a benchmark.

Is prompt caching the same as semantic caching?

No. Prompt caching is a provider feature that discounts a repeated exact prefix but still runs the model and produces a fresh answer. Semantic caching is your own layer that returns a stored answer for similar questions and skips the model call completely.

Will a cheaper model make my chatbot worse?

Only on the queries it cannot handle. Route by intent, test the small model on the golden set per intent, and escalate on low confidence or failed validation. Many FAQ, classification and extraction tasks show no measurable difference.

Should I fine-tune to save money?

Fine-tuning a small model on your task can replace a long prompt and few-shot examples, but it adds training, evaluation and maintenance cost. Try caching, routing and trimming first, since they need no training data.

How often should I recheck costs?

Review a cost dashboard weekly and alert on daily spend. Re-run the golden set whenever you change a prompt, model or retrieval setting, because provider prices and model behavior also change over time.

Related topics:llmapi costsprompt cachingchatbotmodel routing