方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Implement an LRU cache with TTL for LLM responses

Implement an LRU Cache with TTL for LLM Responses

LLM calls are expensive and slow. For many AI features — documentation lookups, FAQ answering, static content generation — the same prompt produces the same answer. Caching identical prompts eliminates redundant API calls and dramatically reduces latency for repeated queries.

What to build

Implement a LLMResponseCache class that combines LRU eviction with TTL expiry:

  1. LRU eviction — when the cache reaches max_size, evict the least-recently-used entry (not the oldest by insertion time).
  2. TTL expiry — each entry expires after ttl_seconds. Expired entries are treated as cache misses and removed on access.
  3. Deterministic cache keycache_key(prompt: str, model: str, temperature: float) -> str returns a stable SHA-256 hash. Same inputs must always produce the same key.
  4. get(key: str) -> dict | None — returns the cached value if present and not expired, else None. Accessing an entry updates its LRU position.
  5. set(key: str, value: dict) -> None — stores the value. If at capacity, evict the LRU entry first.
  6. stats() -> dict — returns {"size": int, "hits": int, "misses": int, "evictions": int, "hit_rate": float}.

Why this matters

Caching is the single highest-leverage optimization in most AI applications. Understanding how LRU + TTL interact is essential for building caches that stay fresh without consuming unbounded memory.

Constraints

  • Use collections.OrderedDict to implement LRU ordering — do not use functools.lru_cache (that hides the mechanism).
  • Do not import any third-party caching library.
  • hit_rate should be hits / (hits + misses), returning 0.0 when no requests have been made.

Python Ai / medium / Step 5 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.