Optimizing LLM Request Costs: Practical Methods
The cost of LLM requests is one of the main expenses in AI products. Every token costs money, and suboptimal prompts and architecture can double the bill. In this article, I will explore practical methods to reduce costs on language model APIs: from caching to model selection.
Where Do Costs Come From
The cost of a request consists of three components: - input tokens (prompt, context); - output tokens (response); - additional calls (embeddings, reranks, multiple models). The main source of overruns is duplicate requests and excessive context. Users often ask similar questions, and the system sends a full prompt with the conversation history each time.
Caching Responses
The simplest way to save costs is to cache responses to repeated requests. If two users ask the same question, the response does not need to be generated again. Implementation of caching:
import hashlib
import json
cache = {}
def get_cached_response(prompt, model):
key = hashlib.md5(f"{model}:{prompt}".encode()).hexdigest()
return cache.get(key)
def cache_response(prompt, model, response):
key = hashlib.md5(f"{model}:{prompt}".encode()).hexdigest()
cache[key] = response
Caching Context
Modern APIs support context caching. If the system prompt and most of the context do not change between requests, the provider does not recalculate them and charges less. For example, in DeepSeek API, cached input tokens cost several times less. To use this, you need: - a stable system prompt; - the same order of messages in the conversation; - minimal changes in context between requests. This is especially important for multi-turn conversations and agents, where context grows with each step.
Managing Context Length
The longer the context, the more expensive the request. Methods to shorten: - summarizing the conversation history instead of storing all messages; - extracting only relevant fragments from knowledge bases; - limiting the maximum number of tokens in the response; - using semantic routing to choose a model with the appropriate context window. Example: instead of sending the entire conversation history (2000 tokens), you can send a summary (200 tokens) + the last 5 messages. Savings: 80% of input tokens.
Selecting a Model for the Task
Not all tasks require the most powerful model. For classification, data extraction, and simple responses, small models suffice. For complex reasoning, large models are needed. | Task | Model | Cost | |---|---|---| | Text Classification | Small model | Low | | Data Extraction | Medium model | Medium | | Complex Reasoning | Large model | High | Semantic router automatically routes requests to the appropriate model. For example, the question "how to reset password" is handled by a small model, while "analyze the financial report" is handled by a large model.
Batching Requests
If an application processes many similar requests, they can be batched. Some APIs offer discounts for batch processing. Batching is effective for: - classifying large volumes of text; - generating metadata; - summarizing documents. Instead of 100 individual requests, you can send one batch of 100 elements. This reduces costs and decreases API load.
Monitoring and Alerts
Without monitoring, it's impossible to control costs. You need to track: - cost per day/week/month; - cost by models and users; - average cost per request; - anomalies (sudden cost spikes). Setting up an alert: if the cost per hour exceeds the threshold, a Telegram notification is sent. This allows for quick reaction to errors in the code that lead to infinite request loops.
Final Optimization Scheme
graph TD
A[User Request] --> B[Response Cache]
B -->|Has response| C[Return from cache]
B -->|No response| D[Semantic Router]
D --> E[Model Selection]
E --> F[Context Reduction]
F --> G[API Request]
G --> H[Context Caching]
H --> I[Response]
I --> J[Logging Cost]
The combination of methods yields savings of 30–70% without quality loss. Start with response caching and context management — these are the simplest and most effective steps.