For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Primary navigation

Counting tokens

Get accurate input token counts before sending requests.

Token counting lets you determine how many input tokens a request will use before you send it to the model. Use it to:

  • Optimize prompts to fit within context limits
  • Estimate costs before making API calls
  • Route requests based on size (e.g., smaller prompts to faster models)
  • Avoid surprises with images and files—no more character-based estimation

The input token count endpoint accepts the same input format as the Responses API. Pass text, messages, images, files, tools, or conversations—the API returns the exact count the model will receive.

The count includes formatting tokens used to represent request structure, such as message roles and boundaries. These tokens might not appear in the text or fields you tokenize locally.

Why use the token counting API?

Local tokenizers like tiktoken work for plain text, but they have limitations:

  • Images and files are not supported—estimates like characters / 4 are inaccurate
  • Tools and schemas add tokens that are hard to count locally
  • Model-specific behavior can change tokenization (e.g., reasoning, caching)

The token counting API handles all of these. Use the same payload you would send to responses.create and get an accurate count. Then plug the result into your message validation or cost estimation flow.

Count tokens in basic messages

Simple text input
from openai import OpenAI

client = OpenAI()

response = client.responses.input_tokens.count(
    model="gpt-5.6", input="Tell me a joke."
)
print(response.input_tokens)

Count tokens in conversations

Multi-turn conversation
from openai import OpenAI

client = OpenAI()

response = client.responses.input_tokens.count(
    model="gpt-5.6",
    input=[
        {"role": "user", "content": "What is 2 + 2?"},
        {"role": "assistant", "content": "2 + 2 equals 4."},
        {"role": "user", "content": "What about 3 + 3?"},
    ],
)
print(response.input_tokens)

Count tokens with instructions

Input with system instructions
from openai import OpenAI

client = OpenAI()

response = client.responses.input_tokens.count(
    model="gpt-5.6",
    instructions="You are a helpful assistant that explains concepts simply.",
    input="Explain quantum computing in one sentence.",
)
print(response.input_tokens)

Count tokens with images

Images consume tokens based on size and detail level. The token counting API returns the exact count—no guesswork.

Input with an image