New Tool Radar

AI Concepts

How to Count the Tokens in a Prompt Before You Send It

Count tokens with the model tokenizer, add the expected output, and check the total fits the context window before sending.

Schematic with three steps: Count the prompt tokens; Add the output budget; Shorten before you send if it does.

A context window is a hard limit, and a request that exceeds it is rejected or truncated, so counting tokens before sending is the check that prevents both. For OpenAI models you can split a string into tokens with the tiktoken tokenizer, and for third-generation embedding models the cl100k_base encoding is the right one. Count the prompt, add a budget for the output, and compare the total with the model window: if it does not fit, shorten the prompt before you pay for a failed request.

What you need

  • The tokenizer for your model, for example tiktoken with cl100k_base
  • The full prompt text you plan to send
  • The model context window size and the output budget you need

Step 1: Count the prompt tokens

Run the tokenizer over the exact prompt text, including the system message and any tool definitions, since all of them count. Do not estimate from word count: a word is usually more than one token.

Step 2: Add the output budget

Add the maximum output tokens you will allow, since the prompt plus the output must fit inside the window together. A prompt that fits alone can still overflow once the model starts writing.

Step 3: Shorten before you send if it does not fit

If the total exceeds the window, cut the longest part first, usually the background context, or compress it, or move it to retrieval. Send only when the counted total fits with room to spare.

Worked example: synthetic token count for one request

The table below is a synthetic example. It shows the expected result of counting tokens; no request was sent.

Part Tokens Running total
System message 400 400
Background context 6,000 6,400
User question 50 6,450
Output budget 1,000 7,450 of 8,192 – fits

Expected result (UNTESTED). the prompt plus the output budget totals 7,450 tokens, which fits inside the 8,192-token window. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Token counts depend on the tokenizer: the same text counts differently under cl100k_base and another encoding, so use the model own tokenizer.
  • Tool definitions count against the context limit and are billed as input tokens.
  • A count is exact for the text you counted; a prompt that changes per request must be counted per request.
  • Counting does not tell you whether the model will use the context well; long context prompting still needs the important content placed well.

Sources

See all