OpenAI Automatic Caching Intermediate
OpenAI uses automatic prompt caching for supported models. There are no code changes required - the system automatically detects and caches repeated prompt prefixes, offering a 50% discount on cached input tokens.
How Automatic Caching Works
OpenAI's caching is based on prefix matching. The system automatically caches the longest common prefix of your prompt that meets the minimum length. Caching happens at 128-token boundaries.
# Request 1: [System: 1500 tokens] + [Tools: 500 tokens] + [User: 100 tokens] → Full processing, prefix cached automatically # Request 2 (same system + tools, different user message): [System: 1500 tokens] + [Tools: 500 tokens] + [User: 80 tokens] → 2000 tokens served from cache (50% off) → 80 tokens processed normally
Supported Models
| Model | Caching Support | Minimum Prefix Length |
|---|---|---|
| GPT-4o | Automatic | 1,024 tokens |
| GPT-4o-mini | Automatic | 1,024 tokens |
| o1, o1-mini | Automatic | 1,024 tokens |
| o3-mini | Automatic | 1,024 tokens |
Usage Example
No special API parameters are needed. Just structure your prompts so the cacheable content comes first:
from openai import OpenAI client = OpenAI() # Both requests share the same system prompt prefix # OpenAI caches it automatically def ask_question(question): response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "system", "content": very_long_system_prompt # 2000+ tokens }, { "role": "user", "content": question } ] ) # Check cache usage in response usage = response.usage print(f"Cached tokens: {usage.prompt_tokens_details.cached_tokens}") return response.choices[0].message.content # First call: no cache (creates cache entry) ask_question("What is Python?") # Second call: cache hit on system prompt ask_question("Explain decorators")
OpenAI vs. Anthropic Caching
| Feature | OpenAI | Anthropic |
|---|---|---|
| Approach | Automatic | Explicit (cache_control) |
| Code changes needed | None | Add cache_control markers |
| Cache discount | 50% off input price | 90% off input price |
| Cache write premium | None | 25% premium |
| Cache TTL | 5-10 minutes | 5 minutes (refreshed on hit) |
| Control level | Low (automatic) | High (explicit breakpoints) |
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX