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.

Conceptual
# 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:

Python
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)
Optimization Tip: Even though OpenAI's caching is automatic, you can improve cache hit rates by keeping your prompt prefix stable. Put static content (system prompt, tools, examples) first, and dynamic content (user message) last.
Important: Caching is per-organization and scoped by API key. Different API keys within the same organization may not share cache entries.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.