Published
LLM Cost Optimization: Model Routing, Caching, Token Budgets and Batch Processing
Keep LLM spend predictable as usage grows: estimate cost per task, route to the smallest model that works, cache similar queries and enforce token budgets.
- Written by
- Ali ÖzdurmuşFounder, Veni AI
- Updated
- Reading time
- 6 min read

An AI application that costs a few dollars a day in a pilot can cost thousands a month once a whole department uses it. The good news: most of that spend is controllable with a handful of engineering habits. This guide walks through them.
Code samples are illustrative Python.
clientis an initialized SDK client; model names such asSMALL_MODELare placeholders for the model IDs you choose.
How LLM Pricing Works
Almost every provider charges per token, with separate prices for:
- Input tokens: your prompt, instructions, retrieved documents and conversation history
- Output tokens: what the model writes, usually several times more expensive per token than input
- Extras: cached input (often discounted), batch processing (often discounted), images and audio, tool calls such as web search
Prices also differ by model tier: small, fast models can cost an order of magnitude less than the largest reasoning models. Prices change often, so keep them in configuration, not in code, and review them when providers announce updates.
Know Your Cost per Task
Before optimizing anything, measure. Cost per request is less useful than cost per completed business task (one invoice processed, one ticket answered).
class CostCalculator:
def __init__(self, price_table: dict):
# price_table loaded from config: {"model-id": {"input": per_1m, "output": per_1m}}
self.prices = price_table
def request_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
p = self.prices[model]
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def monthly_estimate(self, model, tasks_per_day, calls_per_task, avg_in, avg_out) -> float:
per_task = calls_per_task * self.request_cost(model, avg_in, avg_out)
return per_task * tasks_per_day * 30Usually a few things dominate: long system prompts repeated on every call, too much retrieved context, and agents that take more steps than necessary.
Model Routing
Not every request needs the strongest model. Route by task type and complexity.
Rule-based routing
ROUTES = {
"classification": SMALL_MODEL,
"extraction": SMALL_MODEL,
"summarization": MEDIUM_MODEL,
"multi_step_reasoning": LARGE_MODEL,
}
def route(task_type: str) -> str:
return ROUTES.get(task_type, MEDIUM_MODEL)Classifier-based routing
def classify_complexity(prompt: str) -> str:
response = client.chat.completions.create(
model=SMALL_MODEL, # a cheap model decides
messages=[
{"role": "system", "content": "Answer with one word: simple, medium or complex."},
{"role": "user", "content": prompt},
],
max_tokens=3,
)
return response.choices[0].message.content.strip().lower()Escalation with a quality check
class AdaptiveRouter:
def __init__(self, models: list[str], quality_threshold: float = 0.8):
self.models = models # ordered from cheapest to strongest
self.threshold = quality_threshold
def run(self, prompt: str) -> dict:
for model in self.models:
response = call_model(model, prompt)
quality = assess_quality(response) # validation rules or a judge model
if quality >= self.threshold:
return {"response": response, "model": model, "quality": quality}
return {"response": response, "model": self.models[-1], "quality": quality}Escalation works best where output can be validated cheaply, for example JSON that must match a schema or extracted totals that must add up.
Caching
Exact response cache
import hashlib, json, redis
class LLMCache:
def __init__(self, redis_url: str, ttl: int = 3600):
self.redis = redis.from_url(redis_url)
self.ttl = ttl
def key(self, model: str, messages: list, **params) -> str:
payload = json.dumps({"model": model, "messages": messages, **params}, sort_keys=True)
return "llm:" + hashlib.sha256(payload.encode()).hexdigest()
def get(self, model, messages, **params):
cached = self.redis.get(self.key(model, messages, **params))
return json.loads(cached) if cached else None
def set(self, model, messages, response, **params):
self.redis.setex(self.key(model, messages, **params), self.ttl, json.dumps(response))Semantic cache
Serve answers to questions that are phrased differently but mean the same thing:
def semantic_cache_lookup(query: str, threshold: float = 0.95):
results = vector_store.search(vector=get_embedding(query), top_k=1, filter={"type": "cache"})
if results and results[0].score >= threshold:
return results[0].metadata["response"]
return NoneUse a high threshold, and never cache answers that depend on user-specific data or permissions.
Provider-side prompt caching
Many providers discount input tokens that repeat at the start of a prompt. Put stable content (system instructions, tool definitions, reference documents) first and the variable part last to benefit.
Token Optimization
Shorter inputs
- Trim system prompts; remove instructions the model already follows.
- Retrieve fewer, better passages (rerank instead of stuffing ten chunks).
- Summarize long conversation history instead of resending it.
Controlled outputs
OUTPUT_LIMITS = {
"classification": 10,
"extraction": 300,
"summarization": 400,
"drafting": 800,
}
response = client.chat.completions.create(
model=SMALL_MODEL,
messages=messages,
max_tokens=OUTPUT_LIMITS[task_type],
)Ask for structured output (JSON with a schema) instead of prose when the result goes into another system. It is shorter and easier to validate.
Batch Processing
Work that does not need an instant answer, such as nightly document classification, bulk summarization or re-indexing, can go through a provider's batch API, which is typically cheaper than real-time calls in exchange for a longer completion window.
batch_input = [
{
"custom_id": f"doc-{i}",
"method": "POST",
"url": "/v1/chat/completions",
"body": {"model": SMALL_MODEL, "messages": [{"role": "user", "content": text}]},
}
for i, text in enumerate(documents)
]
batch = client.batches.create(
input_file_id=upload_batch_file(batch_input),
endpoint="/v1/chat/completions",
completion_window="24h",
)Self-Hosting for Steady, High-Volume Work
For predictable, high-volume tasks, an open-weights model on your own GPUs can be cheaper than per-token pricing, and it keeps data in-house. Compare the full cost honestly: hardware or GPU rental, operations and on-call time, not just token prices.
Budget Monitoring
from datetime import date
class BudgetMonitor:
def __init__(self, daily_limit: float, alert_ratio: float = 0.8):
self.daily_limit, self.alert_ratio = daily_limit, alert_ratio
self.spend, self.day = 0.0, date.today()
def track(self, cost: float):
if date.today() != self.day:
self.spend, self.day = 0.0, date.today()
self.spend += cost
if self.spend >= self.daily_limit * self.alert_ratio:
send_alert(f"LLM spend at {self.spend:.2f} of {self.daily_limit:.2f}")
if self.spend >= self.daily_limit:
raise BudgetExceededError("Daily LLM budget reached")Set budgets per application and per workflow, not just per account, so one runaway agent cannot consume everyone's budget.
Measuring Return
Compare the AI cost per task with the cost of doing the task manually, including the cost of fixing AI mistakes:
def monthly_savings(manual_cost_per_task, tasks, ai_cost_per_task, error_rate, fix_cost_per_error):
manual = manual_cost_per_task * tasks
ai = ai_cost_per_task * tasks + error_rate * tasks * fix_cost_per_error
return manual - aiSummary
LLM costs become predictable when you measure cost per task, route to the smallest model that does the job, cache what repeats, control tokens on both sides and enforce budgets per workflow. Most savings come from architecture, not from negotiating prices.
Veni AI builds AI applications with cost controls designed in from the start, so spend grows with value rather than with usage. See our services or talk to us about your use case.


