TiktokenSharp 1.2.1
dotnet add package TiktokenSharp --version 1.2.1
NuGet\Install-Package TiktokenSharp -Version 1.2.1
<PackageReference Include="TiktokenSharp" Version="1.2.1" />
<PackageVersion Include="TiktokenSharp" Version="1.2.1" />
<PackageReference Include="TiktokenSharp" />
paket add TiktokenSharp --version 1.2.1
#r "nuget: TiktokenSharp, 1.2.1"
#:package TiktokenSharp@1.2.1
#addin nuget:?package=TiktokenSharp&version=1.2.1
#tool nuget:?package=TiktokenSharp&version=1.2.1
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.
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
- TiktokenSharp Version: 1.2.0
- SharpToken Version: 2.0.1
- Benchmark Project:
TiktokenSharp.Benchmark
Run benchmark:
dotnet run --project TiktokenSharp.Benchmark/TiktokenSharp.Benchmark.csproj --framework net10.0 -c Release
List benchmarks:
dotnet run --project TiktokenSharp.Benchmark/TiktokenSharp.Benchmark.csproj --framework net10.0 -c Release -- --list flat
<details> <summary>Code:</summary>
private GptEncoding _sharpToken = GptEncoding.GetEncoding("cl100k_base");
private TikToken _tikToken = TikToken.GetEncoding("cl100k_base");
private string _kLongText = "King Lear, one of Shakespeare's darkest and most savage plays, tells the story of the foolish and Job-like Lear, who divides his kingdom, as he does his affections, according to vanity and whim. Lear’s failure as a father engulfs himself and his world in turmoil and tragedy.";
[Benchmark]
public int SharpToken()
{
var sum = 0;
for (var i = 0; i < 10000; i++)
{
var encoded = _sharpToken.Encode(_kLongText);
var decoded = _sharpToken.Decode(encoded);
sum += decoded.Length;
}
return sum;
}
[Benchmark]
public int TiktokenSharp()
{
var sum = 0;
for (var i = 0; i < 10000; i++)
{
var encoded = _tikToken.Encode(_kLongText);
var decoded = _tikToken.Decode(encoded);
sum += decoded.Length;
}
return sum;
}
</details>
| Method | Job | Runtime | Mean | Error | StdDev | Median | Gen0 | Allocated |
|---|---|---|---|---|---|---|---|---|
| SharpToken | .NET 10.0 | .NET 10.0 | 58.24 ms | 1.159 ms | 2.885 ms | 56.97 ms | 1000.0000 | 22.13 MB |
| TiktokenSharp | .NET 10.0 | .NET 10.0 | 40.85 ms | 0.806 ms | 0.754 ms | 40.71 ms | 1076.9231 | 13.28 MB |
| SharpToken | .NET 8.0 | .NET 8.0 | 67.04 ms | 1.281 ms | 1.258 ms | 67.42 ms | 1500.0000 | 22.13 MB |
| TiktokenSharp | .NET 8.0 | .NET 8.0 | 42.97 ms | 0.851 ms | 1.107 ms | 42.63 ms | 1076.9231 | 13.28 MB |
Update
1.2.1 20260222
- Fix cache write failures in read-only environments by falling back from
PBEFileDirectory/BaseDirectoryto systemTemp. - Add in-memory loading fallback when both cache directories are unavailable to avoid runtime crashes.
- Upgrade
TiktokenSharp.Testtarget framework to.NET 10. - Move benchmark code out of
TiktokenSharp.Testinto dedicated projectTiktokenSharp.Benchmark(net8.0+net10.0). - Remove
--benchmarkmode from test runner and keepTiktokenSharp.Testfocused 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 | Versions 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. |
-
.NETStandard 2.0
- IndexRange (>= 1.0.2)
- System.Memory (>= 4.5.3)
-
.NETStandard 2.1
- No dependencies.
-
net10.0
- No dependencies.
-
net7.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (5)
Showing the top 5 NuGet packages that depend on TiktokenSharp:
| Package | Downloads |
|---|---|
|
Mythosia.AI
## What's New in v6.5.0 ### New models (2026 refresh) - OpenAI: GPT-5.5, GPT-5.5 Pro (+ dated snapshots), GPT-5 Pro - Anthropic: Claude Opus 4.8, Claude Opus 4.7 - Google: Gemini 3.1 Pro (preview), Gemini 3.5 Flash, Gemini 3.1 Flash-Lite - xAI: Grok 4.3, Grok 4.20 (reasoning / non-reasoning), Grok Build 0.1 - Perplexity: Sonar Reasoning Pro - GPT-5.5 parameters via WithGpt5_5Parameters (reasoning effort none/low/medium/high/xhigh + verbosity). ### Provider fixes (current model API contracts) - Anthropic Opus 4.7/4.8: omit unsupported temperature; extended thinking now uses adaptive mode (thinking.type=adaptive + output_config.effort) instead of the rejected budget_tokens form. - OpenAI pro models: gpt-5-pro is sent the only supported "high" effort; gpt-5.2/5.4/5.5-pro clamp none/low to medium. - OpenAI image generation: the retired dall-e-3 is replaced with gpt-image-1 and the unsupported response_format is removed. GenerateImageUrlAsync now returns a base64 data: URI (gpt-image models do not provide hosted URLs). - Unified request timeout (single control point): the FunctionCallingPolicy timeout is now authoritative across completion/streaming/audio/image and is no longer silently capped by HttpClient.Timeout. Slow "pro" reasoning models get a 300s default. - xAI grok-build: omit unsupported frequency_penalty / presence_penalty. - Google Gemini 3 "pro": use the Low thinking level (not MINIMAL, which it rejects) when reasoning is disabled. ### Default models updated to current flagships - Anthropic Claude Sonnet 4.6, xAI Grok 4.3, Google Gemini 3.1 Pro (preview). ### Removed (retired / incompatible models) - grok-3, grok-4-0709, grok-4-1-fast, grok-4.20-multi-agent-0309, claude-sonnet-4-20250514, sonar-reasoning, gemini-3-pro-preview, gpt-5.3-codex-spark. These reference models that no longer function; update any by-name references to a current model. Requires Mythosia.AI.Abstractions v2.3.0. --- ## Documentation - Basic Usage: https://github.com/AJ-comp/Mythosia.AI/wiki - Advanced Features: https://github.com/AJ-comp/Mythosia.AI/wiki/Advanced-Features - Release Notes: https://github.com/AJ-comp/Mythosia.AI/wiki/Release-Notes - GitHub: https://github.com/AJ-comp/Mythosia.AI |
|
|
NjxyChatAISDK
支持通过API调用OpenAI、DeepSeek、Doubao |
|
|
Mythosia.AI.Providers.Alibaba
Alibaba Cloud Qwen provider package for Mythosia.AI. Includes QwenService with expanded Qwen 3 / 3.5 model constants, platform-specific thinking request handling across DashScope, vLLM, and Ollama, token usage streaming support, and Mythosia.AI v6.4.0 compatibility. Documentation - GitHub: https://github.com/AJ-comp/Mythosia.AI - Release Notes: core/Mythosia.AI.Providers.Alibaba/RELEASE_NOTES.md |
|
|
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.1 | 23,845 | 2/22/2026 | |
| 1.2.0 | 41,399 | 11/19/2025 | |
| 1.1.8 | 76,079 | 8/14/2025 | |
| 1.1.7 | 81,715 | 3/14/2025 | |
| 1.1.6 | 25,414 | 12/24/2024 | |
| 1.1.5 | 42,732 | 10/8/2024 | |
| 1.1.4 | 131,187 | 5/14/2024 | |
| 1.1.2 | 633 | 5/14/2024 | |
| 1.1.1 | 296 | 5/14/2024 | |
| 1.1.0 | 14,565 | 4/8/2024 | |
| 1.0.9 | 24,362 | 2/8/2024 | |
| 1.0.8 | 19,533 | 12/27/2023 | |
| 1.0.7 | 38,905 | 10/10/2023 | |
| 1.0.6 | 104,415 | 6/25/2023 | |
| 1.0.5 | 53,714 | 5/8/2023 | |
| 1.0.4 | 3,226 | 4/24/2023 | |
| 1.0.3 | 3,390 | 3/21/2023 | |
| 1.0.2 | 992 | 3/17/2023 | |
| 1.0.1 | 1,649 | 3/13/2023 | |
| 1.0.0 | 1,095 | 3/7/2023 |