Cache decks and re-theme without AI
Never pay twice for the same deck: an LRU store keyed by a stable hash of the request, and theme changes that re-run only the compiler on saved SlideML.
People regenerate the same deck constantly: a page refresh, a double-click, a colleague with the same brief. And they change the theme after seeing the result. Neither should cost another 30 seconds and another few thousand tokens.
Request
{ topic, slideCount, theme }
requestKey()
same fields → same key
store.get(key)
hit: return it
miss: generate
then store.set(key, deck)
saved.xml
the SlideML
compileDeck(xml, 'dark')
no model call
A stable key
{ topic, slideCount } and { slideCount, topic } are the same request, but JSON.stringify writes them differently. stableStringify sorts object keys first, then requestKey turns that text into a short . Same request, same key, whatever order the fields arrived in.
An LRU store
Memory isn't infinite, so the store keeps a maximum number of decks. When it's full, it drops the one used longest ago: an . A JavaScript Map makes this short, because it remembers insertion order:
- get: delete the entry and set it again, which moves it to the end: "most recently used".
- set: put it at the end. While the map is too big, delete the first key: the least recently used.
Re-theming for free
Because the pipeline returns the SlideML, the store keeps it. rethemeDeck(saved, "dark") just calls compileDeck(saved.xml, "dark"): milliseconds, no tokens, and exactly the same words.
theme: light
theme: dark
Under the hood — Isn't caching AI output wrong, if each run could be different?
For a chat reply, sometimes. For a deck, the user asked for a deck, got one, and asked again with the same inputs, usually by accident. Returning what they already have is what they expect. If they want a new version, give the UI a "regenerate" button that skips the cache on purpose.
Key takeaways
- The same request should never cost tokens twice: key saved decks by a hash of the request.
- Save the SlideML, not just the .pptx, so a theme change only re-runs the compiler.
- An LRU cache keeps recent entries and drops the least recently used when it's full.
Sign in to run the exercise
Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +35 XP you are about to earn.