Skip to content

Practical Cost Optimization for LLM API: Caching, Batching, and Model Selection

Summary

Step-by-step guide to reducing costs for LLM API: caching strategies, batching, model selection, context management, and cost monitoring.

1. Cost Structure Analysis

Before optimizing, understand where the money goes. Main cost items: input tokens, output tokens, number of requests.

Item Impact Optimization Method
Input tokens High Caching, context compression
Output tokens Medium Limit max_tokens, degradation
Number of requests High Batching, caching responses

2. Caching Responses

For repeated requests (e.g., FAQ), cache responses at the application level.

import hashlib
import redis

cache = redis.Redis()

def get_cached_response(prompt: str, model: str) -> str | None:
    key = hashlib.sha256(f"{model}:{prompt}".encode()).hexdigest()
    return cache.get(key)

def set_cached_response(prompt: str, model: str, response: str):
    key = hashlib.sha256(f"{model}:{prompt}".encode()).hexdigest()
    cache.setex(key, 3600, response)

3. Caching Prompts

Providers (OpenAI, Anthropic) support caching of system prompts. Enable it for long system messages.

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are an assistant..."},
        {"role": "user", "content": "Question"}
    ],
    # caching parameters depend on the provider
)

4. Request Batching

Combine independent requests into one. Some APIs offer a batch endpoint with up to a 50% discount.

# Example for OpenAI Batch API
import json

batch_requests = []
for i, prompt in enumerate(prompts):
    batch_requests.append({
        "custom_id": f"req-{i}",
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": {
            "model": "gpt-4o",
            "messages": [{"role": "user", "content": prompt}]
        }
    })

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

5. Model Selection

Use cheaper models for simple tasks, and more expensive ones for complex tasks. Configure semantic routing.

def route_to_model(query: str) -> str:
    if len(query) < 50:
        return "gpt-4o-mini"
    else:
        return "gpt-4o"

6. Context Management

Reduce the number of input tokens: trim history, use summarization.

def trim_history(messages, max_tokens=2000):
    # implementation of trimming
    return messages[-10:]  # example

7. Cost Monitoring

Track tokens per request and aggregate by day.

import time
from collections import defaultdict

usage = defaultdict(lambda: {"prompt_tokens": 0, "completion_tokens": 0})

def track_usage(model, prompt_tokens, completion_tokens):
    day = time.strftime("%Y-%m-%d")
    usage[day]["prompt_tokens"] += prompt_tokens
    usage[day]["completion_tokens"] += completion_tokens

8. Conclusion

Cost optimization is an iterative process. Start with caching and model selection, then add batching and monitoring. Related materials: LLM API Caching Strategies, Request Batching, Rate Limit Budgeting.