tiktoken-rs

Library Featured

Library for encoding and decoding with the tiktoken library in Rust

Checked · Sources

Downloads
3,939,182
Dependents
449
Stars
410
Forks
76
Contributors
19
Commits
208
Latest release
0.12.1 ·

About

From the project README ·

Rust library for tokenizing text with OpenAI models using tiktoken.

This library provides a set of ready-made tokenizer libraries for working with GPT, tiktoken and related OpenAI models. Use cases cover tokenizing and counting tokens in text inputs.

This library is built on top of the tiktoken library and includes some additional features and enhancements for ease of use with Rust code.

Supported OpenAI models include GPT-5.4, GPT-5, GPT-4.1, GPT-4o, o1, o3, o4-mini, and gpt-oss models.

Scope: This crate is focused on OpenAI tokenizers (tiktoken). For non-OpenAI models (Llama, Gemini, Mistral, etc.), use the HuggingFace tokenizers crate.

Examples

For full working examples for all supported features, see the examples directory in the repository.

Usage

Add the library to your project:

cargo add tiktoken-rs

Use the examples below in your Rust code.

Counting tokens

use tiktoken_rs::o200k_base;

let bpe = o200k_base().unwrap();
let tokens = bpe.encode_with_special_tokens(
  "This is a sentence   with spaces"
);
println!("Token count: {}", tokens.len());

For repeated calls, use the singleton to avoid re-initializing the tokenizer:

Read the full README
use tiktoken_rs::o200k_base_singleton;

let bpe = o200k_base_singleton();
let tokens = bpe.encode_with_special_tokens(
  "This is a sentence   with spaces"
);
println!("Token count: {}", tokens.len());

Encoding text

CoreBPE::encode mirrors upstream tiktoken and returns a Result. Propagate or unwrap the result before using the tokens:

use tiktoken_rs::o200k_base;

let bpe = o200k_base().unwrap();
let allowed = bpe.special_tokens();
let (tokens, last_piece_token_len) = bpe.encode("hello <|endoftext|>", &allowed).unwrap();

The generic encode_as and count helpers also return Result. The crate requires Rust 1.85 or newer.

Counting max_tokens parameter for a chat completion request

use tiktoken_rs::{get_chat_completion_max_tokens, ChatCompletionRequestMessage};

let messages = vec![
    ChatCompletionRequestMessage {
        content: Some("You are a helpful assistant that only speaks French.".to_string()),
        role: "system".to_string(),
        ..Default::default()
    },
    ChatCompletionRequestMessage {
        content: Some("Hello, how are you?".to_string()),
        role: "user".to_string(),
        ..Default::default()
    },
    ChatCompletionRequestMessage {
        content: Some("Parlez-vous francais?".to_string()),
        role: "system".to_string(),
        ..Default::default()
    },
];
let max_tokens = get_chat_completion_max_tokens("o1-mini", &messages).unwrap();
println!("max_tokens: {}", max_tokens);

Counting max_tokens parameter for a chat completion request with async-openai

Enable the async-openai feature in your Cargo.toml file.

# #[cfg(feature = "async-openai")]
# {
use tiktoken_rs::async_openai::get_chat_completion_max_tokens;
use async_openai::types::chat::{
    ChatCompletionRequestMessage, ChatCompletionRequestSystemMessage,
    ChatCompletionRequestSystemMessageContent, ChatCompletionRequestUserMessage,
    ChatCompletionRequestUserMessageContent,
};

let messages = vec![
    ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {
        content: ChatCompletionRequestSystemMessageContent::Text(
            "You are a helpful assistant that only speaks French.".to_string(),
        ),
        name: None,
    }),
    ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {
        content: ChatCompletionRequestUserMessageContent::Text(
            "Hello, how are you?".to_string(),
        ),
        name: None,
    }),
];
let max_tokens = get_chat_completion_max_tokens("o1-mini", &messages).unwrap();
println!("max_tokens: {}", max_tokens);
# }

tiktoken supports these encodings used by OpenAI models:

Encoding nameOpenAI models
o200k_harmonygpt-oss-20b, gpt-oss-120b
o200k_baseGPT-5 series, o1/o3/o4 series, gpt-4o, gpt-4.5, gpt-4.1, codex-*
cl100k_basegpt-4, gpt-3.5-turbo, text-embedding-ada-002, text-embedding-3-*
p50k_baseCode models, text-davinci-002, text-davinci-003
p50k_editEdit models like text-davinci-edit-001, code-davinci-edit-001
r50k_base (or gpt2)GPT-3 models like davinci
Context sizes

get_context_size uses the GPT-6 family default for any name beginning with gpt-6, including variants and snapshots. GPT-6 tokenizer lookup and token-budget helpers are unsupported because no encoding mapping is available.

ModelContext window
gpt-6*1,050,000
gpt-5.4, gpt-5.4-pro1,050,000
gpt-4.1, gpt-4.1-mini, gpt-4.1-nano1,047,576
gpt-5, gpt-5-mini, gpt-5-nano, gpt-5.4-mini, gpt-5.4-nano400,000
o1, o3, o3-mini, o3-pro, o4-mini200,000
codex-mini200,000
gpt-oss131,072
gpt-4o, gpt-4o-mini128,000
o1-mini, gpt-5.3-codex-spark128,000
gpt-3.5-turbo16,385
gpt-48,192

See the examples in the repo for use cases. For more context on the different tokenizers, see the OpenAI Cookbook

Encountered any bugs?

If you encounter any bugs or have any suggestions for improvements, please open an issue on the repository.

Acknowledgements

Thanks @spolu for the original code, and .tiktoken files.

License

This project is licensed under the MIT License.

Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

tiktoken-rs beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
tiktoken-rs This page Featured

Library for encoding and decoding with the tiktoken library in Rust

3,939,182 downloads over 30 days 449 410 0.12.1 GPU support unknown No native code found MIT
whatlang-rs Featured

Fast and lightweight language identification library for Rust.

882,019 downloads over 30 days 74 1,087 0.18.0 GPU support unknown No native code found MIT
sentencex Listed

Sentence segmentation library with wide language support optimized for speed and utility.

114,914 downloads over 30 days 1 145 0.1.34 GPU support unknown No native code found MIT
whichlang Listed

A blazingly fast and lightweight language detection library for Rust.

52,880 downloads over 30 days 11 464 0.1.1 GPU support unknown No native code found MIT

Rust runtime reimplementation of SentencePiece model loading, normalization, encoding, and decoding.

30,659 downloads over 30 days 5 2 0.2.2 GPU support unknown No native code found Apache-2.0
splintr Listed

Tokenizer for Rust and Python: pure Rust by default, with 18 bundled vocabularies and four backends covering BPE, SentencePiece and WordPiece. Its output matches Hugging Face tokenizers id for id on 14 model families, including GPT-2, Qwen, Whisper, T5 and BERT.

Python bindings

8,204 downloads over 30 days 7 63 0.22.2 GPU support unknown Binds native code: pcre2-sys (feature pcre2) MIT
xberg New

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.

26,095 downloads over 30 days 2 9,565 1.3.10 CUDA, Metal Binds native code: libheif-sys, libz-sys, xberg_libwpd, xberg_tesseract, clipper-sys and 4 more. Build uses a native toolchain: cc, bindgen (feature bindings), cmake (feature build-tesseract), pkg-config (feature dynamic-linking), vcpkg (feature dynamic-linking) MIT
Why FeaturedIt passes every Featured gate.

What it meets

  • It has 298 active dependents and 267 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days.
  • Active dependents are at 100% of their peak. Featured needs at least 50%.
  • Docs are present. The release commit or a manifest ties the crate to the repository.
  • No vulnerability advisory stays unpatched past the grace window. At least one version is neither a prerelease nor 0.0.x.
  • The last activity is on 24 Sep 2026, 46 days ago. The rules expect an update within 1200 days. Dormancy rule

Exact rules: Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.12.1 base 300, doubled for 3939182 downloads per month, doubled for 298.25 active users: E = 1200 days
  • dormancy: last activity 2026-09-24, 46 days ago, E = 1200: active
  • featured: featured: active_users 298.25, new_adopters 267, former_glory 1

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption298 active dependents, 267 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents298.25crates.io database dumpYes
New dependents (365 days)267crates.io database dumpYes
Peak active dependents294.25crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 46 days ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-09-24GitHub repositoryYes
Latest release2026-09-24crates.io database dumpYes
First release2023-02-02crates.io database dumpYes
Latest version0.12.1crates.io database dumpYes
Days the oldest outside issue waits for a reply298GitHub repositoryYes
Maintainer replies over 365 days15GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution36 releases, 3,939,182 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases36crates.io database dumpYes
Downloads over 30 days3939182crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository410 stars, 76 forks, 19 contributors, 208 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars410GitHub repositoryYes — one part of the repository route
GitHub forks76GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account19GitHub contributorsYes — one part of the repository route
Commits on the default branch208GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly449crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.