← All notes

Counting tokens offline: tiktoken encodings and Hugging Face tokenizers

Answer: Count tokens by counting the length of the list returned by .encode(). Knowing the count tells you whether a string is too long for a model to process and how much a call costs, as usage is priced by token.

tiktoken

Open models

The 🤗 Tokenizers library gives output.tokens and output.ids, with offsets into the original sentence.

It's best to process your texts by batches by using the encode_batch method.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: openai/openai-cookbook (GitHub), How to count tokens with tiktoken, MIT (https://raw.githubusercontent.com/openai/openai-cookbook/main/LICENSE). Copyright (c) 2025 OpenAI; huggingface/tokenizers (GitHub), Tokenizers quicktour, Apache-2.0 (https://raw.githubusercontent.com/huggingface/tokenizers/main/LICENSE). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: openai/openai-cookbook (GitHub), How to count tokens with tiktoken, MIT (https://raw.githubusercontent.com/openai/openai-cookbook/main/LICENSE). Copyright (c) 2025 OpenAI; huggingface/tokenizers (GitHub), Tokenizers quicktour, Apache-2.0 (https://raw.githubusercontent.com/huggingface/tokenizers/main/LICENSE).

Cite this

Permanent ID: iil:note:bnv5mych

iinventedlight. 2026. "Counting tokens offline: tiktoken encodings and Hugging Face tokenizers." iinventedlight Library, iil:note:bnv5mych, version of 2026-11-16. https://iinventedlight.com/library/notes/ao-tokens-tiktoken-counting/. License: CC-BY-4.0.

@misc{iil_note_bnv5mych,
  author = {{iinventedlight}},
  title = {{Counting tokens offline: tiktoken encodings and Hugging Face tokenizers}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-16},
  url = {https://iinventedlight.com/library/notes/ao-tokens-tiktoken-counting/},
  note = {Permanent ID iil:note:bnv5mych. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/ao-tokens-tiktoken-counting.md.