1. Enter the model window
Use the token limit for the exact model and endpoint.
2. Add system and tool tokens
Include instructions, schemas, and framework-generated messages.
3. Measure conversation history
Count the messages that will be sent with the next request.
4. Add retrieved context
Include document chunks, citations, metadata, and separators.
5. Reserve output tokens
Leave enough capacity for the expected completion.
6. Set a safety margin
Protect against estimation error and variable tokenization.
7. Check remaining capacity
A negative result means the planned request is too large.