TiktokenSharp 1.2.2

dotnet add package TiktokenSharp --version 1.2.2
                    
NuGet\Install-Package TiktokenSharp -Version 1.2.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TiktokenSharp" Version="1.2.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TiktokenSharp" Version="1.2.2" />
                    
Directory.Packages.props
<PackageReference Include="TiktokenSharp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TiktokenSharp --version 1.2.2
                    
#r "nuget: TiktokenSharp, 1.2.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TiktokenSharp@1.2.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TiktokenSharp&version=1.2.2
                    
Install as a Cake Addin
#tool nuget:?package=TiktokenSharp&version=1.2.2
                    
Install as a Cake Tool

TiktokenSharp

This library is a C# implementation of the token count calculation, referencing OpenAI's official Rust language version. Currently, the encoding algorithms for o200k_base, cl100k_base, and p50k_base have been implemented. You can directly obtain the corresponding encoding algorithm using the model name.

GPT-5.x models use o200k_base. GPT-6.x models, including gpt-6.2-astra and gpt-6.2-sol, use o200k_base for local text token estimates while the public tiktoken mapping omits GPT-6.x. OpenAI tiktoken model mappings

Getting Started

TiktokenSharp is available as NuGet package.

using TiktokenSharp;

//use model name
TikToken tikToken = TikToken.EncodingForModel("gpt-3.5-turbo");
var i = tikToken.Encode("hello world"); //[15339, 1917]
var d = tikToken.Decode(i); //hello world

//use encoding name
TikToken tikToken = TikToken.GetEncoding("cl100k_base");
var i = tikToken.Encode("hello world"); //[15339, 1917]
var d = tikToken.Decode(i); //hello world

When using a new encoder for the first time, the required tiktoken files for the encoder will be downloaded from the internet. This may take some time. Once the download is successful, subsequent uses will not require downloading again. You can set TikToken.PBEFileDirectory before using the encoder to modify the storage path of the downloaded tiktoken files, or you can pre-download the files to avoid network issues causing download failures.

Why are the tiktoken files not integrated into the package? On one hand, this would make the package size larger. On the other hand, I want to stay as consistent as possible with OpenAI's official Python code.

If you are deploying cloud functions, such as "Azure App Service," which cannot read/write local files, please package tiktoken files(PBE Dir) with the publish files.

Below are the file download links: p50k_base.tiktoken cl100k_base.tiktoken o200k_base.tiktoken

Benchmark Test

Measured on November 18, 2026, using BenchmarkDotNet 0.15.6, Windows 11 x64 (14 physical cores, 20 logical processors), and .NET SDK 10.0.403. All runs used Release builds, one launch, three warmup iterations, and eight measurement iterations. The tables report mean elapsed time and managed bytes allocated per operation.

Encode and decode

One operation encodes and decodes the same English paragraph 10,000 times using an initialized cl100k_base encoder. Both libraries process the same text. Benchmark source

Runtime Library Mean per 10,000 round trips Allocated per 10,000 round trips
.NET 10.0.14 SharpToken 2.0.6 55.94 ms 22.13 MiB
.NET 10.0.14 TiktokenSharp 37.61 ms 11.67 MiB
.NET 8.0.33 SharpToken 2.0.6 65.59 ms 22.13 MiB
.NET 8.0.33 TiktokenSharp 39.12 ms 11.67 MiB

Individual operations

Both builds ran the same four benchmarks on .NET 10.0.14 with a live cl100k_base encoder. Each row measures one call. The long-piece input is a single run of 8,192 ASCII a characters. Baseline commit 779cf1b · Benchmark source

Operation Baseline mean Optimized mean Baseline allocation Optimized allocation
Get an already loaded encoding 46.59 ms 5.57 µs 36,340,341 B 1,328 B
Count one English sentence 629.6 ns 589.3 ns 128 B 0 B
Count one 8,192-byte piece 50.96 ms 1.18 ms 65,728 B 0 B
Decode the tokens for 256 copies of the sentence 24.70 µs 18.00 µs 102,560 B 32,792 B

First vocabulary load

A separate fresh-process measurement loaded o200k_base from a local vocabulary file on .NET 10.0.14 with tiered compilation disabled. The first GetEncoding call allocated 71.51 MiB on the baseline and 20.85 MiB on the optimized build. With the encoder still alive, the increase in managed heap size after a full GC was 17.77 MiB and 9.17 MiB, respectively.

Reproduce

Run the BenchmarkDotNet workloads from the repository root with the .NET 10 SDK and both .NET 8 and .NET 10 runtimes installed.

dotnet run --project TiktokenSharp.Benchmark -f net10.0 -c Release -- --filter "*" --launchCount 1 --warmupCount 3 --iterationCount 8

Use --list flat to list the benchmarks, or replace "*" with "*TokenizerBenchmarks*" to run only the individual operations.

To reproduce the baseline column, check out 779cf1b in a separate worktree, copy the same TokenizerBenchmarks.cs into its benchmark project, and run the individual operations there.

Update

1.2.2 20261118

  • Use o200k_base for local token count estimates for GPT-6.x models.
  • Stream vocabulary files and reuse loaded vocabularies and encoders across factory calls. On .NET 10, loading o200k_base from disk allocated 20.85 MiB, down from 71.51 MiB.
  • Speed up encoding and counting long pieces on .NET 7 and later. In the .NET 10 benchmark, counting 8,192 consecutive ASCII a characters took 1.18 ms, down from 50.96 ms. Benchmark results
  • Encode ReadOnlySpan<char> inputs directly and reuse buffers when counting tokens and decoding text to reduce temporary allocations.

1.2.1 20260222

  • Fix cache write failures in read-only environments by falling back from PBEFileDirectory/BaseDirectory to system Temp.
  • Add in-memory loading fallback when both cache directories are unavailable to avoid runtime crashes.
  • Upgrade TiktokenSharp.Test target framework to .NET 10.
  • Move benchmark code out of TiktokenSharp.Test into dedicated project TiktokenSharp.Benchmark (net8.0 + net10.0).
  • Remove --benchmark mode from test runner and keep TiktokenSharp.Test focused on functional validation.

1.2.0 20251119

  • Optimize memory allocation and execution efficiency.

1.1.8 20250814

  • Add Support gpt-5 models.

1.1.7 20250314

  • Add Support o3 models.

1.1.6 20241224

  • Optimize model name matching encoding.

1.1.5 20240913

  • Add Support o1 models(o200k_base).

1.1.4 20240514

  • Add Support gpt-4o(o200k_base).

1.1.0 20240408

  • Optimize algorithm efficiency.

1.0.9 20240208

  • Adding support for new OpenAI embeddings. by @winzig

1.0.7 20231010

  • Corrected the issue where some new models could not properly obtain the encoder.

1.0.7 20231010

  • Corrected the issue where some new models could not properly obtain the encoder.

1.0.6 20230625

  • Replace WebClient with HttpClient, add async methods.

1.0.5 20230508

  • New support for .Net Standard 2.0 has been added, making TiktokenSharp usable in the .Net Framework.

1.0.4 20230424

  • Add method TikToken.GetEncoding(encodingName).

1.0.3 20230321

  • GetEncodingSetting now supports the model of gpt-4 and also allows for encoding names to be directly passed in.

1.0.2 20230317

  • add method TikToken.PBEFileDirectory to allow for custom storage directory of bpe files. the path needs to be set before TikToken.EncodingForModel().

1.0.1 20230313

  • p50k_base encoding algorithm that supports the text-davinci-003 model.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

  • .NETStandard 2.1

    • No dependencies.
  • net10.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages (7)

Showing the top 5 NuGet packages that depend on TiktokenSharp:

Package Downloads
Mythosia.AI

Build .NET applications with multiple AI providers through consistent completion, streaming and tool workflows. Supports OpenAI GPT-6.1 Sol and GPT-6 Astra/Sol/Luna, Anthropic including Claude Sonnet 5.5 and Opus 5.5, Google, xAI including Grok 4.7, DeepSeek Flash/V4 Pro and Perplexity. Includes immutable request builders, controllable Runs, typed output, cancellable local tools, reasoning, search/citations, image generation/editing, capability inspection and per-request processing-speed observations. Targets .NET Standard 2.1; requires Mythosia.AI.Abstractions 4.2.0. What's New in v8.2.0: GPT-6.1 Sol adds mandatory reasoning, Responses tools and native Run support; Sonnet 5.5 adds adaptive/high defaults and explicit between-tools thinking. Request preparation captures effective settings, runs profile hooks once and validates before side effects. Nested auxiliary requests isolate parent state; forwarded profile changes preserve later request-local tool and policy edits. Claude retains signed and tool history across projection, counting and permitted compaction, preserves persistent instructions, and serializes valid lowercase tool schemas. Streaming fixes cover producer cleanup, HTTP error-body cancellation, identifiable HttpClient timeouts and preservation of outcomes during response disposal. OpenAI Run honors configured endpoints and preserves steering order, cancellation boundaries and terminal outcomes. Existing public execution APIs and service defaults remain. Known limitations: Sonnet 5.5/Opus 5.5 pauses ending in a pending server_tool_use can be rejected before continuation. Custom buffering HTTP content can delay successful SSE body acquisition past cancellation or timeout, retaining the active Run. These cases remain unfixed. Full release notes: https://github.com/AJ-comp/Mythosia.AI/blob/main/src/core/Mythosia.AI/RELEASE_NOTES.md#v820

Mythosia.AI.Providers.Alibaba

Call Qwen chat endpoints on DashScope, vLLM or Ollama while using the shared Mythosia.AI conversation and tool APIs. QwenService supports provider-specific thinking controls, custom deployment names, streaming usage, immutable request configuration, cancellable local tools, controllable runs and local model-capability inspection. Requires Mythosia.AI 8.2.0. What's New in v3.0.2: Completion uses the prepared request message snapshot for request context and history consistency. Public APIs, endpoint defaults and thinking controls remain unchanged. Native steering, hosted search and image generation are outside this adapter.

NjxyChatAISDK

支持通过API调用OpenAI、DeepSeek、Doubao、Qwen

TokenFlow.Tokenizers

Model-specific tokenizer implementations for TokenFlow.AI (OpenAI, Claude, etc.).

Serina.Semantic.Ai.Pipelines

Serina Pipelines for Semantic Kernel allows to build flexible Ai Proccessing pipelines.

GitHub repositories (3)

Showing the top 3 popular GitHub repositories that depend on TiktokenSharp:

Repository Stars
StartupHakk/OpenMonoAgent.ai
(BETA) AI shouldn't have a meter. Unlimited tokens. Forever. Your machine. Your agent. Use it from anywhere. Terminal-native coding agent powered by local LLMs — 100% open source, free forever, and installed with a single command. Proudly built on C#/.NET, because AI tooling should be infrastructure, not a subscription.
MayDay-wpf/AIBotPublic
AIBot PRO 是一个基于.NET 8 的 AI聚合客户端 to C 弱 to B 可以集成众多AI产品(ChatGPT,Gemini,Claude,文心一言,通义千问,讯飞星火),无感切换对话,支持知识库、插件开发、AI流程引擎(workflow)、以及开放平台对外输出定制化的特色AI API
dmitry-brazhenko/SharpToken
SharpToken is a C# library for tokenizing natural language text. It's based on the tiktoken Python library and designed to be fast and accurate.
Version Downloads Last Updated
1.2.2 708 11/18/2026
1.2.1 325,624 2/22/2026
1.2.0 69,801 11/19/2025
1.1.8 109,555 8/14/2025
1.1.7 120,578 3/14/2025
1.1.6 32,801 12/24/2024
1.1.5 62,994 10/8/2024
1.1.4 174,519 5/14/2024
1.1.2 680 5/14/2024 1.1.2 is deprecated because it has critical bugs.
1.1.1 344 5/14/2024 1.1.1 is deprecated because it has critical bugs.
1.1.0 18,985 4/8/2024
1.0.9 26,371 2/8/2024
1.0.8 20,773 12/27/2023
1.0.7 47,751 10/10/2023
1.0.6 109,328 6/25/2023
1.0.5 54,146 5/8/2023
1.0.4 4,274 4/24/2023
1.0.3 3,688 3/21/2023
1.0.2 1,764 3/17/2023
1.0.1 1,719 3/13/2023
Loading failed