---
title: "Wire the cache into a session"
lesson_id: "05"
---

# Wire the cache into a session

- **Lesson ID:** 05
- **Goal:** Call the cache before LanguageModelSession.respond and write misses back.
- **Human lesson:** [05-wire-into-session.html](05-wire-into-session.html)

## Prerequisites

- Lessons 02 through 04.
- Xcode 27 with Foundation Models.

## Inputs, outputs, and artifacts

- **Inputs:** User question, prepared session, embedder, rows.
- **Outputs:** Answer text, updated rows, updated stats.

## Agent build steps

1. Embed the question on device.
2. Return a stored answer on a high-similarity hit.
3. On a miss, call `session.respond` and store the pair with an expiry.
4. Keep the cache outside Dynamic Profiles. One Profile is active if you generate.
5. Do not cache tool-using turns unless the row keys on tool results.
6. Cite [WWDC26 241](https://developer.apple.com/videos/play/wwdc2026/241/) and Foundation Models / Core AI docs lightly.

## Constraints

Illustrative Swift. SystemLanguageModel for the first cache. iOS 27 and macOS 27. No em dashes.

## Key concepts

- The cache sits before `LanguageModelSession`. A hit returns the stored answer.
- A miss calls `session.respond`, then writes the pair.
- Dynamic Profiles pick instructions and tools. The cache decides whether to call the session.
- Do not cache tool-using turns until rows can key on tool results.

## Takeaways

- Ask the cache first on every question.
- Tool turns need richer cache keys than question text alone.
- You now have an on-device semantic cache, a high threshold, and hit-rate counters.

## Acceptance checks

- Hit path skips generate.
- Miss path writes the pair.
- Tool-using turns are called out as unsafe to cache blindly.
- Agent brief link is present.
