Count LLM input tokens before sending a generation request

Count the request you will actually send when enforcing an LLM input budget. A tokenizer applied to a plain string is useful for local inspection, but it does not necessarily include message framing, tool definitions, schemas, images or conversation history. The Responses API provides a separate input-token count endpoint for that full-request check.

Inspect plain text locally

Use Python 3.14 with tiktoken==0.14.0 and openai==3.58.0 in an isolated environment. The following example uses the explicitly named o200k_base encoding to demonstrate text tokenization. It does not claim that every model uses that encoding.

Python
import tiktoken

encoding = tiktoken.get_encoding("o200k_base")
text = "Summarize the release notes in three sentences."
tokens = encoding.encode(text)
assert encoding.decode(tokens) == text
print("Plain-text tokens:", len(tokens))

The printed count belongs to that exact string and encoding. Whitespace and punctuation participate in tokenization. The tokenizer may download its public encoding data on first use, after which the cached data can support offline use. Choose a model's documented encoding when a model-specific local estimate is needed. Tiktoken documentation .

Count the complete API input

For the next example, configure OPENAI_API_KEY through your normal environment or secret manager and set OPENAI_MODEL to an available Responses-compatible model. Check its context limit and output support in the current model documentation. Running this block sends data to the provider and may incur usage charges. Model catalog .

Python
import os
from openai import OpenAI

request = {
    "model": os.environ["OPENAI_MODEL"],
    "instructions": "Summarize only facts present in the supplied notes.",
    "input": "Release notes: fixed a startup crash and added CSV export.",
}
input_budget = 8_000
output_budget = 512

with OpenAI(timeout=30.0, max_retries=0) as client:
    count = client.responses.input_tokens.count(**request)
    if count.input_tokens > input_budget:
        raise ValueError("Input exceeds this application's token budget")
    response = client.responses.create(
        **request,
        max_output_tokens=output_budget,
        store=False,
    )
    print("Counted input:", count.input_tokens)
    print("Response status:", response.status)
    if response.usage is not None:
        print("Actual input:", response.usage.input_tokens)
        print("Actual output:", response.usage.output_tokens)
    if response.status != "completed":
        raise RuntimeError("The response did not complete")
    print(response.output_text)

The same model, instructions and input are shared between counting and generation. Add tools, schemas or a previous-response reference to that shared input specification when using them. The counter includes request framing that a plain-string estimate misses. It is a remote API request, so it is not a way to inspect confidential input without transmitting it. Token-counting guide .

Separate application budgets from model limits

The 8,000-token threshold is an application policy for this example. It is not a provider context limit. Leave sufficient space for output within the selected model's context window and observe its independent maximum-output limit. Reasoning models can consume part of their output budget on reasoning, so a small output cap may yield an incomplete response before enough visible text is produced. Responses API reference .

Input counting also cannot predict the exact length of a generated answer. Record actual usage after completion, and use current pricing for the selected model and token types when calculating cost. Cached input and generated output can have different accounting rules.

If the request changes after counting, count it again. In particular, a conversation may grow between requests. Keep counting and submission tied to the same immutable payload or conversation version. The counter's accepted parameters are documented separately from generation controls such as max_output_tokens. Input-token count API .

Local text tokenization was executed. SDK payloads and budget branches were checked with mocked HTTP responses. No provider token-count or generation call was made during verification.

Question provenance

This article addresses OpenAI API: How do I count tokens before(!) I send an API request? , asked by meliksahturker on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.

Author: Herman Schoenfeld