Tokens, the Context Window and Cut-Off Replies

A language model does not read or write text letter by letter or word by word: it works in tokens. Tokens decide how much one request can hold, where a reply stops when you limit its length, and what the call costs, because providers count and bill every request in tokens. Reading those counts is what lets a program notice a reply that stopped too early and know what each call costs.

Tokens: the pieces a model reads and writes

Before a model sees your text, a tokenizer cuts it into pieces taken from a fixed vocabulary, and each piece becomes a number the model can work with. Those pieces are tokens. The model reads the tokens of the request, then writes its reply one token at a time, and the provider turns those tokens back into text before the response reaches your program. The client only ever receives text.

A token is neither a word nor a character. Common short words are often one token each, a long or rare word is split into several pieces, and punctuation usually gets a token of its own. Spaces and capitals matter too. The space in front of a word is normally part of that word's token, so red (with a leading space) is a different piece from red, and Red is different again. In the split below a dot marks where a token starts with a space.

An illustrative split (the real pieces depend on the model)
  1. The
  2. ·token
  3. izer
  4. ·splits
  5. ·red
  6. ·and
  7. ·Red
  8. .

For English text, OpenAI gives rough rules of thumb: one token is about 4 characters, or about three quarters of a word, so 100 tokens are about 75 words. These are estimates, not counts. Other languages have a different relationship between characters, words and tokens, and code is split differently again.

Each model family uses its own tokenizer. The same sentence can give one count on one provider's model and another count on a local model, so a count is only exact for the model that produced it. A library such as OpenAI's tiktoken can count the tokens of plain text for OpenAI's encodings, but a request holds more than its plain text: the roles and boundaries of the messages, and any tool definitions, are turned into tokens too. The number that matters is the one the provider reports back.

True or false?

A sentence of 20 English words is always exactly 20 tokens.

False. Tokens are pieces of text, not words. A long word may take several tokens and punctuation takes its own, so 20 words come to roughly 27 tokens, and the exact number depends on the tokenizer.

The same paragraph can have a different token count on two different models.

True. Each model family has its own tokenizer and vocabulary, so the same text is cut into different pieces.

Reading the token counts of a call

You do not have to count tokens yourself to know what a call used. A Chat Completions response carries a usage object with three counts. prompt_tokens is the input: every message you sent, with its formatting. completion_tokens is the output: every token the model generated. total_tokens is the two added together. Input tokens are also called prompt tokens and output tokens completion tokens; other APIs name the same counts input_tokens and output_tokens.

The three counts of one call
response = client.chat.completions.create(
    model=model,
    messages=[{"role": "user", "content": "What is a token?"}],
)

usage = response.usage
print("input: ", usage.prompt_tokens)
print("output:", usage.completion_tokens)
print("total: ", usage.total_tokens)

These counts are the facts every later question rests on: how full the request was, whether the reply ran into a limit, and what the call cost. A usage object can carry more detail, such as how many input tokens came from a cache. Some providers keep the start of a prompt they have recently processed, such as a long system prompt that repeats on every call, and reuse it when the same start arrives again instead of processing it once more; those reused tokens are the cached ones. Only the three counts are always there, though. The detail fields are optional and many endpoints leave them out, so code treats them as possibly None.

The context window: one budget for input and output

A model can only work with a limited number of tokens in a single request. That limit is its context window, and it is shared: the tokens of everything you send and the tokens of everything the model generates in reply must fit in it together. A request does not get one budget for reading and another for writing.

The consequence is easy to miss. The longer the input, the less room is left for the reply. A short question leaves almost the whole window free, while a long document pasted into the prompt can leave only a narrow strip for the answer. The chart uses made-up round numbers to show the shape of this.

Two requests in the same window (illustrative numbers)
  • Short question
  • Long document
  • Input tokens
  • Reply tokens
  • Room left

A conversation runs into this over time. Its whole history is sent again with every turn, so the input of a long chat grows with each message and creeps towards the size of the window.

Models also have a second, smaller limit: an output limit on how many tokens one reply can contain, however much of the window is free. Each model's documentation gives both numbers, and they differ from model to model and even between versions of the same model.

True or false?

The context window limits only the text you send, so the reply always has its own separate space.

False. The window holds the input and the output of one request together. A longer input leaves fewer tokens for the reply.

A model can have a large context window and still be unable to write a reply that fills it.

True. The output limit is separate and smaller than the window, so one reply can never be longer than that limit.

Capping the length of a reply

Left alone, a reply can run as long as the model's output limit and the free space in the window allow. Most applications want a smaller ceiling: to keep each call cheap and quick, and to stop a runaway answer. You set that ceiling in the request, as a maximum number of tokens the model may generate for this reply.

On Chat Completions the parameter is max_completion_tokens. An older parameter, max_tokens, does the same job. OpenAI marks it deprecated, and its reasoning models do not accept it. Many compatible servers still accept it, though, and some document only max_tokens. Use the one your endpoint accepts.

A reply limited to 300 tokens
response = client.chat.completions.create(
    model=model,
    messages=[{"role": "user", "content": "Explain tokens to a beginner."}],
    max_completion_tokens=300,
)

The cap is a hard stop, not an instruction. The model does not see it and does not plan a shorter answer around it: it writes exactly as it would without the cap, and generation simply stops when the count reaches the limit. If you want a short answer, ask for one in the prompt, and keep the cap as a safety limit with some room above the length you expect.

True or false?

Setting the cap to 50 tokens makes the model write a complete, shorter answer that fits in 50 tokens.

False. The model does not know about the cap. It writes as usual and is stopped at token 50, often in the middle of a sentence.

Asking for a short answer in the prompt and setting a cap do different jobs.

True. The prompt shapes what the model writes; the cap only decides where generation is forced to stop.

Detecting a reply that was cut off

When a reply reaches its cap, the call does not fail. The response arrives like any other, with a status of success, a message and its usage counts, and the text simply ends wherever the count ran out. No exception is raised. The only sign is the finish reason of the choice, which says why the model stopped generating.

Values of finish_reason
finish_reasonWhy generation stopped
stopThe model reached a natural end, or a stop sequence you provided
lengthThe token limit was reached: the reply is cut off
tool_callsThe model asked to run a tool instead of answering in text
content_filterContent was left out because a content filter flagged it

A fifth value, function_call, belongs to an older, deprecated way of calling functions. In practice, stop is the value that says the text is whole.

A cut-off reply looks plausible. A summary that ends after its second point, or a list missing its last items, reads as if it were complete, and a program that saves or displays it passes the gap on without anyone noticing. That is why code checks the finish reason before it uses the text, and also checks that there is text at all, because message.content can be None.

Check the finish reason before using the text
choice = response.choices[0]
text = choice.message.content

if choice.finish_reason == "length":
    print("The reply was cut off at the token cap.")
elif not text:
    print("The reply has no text.")
else:
    print(text)

What to do with a cut-off reply depends on the program. It can raise the cap and try again, ask for a shorter answer, or report the problem. What it should not do is treat a partial answer as a finished one.

True or false?

When a reply hits the cap, the client raises an exception, so a try block is enough to catch it.

False. A cut-off reply comes back as a normal successful response. Only finish_reason, set to length, shows that it stopped early.

A reply cut off by the cap still uses tokens and still appears in the usage counts.

True. Every token that was generated before the stop is counted as output, so a cut-off reply is billed like any other.

Reasoning tokens: output you do not see

Some models think before they answer. These reasoning models first generate a chain of intermediate tokens, working through the problem, and only then write the reply you receive. The reasoning tokens are not returned to you through the API, but they were generated like any other output, and that has three consequences.

  • They occupy space in the context window, alongside the input and the visible reply.
  • They are billed as output tokens, and they are already included in completion_tokens.
  • They count against the cap. max_completion_tokens limits all generated tokens, visible and not.

The third point changes how a cap behaves. Depending on the problem, a model may spend anywhere from a few hundred to tens of thousands of tokens reasoning. If the cap is small, reasoning can use most of it, leaving a short visible reply that ends at length, or all of it, leaving no visible text at all. The call is still billed for the input and for every reasoning token.

Where a cap of 1,000 tokens goes (illustrative numbers)
  • No reasoning
  • Reasoning, fits
  • Reasoning, cut off
  • Reasoning, empty
  • Reasoning tokens (not shown)
  • Visible reply

So a cap that works well for an ordinary model can be far too tight for a reasoning model. Leave generous room above the visible length you need; OpenAI suggests reserving at least 25,000 tokens for reasoning and output when you start experimenting with its reasoning models. The empty case is also why code checks for missing text as well as for length.

Endpoints that report reasoning put the count in usage.completion_tokens_details.reasoning_tokens. The details object is optional, and many compatible endpoints omit it, so read it with a guard, as below. Subtracting the reasoning count from completion_tokens gives a rough size of the visible reply. It is only rough because some models also generate formatting tokens that usage does not list separately.

Reading the reasoning count safely
usage = response.usage
details = usage.completion_tokens_details
reasoning = (details and details.reasoning_tokens) or 0

print("output in total:", usage.completion_tokens)
print("of which reasoning:", reasoning)

True or false?

Reasoning tokens are hidden from the reply, so they are not billed.

False. They are billed as output tokens. They are not returned, but they were generated and are included in completion_tokens.

A reasoning model with a small cap can return a reply with no text and finish_reason set to length.

True. The cap counts reasoning tokens too, so reasoning can use the whole cap before any visible token is written.

Working out what a call costs

Providers price tokens, not calls, and they price input and output separately. Prices are usually listed per million tokens, and output costs more than input for every text model on OpenAI's price list. The cost of one call follows from its usage counts: input tokens at the input price, plus output tokens at the output price.

$$\text{cost} = \frac{\text{prompt\_tokens} \times P_{\text{in}} + \text{completion\_tokens} \times P_{\text{out}}}{1\,000\,000}$$

with the input and output prices per million tokens

Take made-up prices of $2.00 per million input tokens and $8.00 per million output tokens, and a call that used 1,200 input tokens and 800 output tokens. The input costs \( 1200 \times 2 / 1\,000\,000 = \$0.0024 \), the output \( 800 \times 8 / 1\,000\,000 = \$0.0064 \), and the call \( \$0.0088 \). Fewer output tokens cost more than the input here, because each output token costs four times as much at these prices.

The cost of a call from its usage
INPUT_PRICE_PER_MILLION = 2.00   # example prices in dollars, not real ones
OUTPUT_PRICE_PER_MILLION = 8.00


def call_cost(usage):
    input_cost = usage.prompt_tokens * INPUT_PRICE_PER_MILLION / 1_000_000
    output_cost = usage.completion_tokens * OUTPUT_PRICE_PER_MILLION / 1_000_000
    return input_cost + output_cost


print(f"${call_cost(response.usage):.4f}")

Reasoning tokens need no line of their own: they are already inside completion_tokens, so adding them again would count them twice. A few details can refine the estimate. Input tokens served from a cache, reported as prompt_tokens_details.cached_tokens where available, often have a lower cached-input price, and some models charge more once the input passes a long-context threshold. Real prices change, so a program keeps them as settings and takes them from the provider's current price page.

True or false?

To price a call to a reasoning model, add reasoning_tokens to completion_tokens and charge the sum at the output price.

False. completion_tokens already includes the reasoning tokens. Adding them again would bill them twice.

Two calls with the same total_tokens can cost different amounts.

True. Input and output have different prices, so a call with more output tokens in the same total costs more.