---
title: "Count tokens and set a budget"
lesson_id: "02"
---

# Count tokens and set a budget

- **Lesson ID:** 02
- **Goal:** Build a token budget from contextSize, tokenCount, and a reply reserve.
- **Human lesson:** [02-token-budgets.html](02-token-budgets.html)

## Prerequisites

- Lesson 01.
- Xcode 27 with Foundation Models.

## Inputs, outputs, and artifacts

- **Inputs:** Model, question text, instruction text.
- **Outputs:** A leftover token count for ranked slices.

## Agent build steps

1. Read `model.contextSize`.
2. Count the question and instructions with the same model that will answer.
3. Reserve reply tokens before filling slices.
4. Count SystemLanguageModel, PrivateCloudComputeLanguageModel, and CoreAILanguageModel separately.
5. If counting is missing, document a conservative fallback. Do not claim it is exact.

## Constraints

Illustrative Swift. iOS 27 and macOS 27. No em dashes.

## Key concepts

- Read `model.contextSize` and count with `model.tokenCount(for:)`.
- Reserve reply tokens first. A full window leaves no room for the answer.
- Each model type has its own window. Do not mix counts.
- If counting is missing in your SDK drop, use a conservative estimate and say so.

## Takeaways

- Count with the same model that will answer.
- A `SystemLanguageModel` count is wrong for a PCC pack.
- Budget the window, then the reply reserve, then the question, then ranked slices.

## Acceptance checks

- Reply reserve exists.
- Same-model counting is stated.
- Fallback honesty is stated.
- Agent brief link is present.
