StackPractices
advanced By Mathias Paulenko

Complete Guide to LLM Cost Optimization

Cut LLM costs in production: model routing, prompt compression, caching, Batch API, token budgets and cost monitoring with real numbers.

Introduction

The first month an LLM feature goes live, the invoice usually tells a story: a classification endpoint that could run on gpt-4o-mini billed every request at gpt-4o prices, a FAQ bot answering the same forty questions as if they were new each time, and a nightly summarization job paying full price for work nobody was waiting on. None of that’s a bug — it’s just money left on the table because nobody designed for cost.

LLM cost optimization means lowering the price per useful token without degrading what users get back. Every optimization in this guide moves exactly one of three dials: which model answers (routing), how many tokens you send and receive (compression, budgets), and how often you call the model at all (caching, batch).

The levers below are ordered roughly by effort-to-savings ratio. Most teams recover 40-80% of spend with the first three; the rest is tuning.

The Cost Levers at a Glance

LeverTypical savingsApply whenImplementation cost
Model routing40-70% of spendMixed task complexityLow — a classifier + routing table
Exact-match caching20-60% on repeated queriesFAQ, docs lookup, idempotent tasksLow — hash + Redis
Batch API50% on eligible volumeNon-interactive jobs (24h OK)Low — JSONL upload pipeline
Semantic caching30-80% on paraphrasesUsers rephrase the same questionsMedium — embeddings + vector index
Prompt compression15-40% of input tokensBloated system prompts, few-shot bloatMedium — careful, affects quality
Token budgetsPrevents runaway spendAlways — cost control, not savingsLow — counter + cutoff
Model cascading20-50% of spendCheap-first with quality fallbackMedium — confidence detection

Savings stack multiplicatively: routing simple traffic to mini (≈85% cheaper per request), caching half the remainder, and batching offline work gets a typical mixed workload into the 50-90% reduction range — with model routing and caching doing most of the work.

flowchart diagram: req([Request

Cost Breakdown

Every LLM invoice decomposes into a few line items:

ComponentWhat it coversWhat drives it up
Input tokensPrompt + context sent to the modelBloated prompts, full chat history, big retrieval chunks
Output tokensTokens the model generatesNo max_tokens, verbose persona, unneeded detail
Embedding tokensText vectorized for search/cacheRe-embedding unchanged docs, oversized chunks
Fine-tuningTraining compute + hosted model premiumOnly pays off at steady high volume of one task
Image/audioPer-image or per-minute billingUncompressed images, full-file transcription

Reference pricing per 1M tokens (check OpenAI pricing and Anthropic pricing — they change often):

ModelInputOutputOutput/Input ratio
gpt-4o$2.50$10.004×
gpt-4o-mini$0.15$0.604×
claude-sonnet-4-5$3.00$15.005×
o1$15.00$60.004×
text-embedding-3-small$0.02——
text-embedding-3-large$0.13——

Two structural facts matter more than any price. Output tokens cost 4-5× input tokens on every model — so max_tokens caps and “be concise” system prompts save disproportionately. And gpt-4o-mini is ~17× cheaper than gpt-4o on input — the whole routing strategy is deciding which requests actually need the expensive model.

Model Routing

Smart Model Selection

The single biggest lever: don’t pay flagship prices for mini-level work. A router inspects the request and picks the cheapest model that can handle it:

from openai import OpenAI
import re

client = OpenAI()

class ModelRouter:
    def __init__(self):
        self.routing_rules = [
            {"pattern": r"^(yes|no|true|false|\d+)$", "model": "gpt-4o-mini"},
            {"pattern": r"^(summarize|classify|extract)", "model": "gpt-4o-mini"},
            {"pattern": r"^(write|create|generate|code|debug)", "model": "gpt-4o"},
            {"pattern": r"^(analyze|reason|compare|evaluate)", "model": "gpt-4o"},
        ]
        self.default_model = "gpt-4o-mini"

    def select_model(self, prompt: str) -> str:
        prompt_lower = prompt.lower().strip()

        for rule in self.routing_rules:
            if re.search(rule["pattern"], prompt_lower):
                return rule["model"]

        # Token-based routing: short prompts use mini
        estimated_tokens = len(prompt) // 4
        if estimated_tokens < 100:
            return "gpt-4o-mini"

        return self.default_model

    def complete(self, prompt: str, **kwargs) -> dict:
        model = self.select_model(prompt)
        response = client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            **kwargs
        )
        return {
            "content": response.choices[0].message.content,
            "model": model,
            "cost": self._calculate_cost(
                model, response.usage.prompt_tokens, response.usage.completion_tokens
            )
        }

    def _calculate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
        pricing = {
            "gpt-4o": {"input": 2.50, "output": 10.00},
            "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        }
        p = pricing.get(model, {"input": 0, "output": 0})
        return (input_tokens / 1e6 * p["input"]) + (output_tokens / 1e6 * p["output"])

router = ModelRouter()

Regex routing is the honest starting point — it handles the obvious cases (“summarize this”, “classify”) and short prompts. Once traffic justifies it, upgrade the classifier to a mini-model or embeddings similarity against labeled examples. Whatever you do, log result['model'] per request: the cost tracking template shows how to attribute spend per route.

The trade-off is quality on borderline inputs. The FAQ covers measuring it; the pattern that keeps quality safe while still saving is cascading — the LLM Router Pattern covers the full classifier ladder, thresholds, and quality-gated escalation.

Cascading Model Fallback

Instead of classifying upfront, try the cheap model first and escalate only when it signals uncertainty:

class CascadingRouter:
    """Try cheap model first, fall back to expensive if quality is insufficient."""

    def __init__(self, confidence_threshold: float = 0.7):
        self.confidence_threshold = confidence_threshold
        self.client = OpenAI()

    def complete(self, prompt: str) -> dict:
        # Try gpt-4o-mini first
        response = self.client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "Answer the question. If you are not confident, say 'UNCERTAIN'."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.0
        )
        answer = response.choices[0].message.content

        if "UNCERTAIN" not in answer:
            return {"answer": answer, "model": "gpt-4o-mini",
                    "cost": self._cost("gpt-4o-mini", response.usage)}

        # Fall back to gpt-4o
        response = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.0
        )
        return {"answer": response.choices[0].message.content, "model": "gpt-4o",
                "cost": self._cost("gpt-4o", response.usage)}

    def _cost(self, model, usage):
        pricing = {"gpt-4o": (2.50, 10.00), "gpt-4o-mini": (0.15, 0.60)}
        p = pricing.get(model, (0, 0))
        return (usage.prompt_tokens / 1e6 * p[0]) + (usage.completion_tokens / 1e6 * p[1])

Cascading pays the full cost of the failed attempt plus the retry — it only wins if the cheap model succeeds most of the time. Measure the escalation rate: if mini punts on >40% of traffic, you’re paying double calls and should route those categories directly. The UNCERTAIN sentinel is crude but reliable at temperature=0; structured outputs with a confidence field are the cleaner version.

Prompt Compression

Token Reduction Techniques

Most production prompts accumulate filler — stacked courtesies, repeated instructions, few-shot examples nobody re-evaluated:

class PromptOptimizer:
    @staticmethod
    def compress_system_prompt(prompt: str) -> str:
        """Remove redundancy and verbosity from system prompts."""
        fillers = [
            "You are a helpful assistant.",
            "Please note that",
            "It is important to",
            "You should always",
            "Make sure to",
        ]
        for filler in fillers:
            prompt = prompt.replace(filler, "")

        # Collapse whitespace
        import re
        prompt = re.sub(r'\s+', ' ', prompt).strip()
        return prompt

    @staticmethod
    def truncate_context(context: str, max_tokens: int = 2000) -> str:
        """Truncate context to fit within token budget."""
        max_chars = max_tokens * 4  # rough estimate: 1 token ≈ 4 chars
        if len(context) <= max_chars:
            return context
        keep_start = max_chars // 2
        keep_end = max_chars // 2
        return context[:keep_start] + "\n[...truncated...]\n" + context[-keep_end:]

# Before: 500-token system prompt
long_prompt = """
You are a helpful assistant. You should always be polite and professional.
Please note that it is important to provide accurate information.
Make sure to format your responses clearly. You should always cite sources
when possible. It is important to be concise but thorough. Please note that
you should avoid making assumptions.
"""

optimized = PromptOptimizer.compress_system_prompt(long_prompt)

Two cautions. Compression isn’t free savings — cutting few-shot examples or instructions can quietly degrade output quality, so run the change through your eval set before shipping. And context truncation like the middle-cut above is a blunt instrument: for retrieval content, the better fix is fetching fewer, better chunks — the RAG production guide covers that trade-off.

Caching Strategies

The only call cheaper than gpt-4o-mini is the one you never make. Two cache flavors cover most traffic.

Exact Match Cache

Identical inputs get identical outputs — hash the request and short-circuit:

import hashlib
import json
from datetime import datetime, timedelta

class LLMCache:
    def __init__(self, ttl_hours: int = 24):
        self.cache: dict[str, dict] = {}
        self.ttl = timedelta(hours=ttl_hours)

    def _key(self, model: str, messages: list, **kwargs) -> str:
        data = json.dumps({"model": model, "messages": messages, **kwargs}, sort_keys=True)
        return hashlib.sha256(data.encode()).hexdigest()

    def get(self, model: str, messages: list, **kwargs) -> str | None:
        key = self._key(model, messages, **kwargs)
        if key in self.cache:
            entry = self.cache[key]
            if datetime.now() - entry["timestamp"] < self.ttl:
                return entry["response"]
            del self.cache[key]
        return None

    def set(self, model: str, messages: list, response: str, **kwargs):
        key = self._key(model, messages, **kwargs)
        self.cache[key] = {"response": response, "timestamp": datetime.now()}

cache = LLMCache(ttl_hours=24)

The dict version is fine for a single worker; Redis SETEX gives you the same semantics shared across replicas — the application-level caching guide covers the production version. Exact cache wins on repeated queries (FAQ bots, doc lookups, idempotent transforms) and does nothing for free-form chat.

Semantic Cache

Similar questions — “what’s your refund policy?” vs “how do I get my money back?” — should hit the same answer:

import numpy as np
from openai import OpenAI

client = OpenAI()

class SemanticCache:
    def __init__(self, similarity_threshold: float = 0.95, max_entries: int = 1000):
        self.entries: list[dict] = []
        self.threshold = similarity_threshold
        self.max_entries = max_entries

    def _embed(self, text: str) -> np.ndarray:
        response = client.embeddings.create(
            model="text-embedding-3-small",
            input=text
        )
        return np.array(response.data[0].embedding)

    def get(self, query: str) -> str | None:
        query_embedding = self._embed(query)
        for entry in self.entries:
            similarity = np.dot(query_embedding, entry["embedding"]) / (
                np.linalg.norm(query_embedding) * np.linalg.norm(entry["embedding"])
            )
            if similarity >= self.threshold:
                return entry["response"]
        return None

    def set(self, query: str, response: str):
        self.entries.append({
            "query": query,
            "response": response,
            "embedding": self._embed(query)
        })
        if len(self.entries) > self.max_entries:
            self.entries.pop(0)  # evict oldest

The in-memory list scans every entry per request — right for a thousand entries, wrong for a hundred thousand. Past that point, store the embeddings in a vector index (pgvector, Redis Stack, or a dedicated store) and let it do approximate nearest neighbor — the vector databases guide compares the options and the embedding cache pattern covers threshold tuning. Set the threshold too low and users get answers to questions they didn’t ask — that’s worse than a cache miss.

Batch API for Cost Reduction

Anything that doesn’t need an answer in seconds — nightly summaries, bulk classification, backfills — should run on the provider’s batch API: 50% off in exchange for 24-hour turnaround.

import json

class BatchProcessor:
    """OpenAI Batch API: 50% cost reduction on non-time-sensitive workloads."""

    def __init__(self, client):
        self.client = client

    def prepare_batch(self, prompts: list[str], model: str = "gpt-4o-mini") -> str:
        """Prepare batch file and upload."""
        requests = []
        for i, prompt in enumerate(prompts):
            requests.append({
                "custom_id": f"task-{i}",
                "method": "POST",
                "url": "/v1/chat/completions",
                "body": {"model": model, "messages": [{"role": "user", "content": prompt}]}
            })

        filename = "batch_requests.jsonl"
        with open(filename, "w") as f:
            for req in requests:
                f.write(json.dumps(req) + "\n")

        file = self.client.files.create(file=open(filename, "rb"), purpose="batch")
        return file.id

    def submit_batch(self, file_id: str) -> str:
        batch = self.client.batches.create(
            input_file_id=file_id,
            endpoint="/v1/chat/completions",
            completion_window="24h"
        )
        return batch.id

    def get_results(self, batch_id: str) -> list[dict]:
        batch = self.client.batches.retrieve(batch_id)
        if batch.status != "completed":
            return []

        results = []
        content = self.client.files.content(batch.output_file_id)
        for line in content.text.strip().split("\n"):
            result = json.loads(line)
            if not result.get("error"):
                results.append({
                    "custom_id": result["custom_id"],
                    "content": result["response"]["body"]["choices"][0]["message"]["content"]
                })
        return results

# Process 1000 sentiment classifications at 50% cost
# file_id = processor.prepare_batch(prompts, model="gpt-4o-mini")
# batch_id = processor.submit_batch(file_id)
# results = processor.get_results(batch_id)  # available within 24h

The catch: results arrive up to 24 hours later with no SLA, and failures are per-line, not per-batch — always diff custom_ids returned vs submitted. The Batch API docs have the current limits; the OpenAI API mastery guide covers polling and error handling in more depth.

Token Management

Token Counting

You can’t optimize what you don’t measure. tiktoken counts exactly what the model will see:

import tiktoken

class TokenManager:
    def __init__(self, model: str = "gpt-4o"):
        self.encoder = tiktoken.encoding_for_model(model)

    def count_tokens(self, text: str) -> int:
        return len(self.encoder.encode(text))

    def count_messages(self, messages: list[dict]) -> int:
        """Count tokens in a list of messages."""
        total = 0
        for msg in messages:
            total += 4  # message overhead tokens
            for key, value in msg.items():
                total += len(self.encoder.encode(str(value)))
                if key == "name":
                    total -= 1
        total += 2  # conversation overhead
        return total

    def truncate_to_budget(self, text: str, max_tokens: int) -> str:
        tokens = self.encoder.encode(text)
        if len(tokens) <= max_tokens:
            return text
        return self.encoder.decode(tokens[:max_tokens]) + "..."

    def estimate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
        pricing = {
            "gpt-4o": {"input": 2.50, "output": 10.00},
            "gpt-4o-mini": {"input": 0.15, "output": 0.60},
            "o1": {"input": 15.00, "output": 60.00},
            "o1-mini": {"input": 3.00, "output": 12.00},
        }
        p = pricing.get(model, {"input": 0, "output": 0})
        return (input_tokens / 1e6 * p["input"]) + (output_tokens / 1e6 * p["output"])

tm = TokenManager()

Count before sending, not after — count_messages tells you the real input cost including per-message overhead (the len(text)//4 heuristic underestimates code and non-English text by 20-30%). The tiktoken cookbook has the per-model overhead constants.

Budget Control

Per-Request Budget

Cost control isn’t optimization — it’s the guardrail that stops a bug or a spike from becoming an invoice event. Distinguish two behaviors: soft alerts (log, warn, notify) at 70-80% of budget, and hard stops (reject the request or degrade to cache) at 100%:

class BudgetController:
    def __init__(self, daily_budget: float = 10.0, alert_at: float = 0.8):
        self.daily_budget = daily_budget
        self.alert_at = alert_at
        self.spent: dict[str, float] = {}  # date -> amount
        self.pricing = {
            "gpt-4o": {"input": 2.50, "output": 10.00},
            "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        }

    def _today(self) -> str:
        from datetime import date
        return date.today().isoformat()

    def check(self, estimated_cost: float) -> str:
        """Returns 'ok', 'alert' (over threshold) or 'stop' (over budget)."""
        today = self._today()
        projected = self.spent.get(today, 0) + estimated_cost
        if projected > self.daily_budget:
            return "stop"
        if projected > self.daily_budget * self.alert_at:
            return "alert"
        return "ok"

    def record(self, model: str, input_tokens: int, output_tokens: int):
        p = self.pricing.get(model, {"input": 0, "output": 0})
        cost = (input_tokens / 1e6 * p["input"]) + (output_tokens / 1e6 * p["output"])
        today = self._today()
        self.spent[today] = self.spent.get(today, 0) + cost

    def report(self) -> dict:
        today = self._today()
        return {
            "daily_budget": self.daily_budget,
            "spent_today": self.spent.get(today, 0),
            "remaining": max(0, self.daily_budget - self.spent.get(today, 0)),
        }

budget = BudgetController(daily_budget=10.0)

status = budget.check(0.02)
if status == "stop":
    # Hard stop: serve from cache or return a graceful degraded response
    pass
elif status == "alert":
    # Soft alert: log/notify but continue
    pass

In production, back this with a persistent store (the in-memory dict resets on deploy) and a kill-switch that degrades to cached answers instead of 500s — users prefer a stale answer over an error.

Cost Monitoring Dashboard

import time
import json
from dataclasses import dataclass

@dataclass
class CostMetric:
    timestamp: float
    model: str
    input_tokens: int
    output_tokens: int
    cost: float
    endpoint: str
    user_id: str = ""

class CostMonitor:
    def __init__(self):
        self.metrics: list[CostMetric] = []

    def record(self, model: str, input_tokens: int, output_tokens: int,
               endpoint: str = "chat", user_id: str = ""):
        pricing = {
            "gpt-4o": (2.50, 10.00),
            "gpt-4o-mini": (0.15, 0.60),
            "o1": (15.00, 60.00),
        }
        p = pricing.get(model, (0, 0))
        cost = (input_tokens / 1e6 * p[0]) + (output_tokens / 1e6 * p[1])
        self.metrics.append(CostMetric(
            timestamp=time.time(), model=model,
            input_tokens=input_tokens, output_tokens=output_tokens,
            cost=cost, endpoint=endpoint, user_id=user_id
        ))

    def summary(self, hours: int = 24) -> dict:
        cutoff = time.time() - hours * 3600
        recent = [m for m in self.metrics if m.timestamp >= cutoff]
        if not recent:
            return {"total_cost": 0, "total_calls": 0}
        by_model = {}
        by_user = {}
        for m in recent:
            by_model[m.model] = by_model.get(m.model, 0) + m.cost
            if m.user_id:
                by_user[m.user_id] = by_user.get(m.user_id, 0) + m.cost
        return {
            "period_hours": hours,
            "total_cost": sum(m.cost for m in recent),
            "total_calls": len(recent),
            "avg_cost_per_call": sum(m.cost for m in recent) / len(recent),
            "by_model": by_model,
            "by_user": by_user,
        }

monitor = CostMonitor()

This in-memory version is the shape of the data; push the same fields to your real metrics stack (Prometheus counters + per-model cost gauge) and set an alert on hourly spend above threshold — that’s what catches the runaway loop at 3am before finance does. by_user attribution is what turns “our LLM bill doubled” into “the new onboarding flow retries eight times.”

See Also

Frequently Asked Questions

How much can I save with model routing?

Routing a request to gpt-4o-mini instead of gpt-4o costs ~85-90% less per call. Your total savings depend on the traffic mix — if half your requests are simple tasks (classification, extraction, short answers), routing alone cuts spend 40-50%. Measure your task distribution first; routing 10% of traffic to mini barely moves the bill.

Is semantic caching worth the embedding cost?

Usually yes. An embedding call costs ~$0.02/1M tokens — three orders of magnitude cheaper than a gpt-4o completion. Semantic caching pays off once your hit rate clears ~10-15% on paraphrased traffic; below that, exact-match caching is simpler and free.

Should I use the Batch API?

Use it for anything that doesn't need a response in seconds: nightly summarization, bulk classification, eval runs, backfills. It's a flat 50% discount for 24-hour turnaround. Don't use it for anything user-facing — there's no latency SLA.

How do I set max_tokens to control costs?

Set it to the upper bound of answers you actually serve (measure the p95 of completion_tokens in your metrics). Output tokens cost 4-5× input tokens, so a 4000-token cap on answers that only need 300 is wasted headroom — but too tight and you silently truncate responses mid-sentence.

What is the cheapest way to do RAG?

Small embedding model (text-embedding-3-small), chunk once and cache embeddings, retrieve fewer better chunks instead of more mediocre ones, and route the generation step to a mini model when the question is simple. The RAG production guide has the full pipeline.

How do I handle budget overruns?

Two tiers: soft alerts at 70-80% (log + notify, keep serving) and hard stops at 100% (reject or degrade to cached/stale answers). Never let a hard stop return a 500 to users — degrade to cache or a cheaper model instead.

When is fine-tuning cheaper than prompting?

With a high-volume, single-task workload where a smaller fine-tuned model matches the big model's quality — the training cost amortizes over millions of calls. Below that volume, a bigger model with a good prompt wins. The break-even is usually in the millions of requests per month.