---
name: Build a context packer for on-device AI
description: >-
  Teach an edge engineer to assemble a token-budgeted context pack for
  LanguageModelSession and Dynamic Profiles on iOS 27 and macOS 27.
---
# Build a context packer for on-device AI

Use this course to pack memory, search hits, and tools into the window the model can actually use. Dynamic Profiles declare what is visible. Your assembler chooses the slices.

## End-to-end agent recipe

1. Start with [lesson 01](01-why-packing-matters.llms.md) to show wasted tokens and distracted answers.
2. Use [lesson 02](02-token-budgets.llms.md) to read `contextSize` and `tokenCount(for:)`.
3. Use [lesson 03](03-rank-memory-search-tools.llms.md) to rank slices and drop the rest.
4. Use [lesson 04](04-dynamic-profiles-as-the-pack.llms.md) to put the pack into one active Profile, with `historyTransform` when needed.
5. Use [lesson 05](05-build-the-assembler.llms.md) to build, measure leftover budget, and refuse an overfull pack.
6. Use human HTML for reading and `.llms.md` files for agent execution.

## Constraints

- iOS 27 and macOS 27 only.
- Foundation Models Dynamic Profiles. No LangChain.
- Illustrative Swift. Check names in the installed Xcode 27 docs. Do not use Python for the packer.
- No Mermaid. Progressive `.flow` diagrams only.
- Do not use em dashes.
- Cite [WWDC26 241](https://developer.apple.com/videos/play/wwdc2026/241/) and [WWDC26 242](https://developer.apple.com/videos/play/wwdc2026/242/) lightly.

## Key concepts

- Pack memory, search hits, and tools into a token budget for `LanguageModelSession`.
- Dynamic Profiles declare what the model sees. Your assembler picks the slices.
- One active Profile per turn on iOS 27 and macOS 27.
- Count with the same model that will answer, using `contextSize` and `tokenCount(for:)`.

## Takeaways

- You can fill a token budget and declare it as one Dynamic Profile.
- You can hand a packed context to `LanguageModelSession(profile:)` without dumping the whole toolbox.
- You can refuse an overfull pack and log what you left out.

## Acceptance checks

- Every human lesson HTML has **Key concepts** and **Takeaways** sections before lesson-nav. The course home has the same two headings for the whole course.
- Five human lessons and five briefs exist.
- Token budget uses documented counting APIs or an honest fallback.
- One active Profile is stated.
- Course index lists SKILL.md and all briefs.

## Environment setup

Xcode 27. iOS 27 or macOS 27 SwiftUI App. Foundation Models. Confirm `SystemLanguageModel.contextSize` and token counting in the installed SDK.
