Every API call sends the whole chat history, and the total counts against the context window. Counting the history before the call is the only way to know whether the next request fits, because the runtime cuts an over-long prompt silently. Count each turn, add the system prompt, and leave room for the reply you expect.
Prerequisites
- The chat history as a list of turns with roles.
- A tokenizer or a word-count estimate for the model’s encoding.
- The context window size and the reply length you expect.
Steps
Step 1: Count each turn
Count the tokens in each turn: the user’s messages and the assistant’s replies. Roughly 1,000 tokens equals 750 words in English, but for a count near the limit use the real tokenizer.
Step 2: Add the system prompt
Add the system prompt’s tokens to the history total. The system prompt is sent with every request, so it is easy to forget and it is always there.
Step 3: Leave room for the reply
Subtract the total from the window size. The remainder is the room for the reply; if it is smaller than the reply you need, trim the history before calling.
Worked example: Cedar Street Library reference chat
The fictional Cedar Street Library counts a 5-turn reference chat before its next API call. The window is 8,192 tokens and the reply needs 500.
| Turn | Role | Tokens | Running total |
|---|---|---|---|
| System prompt | System | 180 | 180 |
| Turn 1 | User | 240 | 420 |
| Turn 2 | Assistant | 310 | 730 |
| Turn 3 | User | 95 | 825 |
| Turn 4 | Assistant | 120 | 945 |
The history totals 945 tokens, leaving 7,247 tokens of the 8,192-token window, far more than the 500-token reply needs, so the call fits.
Expected result. You have a token total for the whole history, compared with the window, with room for the reply left over. UNTESTED: this guide was not run against a live model or API. The worked example below is fictional practice material, and its result is the expected result, not a measured one.
Limits
- Word-count estimates are approximate; near the limit, count with the real tokenizer.
- Some APIs add per-message overhead tokens; the estimate may undercount slightly.
- This guide does not cover trimming history; that is a separate guide.
