agentic-ai-course

Module 10 — Prompt Caching & Cost Optimization

Every call in every previous module resent the entire system prompt from scratch — and Claude reprocessed it from scratch every time, even when it’s the exact same text as the call before. Prompt caching lets Claude reuse its internal representation of a content block across calls, cutting cost and latency for anything large and repeated.

What you’ll learn

The core idea

response = client.messages.create(
    model=MODEL,
    system=[
        {"type": "text", "text": LARGE_SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}
    ],
    messages=[{"role": "user", "content": prompt}],
)

The first call with a given cached block creates the cache (you pay a small premium for that call) and reports it via cache_creation_input_tokens. Every subsequent call within the cache’s lifetime (about 5 minutes by default, refreshed on each hit) reads the cache instead — cheaper and faster — and reports it via cache_read_input_tokens.

This matters most for exactly the things earlier modules built: Module 4’s skill files, Module 5’s tool definitions, Module 8’s retrieved documents — anything large, reused across many calls in a session, and unlikely to change turn to turn. It matters least for things that change every call, like the latest user message.

Run it

pip install -r requirements.txt
export ANTHROPIC_API_KEY=your_key_here
python exercise.py   # after filling in the TODOs
python solution.py   # to compare against a working version

Watch the printed usage lines: call 1 should show cache_creation tokens and zero cache_read; call 2 (run within a few minutes) should show the reverse.

Next

Module 11 — MCP (Model Context Protocol) — connecting an agent to external tool servers instead of hand-rolling every tool.