j_r_r_token 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2ec532950d7c7718d14e303c9c43d18df4eb6d191bb4dd56cfc1b9dbc62cd673
4
- data.tar.gz: c9bff0c4a3cd9c815b45ee7bd1362d71c12f198241bbbee605050d5addfb9feb
3
+ metadata.gz: 2f3baf82fbf9b744b9f8a880ab523e178f5073ee1ee728868dc73dabd9a57b6c
4
+ data.tar.gz: '09c452ed68be23c87398cd3f66675284f073fb2ea986668f108a6ca91769c299'
5
5
  SHA512:
6
- metadata.gz: ef83e1a569ff920d8cbd55d7f3109c883b2e1b7e5fe561db7f2ac3e67fe3de8d1ad4c552b9bd10c9bbfb9af783331dac0c65d7b45f49af8bc0efd7c8849f747f
7
- data.tar.gz: c990330066e627ca909479fefb397480d05da12401aa23383c96e53c58bae351c2bc4e9ad535d476153507a67333e90cf6cd607e6dfd5590f716a02ce26d1acd
6
+ metadata.gz: 9aaf19432b00274f29165467a415c982c36ce66ef9c71ae42e7b864ed344104f8afb00afa8aa3f81b8c456e8c0f7a2668a0ca919a8ad758a03712c231db32505
7
+ data.tar.gz: 5e0ae9cf031fa5936f7180be731475831831a40983a98b36187de72f245a4beb9076da2849268bb160877989fd7b15c8b4152cfc49d3af2877ab11a7a58f2b10
data/CHANGELOG.md CHANGED
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ---
11
+ ## [1.3.0] - 2026-11-22
12
+ ### Breaking Change
13
+ - Model mapping now matches OpenAI's tiktoken 0.14.0 exactly (via `tiktoken-rs` 0.12.1). `tiktoken-rs` 0.11 carried its own extra `o4` / `o4-*` mappings that OpenAI's tiktoken never had (it only maps `o4-mini`); 0.12 dropped them, so bare `o4` and `o4-pro` (any `o4-*` other than `o4-mini*`) now raise `ArgumentError`, as do fine-tunes of them (e.g. `ft:o4`). Use `o4-mini` or pass `o200k_base` directly.
14
+
15
+ ### Fix
16
+ - A whitespace run of ~1M+ characters followed by text previously killed the process with an uncatchable `fatal` (a Rust panic). It now raises a regular `RuntimeError` ("Could not encode string: ..."), so apps counting untrusted input can rescue it.
17
+
18
+ ### Change
19
+ - Bumped `tiktoken-rs` from 0.11.0 to 0.12.1, which vendors OpenAI's tiktoken 0.14.0 core.
20
+ - Following OpenAI's tiktoken 0.14.0, any model name beginning with `gpt-5` now resolves to `o200k_base` (previously only `gpt-5`, `gpt-5-*` and `gpt-5.*`).
21
+ - Long repetitive input no longer hits a quadratic slowdown: upstream's large-piece BPE merge brings 200 KB of `"a"` from ~15 s to well under a second. Counts are unchanged (verified against 0.11.0 across all encodings).
22
+ - The allowed special-token set is now built once per encoding instead of on every call; repeat `gpt-oss` (`o200k_harmony`, ~1,100 special tokens) counts are now on par with the other encodings.
23
+ - Building from source (the generic gem or `rake compile`) now requires Rust 1.85 or newer. Precompiled platform gems are unaffected.
24
+ - Tokenizers are now built once per process and cached (via `tiktoken_rs::bpe_for_tokenizer`) instead of being rebuilt on every `count` call. Previously each call decoded the full vocabulary and compiled the tokenizer regexes, costing ~20–120 ms per call depending on the encoding; repeat calls are now sub-millisecond for short text. The first call for each encoding still pays the one-time build cost.
25
+ - Memory tradeoff: each encoding, once used, now stays resident for the life of the process. Approximate RSS per encoding: `o200k_base` ~45 MB, `o200k_harmony` ~47 MB, `cl100k_base` ~24 MB, `p50k_base` / `p50k_edit` / `r50k_base` ~10 MB each. Only encodings you actually call are loaded.
26
+ - Bumped `magnus` from 0.8.2 to 0.8.5 (patch fixes). Staying on the 0.8 series, the last to support Ruby 3.0.
27
+ - Migrated the extension off magnus's deprecated "old-api" (global `define_module` / `exception::*`) to the `&Ruby` handle API and dropped the `old-api` feature flag. No behavior change.
28
+ - Bumped `rb_sys` (gem and crate) from 0.9.128 to 0.9.130. It still pins `rake-compiler-dock` 1.12.0, so Ruby 3.0 platform gems are unaffected.
29
+ - README: documented the `RuntimeError` case, the one-time build cost and memory per encoding (with a boot-time warm-up tip for preforking servers), and the Rust >= 1.85 requirement for source builds.
30
+ - Gemspec description now lists `o200k_harmony`; added RBS signatures for `JRRToken::Tokenizer.count`.
31
+ - CI: the cross-gem matrix is now an explicit allowlist of the seven platforms this gem ships (`aarch64-linux`, `aarch64-linux-musl`, `arm-linux`, `arm64-darwin`, `x86_64-darwin`, `x86_64-linux`, `x86_64-linux-musl`) instead of an exclude list. The platform list comes from rb-sys `main` at release time, so new rb-sys targets (e.g. `arm-linux-musl`, added in 0.9.130) previously slipped into the release matrix; adding a platform is now a deliberate edit.
32
+ - CI: test jobs pin `ubuntu-24.04` instead of `ubuntu-latest`. Ruby 3.2.11's ubuntu-26.04 build (from ruby/ruby-builder, compiled with GCC 15 in C23 mode) lacks `HAVE_STDBOOL_H` in its `config.h`, so rb-sys's bindgen step fails with "unknown type name 'bool'". Other Ruby versions on that image, and Ruby 3.2 on the ARM Linux and macOS runners, were unaffected.
33
+
10
34
  ---
11
35
  ## [1.2.1] - 2026-05-13
12
36
  ### Breaking Change
data/Cargo.lock CHANGED
@@ -36,9 +36,9 @@ dependencies = [
36
36
  "proc-macro2",
37
37
  "quote",
38
38
  "regex",
39
- "rustc-hash 2.1.2",
39
+ "rustc-hash",
40
40
  "shlex",
41
- "syn",
41
+ "syn 2.0.104",
42
42
  ]
43
43
 
44
44
  [[package]]
@@ -64,13 +64,13 @@ checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
64
64
 
65
65
  [[package]]
66
66
  name = "bstr"
67
- version = "1.12.1"
67
+ version = "1.14.0"
68
68
  source = "registry+https://github.com/rust-lang/crates.io-index"
69
- checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"
69
+ checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
70
70
  dependencies = [
71
71
  "memchr",
72
72
  "regex-automata",
73
- "serde",
73
+ "serde_core",
74
74
  ]
75
75
 
76
76
  [[package]]
@@ -107,9 +107,9 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
107
107
 
108
108
  [[package]]
109
109
  name = "fancy-regex"
110
- version = "0.17.0"
110
+ version = "0.19.2"
111
111
  source = "registry+https://github.com/rust-lang/crates.io-index"
112
- checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8"
112
+ checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
113
113
  dependencies = [
114
114
  "bit-set",
115
115
  "regex-automata",
@@ -163,9 +163,9 @@ dependencies = [
163
163
 
164
164
  [[package]]
165
165
  name = "magnus"
166
- version = "0.8.2"
166
+ version = "0.8.5"
167
167
  source = "registry+https://github.com/rust-lang/crates.io-index"
168
- checksum = "3b36a5b126bbe97eb0d02d07acfeb327036c6319fd816139a49824a83b7f9012"
168
+ checksum = "8137349730ade4d395b6cfb3fca073f09d6fdc35b276af17f5b974c44ccc3a21"
169
169
  dependencies = [
170
170
  "magnus-macros",
171
171
  "rb-sys",
@@ -181,7 +181,7 @@ checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
181
181
  dependencies = [
182
182
  "proc-macro2",
183
183
  "quote",
184
- "syn",
184
+ "syn 2.0.104",
185
185
  ]
186
186
 
187
187
  [[package]]
@@ -226,18 +226,18 @@ dependencies = [
226
226
 
227
227
  [[package]]
228
228
  name = "rb-sys"
229
- version = "0.9.128"
229
+ version = "0.9.130"
230
230
  source = "registry+https://github.com/rust-lang/crates.io-index"
231
- checksum = "45ca28513560e56cfb79a62b1fce363c73af170a182024ce880c77ee9429920a"
231
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
232
232
  dependencies = [
233
233
  "rb-sys-build",
234
234
  ]
235
235
 
236
236
  [[package]]
237
237
  name = "rb-sys-build"
238
- version = "0.9.128"
238
+ version = "0.9.130"
239
239
  source = "registry+https://github.com/rust-lang/crates.io-index"
240
- checksum = "ce04b2c55eff3a21aaa623fcc655d94373238e72cac6b3e1a3641ff31649f99a"
240
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
241
241
  dependencies = [
242
242
  "bindgen",
243
243
  "lazy_static",
@@ -245,7 +245,7 @@ dependencies = [
245
245
  "quote",
246
246
  "regex",
247
247
  "shell-words",
248
- "syn",
248
+ "syn 2.0.104",
249
249
  ]
250
250
 
251
251
  [[package]]
@@ -256,9 +256,9 @@ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
256
256
 
257
257
  [[package]]
258
258
  name = "regex"
259
- version = "1.12.3"
259
+ version = "1.13.2"
260
260
  source = "registry+https://github.com/rust-lang/crates.io-index"
261
- checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
261
+ checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
262
262
  dependencies = [
263
263
  "aho-corasick",
264
264
  "memchr",
@@ -268,9 +268,9 @@ dependencies = [
268
268
 
269
269
  [[package]]
270
270
  name = "regex-automata"
271
- version = "0.4.14"
271
+ version = "0.4.19"
272
272
  source = "registry+https://github.com/rust-lang/crates.io-index"
273
- checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
273
+ checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
274
274
  dependencies = [
275
275
  "aho-corasick",
276
276
  "memchr",
@@ -279,15 +279,9 @@ dependencies = [
279
279
 
280
280
  [[package]]
281
281
  name = "regex-syntax"
282
- version = "0.8.5"
282
+ version = "0.8.12"
283
283
  source = "registry+https://github.com/rust-lang/crates.io-index"
284
- checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
285
-
286
- [[package]]
287
- name = "rustc-hash"
288
- version = "1.1.0"
289
- source = "registry+https://github.com/rust-lang/crates.io-index"
290
- checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
284
+ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
291
285
 
292
286
  [[package]]
293
287
  name = "rustc-hash"
@@ -302,23 +296,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
302
296
  checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
303
297
 
304
298
  [[package]]
305
- name = "serde"
306
- version = "1.0.219"
299
+ name = "serde_core"
300
+ version = "1.0.229"
307
301
  source = "registry+https://github.com/rust-lang/crates.io-index"
308
- checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
302
+ checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
309
303
  dependencies = [
310
304
  "serde_derive",
311
305
  ]
312
306
 
313
307
  [[package]]
314
308
  name = "serde_derive"
315
- version = "1.0.219"
309
+ version = "1.0.229"
316
310
  source = "registry+https://github.com/rust-lang/crates.io-index"
317
- checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
311
+ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
318
312
  dependencies = [
319
313
  "proc-macro2",
320
314
  "quote",
321
- "syn",
315
+ "syn 3.0.10",
322
316
  ]
323
317
 
324
318
  [[package]]
@@ -344,19 +338,29 @@ dependencies = [
344
338
  "unicode-ident",
345
339
  ]
346
340
 
341
+ [[package]]
342
+ name = "syn"
343
+ version = "3.0.10"
344
+ source = "registry+https://github.com/rust-lang/crates.io-index"
345
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
346
+ dependencies = [
347
+ "proc-macro2",
348
+ "quote",
349
+ "unicode-ident",
350
+ ]
351
+
347
352
  [[package]]
348
353
  name = "tiktoken-rs"
349
- version = "0.11.0"
354
+ version = "0.12.1"
350
355
  source = "registry+https://github.com/rust-lang/crates.io-index"
351
- checksum = "fac4a168cfc1d8ed65bf17a6ee0843ad9a68f863c63c0fb2fa7eab67838782ee"
356
+ checksum = "2aeff724640cfe13037336ddf35befdffd2909cbdb65cf041cc8a4cf8c584cfa"
352
357
  dependencies = [
353
358
  "anyhow",
354
359
  "base64",
355
360
  "bstr",
356
361
  "fancy-regex",
357
- "lazy_static",
358
362
  "regex",
359
- "rustc-hash 1.1.0",
363
+ "rustc-hash",
360
364
  ]
361
365
 
362
366
  [[package]]
data/README.md CHANGED
@@ -1,10 +1,17 @@
1
- # JRRToken [<img src="https://github.com/LoganBresnahan/j_r_r_token/raw/main/.github/assets/ring.png" width="32px" alt="One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them.">](https://www.youtube.com/watch?v=lemgdzLDYqA)
1
+ <p align="center">
2
+ <img src="https://github.com/LoganBresnahan/j_r_r_token/raw/main/.github/assets/rings.png" height="120px" alt="JRRToken" />
3
+ </p>
2
4
 
3
- (Just Ruby, Rust, & Tokens)
5
+ <h1 align="center">JRRToken</h1>
6
+ <h2 align="center">v1.3.0</h2>
7
+
8
+ <p align="center">(Just Ruby, Rust, &amp; Tokens)</p>
9
+
10
+ ---
4
11
 
5
12
  JRRToken provides a high-performance, native Ruby interface for counting tokens using the powerful [tiktoken-rs](https://github.com/zurawiki/tiktoken-rs) library. It leverages the speed of Rust to offer a fast and efficient way to calculate token counts for various OpenAI models.
6
13
 
7
- The gem ships with pre-compiled native extensions for Linux and macOS, so your end-users don't need a Rust toolchain installed.
14
+ The gem ships with pre-compiled native extensions for Linux and macOS, so your end-users don't need a Rust toolchain installed. On other platforms the gem builds from source, which requires Rust >= 1.85.
8
15
 
9
16
  Supports Ruby >= 3.0.0
10
17
 
@@ -15,10 +22,10 @@ Extensive Model Support: Includes tokenizers for all modern and legacy OpenAI mo
15
22
  ## Install
16
23
 
17
24
  #### Gemfile
18
- `gem 'j_r_r_token', '~> 1.2'`
25
+ `gem 'j_r_r_token', '~> 1.3'`
19
26
 
20
27
  #### Command Line
21
- `gem install j_r_r_token -v '~> 1.2'`
28
+ `gem install j_r_r_token -v '~> 1.3'`
22
29
 
23
30
  ## Use
24
31
 
@@ -37,7 +44,10 @@ count = JRRToken::Tokenizer.count("hello world!", model: "text-davinci-003")
37
44
  count = JRRToken::Tokenizer.count(1234, model: "o200k_base")
38
45
  ```
39
46
 
40
- If you provide an unsupported model name, the gem will raise an `ArgumentError`.
47
+ ### Errors
48
+ - An unsupported model name raises `ArgumentError`.
49
+ - A model that isn't a String (e.g. `nil` or a Symbol) raises `TypeError`.
50
+ - If the tokenizer itself fails on pathological input (for example, a whitespace run of roughly a million characters followed by text), the gem raises `RuntimeError`. When counting untrusted input, rescue it or cap the input size.
41
51
 
42
52
  ## Supported Models
43
53
  The gem automatically maps dozens of model names and prefixes to the correct underlying tokenizer. You don't need to know the tokenizer's base name (e.g., cl100k_base); just use the model name you're working with. Model resolution is delegated to [`tiktoken-rs`](https://github.com/zurawiki/tiktoken-rs), so the alias list stays in sync with upstream.
@@ -51,6 +61,18 @@ The gem automatically maps dozens of model names and prefixes to the correct und
51
61
 
52
62
  Fine-tuned models (`ft:<base>:org:name:id`) are automatically resolved to the same tokenizer as their base model.
53
63
 
64
+ ## Performance and Memory
65
+ Each tokenizer is built the first time you use it (roughly 15–85 ms, depending on the encoding) and then cached for the life of the process, so later calls are fast. A cached tokenizer stays in memory: roughly 45 MB for `o200k_base` and `o200k_harmony`, 24 MB for `cl100k_base`, and 10 MB each for the older encodings. Only the encodings you actually use are loaded.
66
+
67
+ To keep that one-time cost out of your first request, warm up the encodings you use at boot:
68
+
69
+ ```Ruby
70
+ # e.g. config/initializers/j_r_r_token.rb
71
+ JRRToken::Tokenizer.count("", model: "gpt-4o")
72
+ ```
73
+
74
+ With a preforking server (Puma with `preload_app!`, Unicorn with `preload_app true`), warming up before the fork lets the workers share the tokenizer memory copy-on-write instead of each building its own.
75
+
54
76
  ## Developing JRRToken Locally
55
77
 
56
78
  ### Install Ruby and Rust dependencies
@@ -58,7 +80,7 @@ Ruby >= 3.0.0
58
80
 
59
81
  RubyGems >= 3.0.0
60
82
 
61
- Rust edition 2021
83
+ Rust >= 1.85
62
84
 
63
85
  ### Compile the Rust extension and run tests
64
86
  Compile:
@@ -9,5 +9,5 @@ publish = false
9
9
  crate-type = ["cdylib"]
10
10
 
11
11
  [dependencies]
12
- magnus = { version = "0.8", features = ["old-api"] }
13
- tiktoken-rs = { version = "0.11" }
12
+ magnus = "0.8.5"
13
+ tiktoken-rs = "0.12.1"
@@ -1,52 +1,73 @@
1
- use magnus::{define_module, exception, function, Error};
1
+ use std::{collections::HashSet, sync::OnceLock};
2
+
3
+ use magnus::{function, Error, Ruby};
2
4
  use tiktoken_rs::{
3
- cl100k_base, o200k_base, o200k_harmony, p50k_base, p50k_edit, r50k_base,
5
+ bpe_for_tokenizer,
4
6
  tokenizer::{get_tokenizer, Tokenizer},
5
7
  CoreBPE,
6
8
  };
7
9
 
8
- // Resolves a model name (or bare encoding name) to a CoreBPE instance.
10
+ // Resolves a model name (or bare encoding name) to a tokenizer.
9
11
  // Model -> tokenizer dispatch is delegated to `tiktoken_rs::tokenizer::get_tokenizer`,
10
12
  // which is kept in sync with upstream OpenAI tiktoken. It handles `ft:` prefix
11
- // stripping, GPT-5/4.5/4.1/4o families, o1/o3/o4 reasoning models, gpt-oss
13
+ // stripping, GPT-5/4.5/4.1/4o families, o1/o3/o4-mini reasoning models, gpt-oss
12
14
  // (harmony), codex-mini, and all legacy aliases.
13
- fn get_bpe_from_model(model: &str) -> Result<CoreBPE, Error> {
14
- let tokenizer_result = match model {
15
+ fn tokenizer_for(model: &str) -> Option<Tokenizer> {
16
+ match model {
15
17
  // Bare encoding names — callers may pass these directly.
16
- "o200k_harmony" => o200k_harmony(),
17
- "o200k_base" => o200k_base(),
18
- "cl100k_base" => cl100k_base(),
19
- "p50k_base" => p50k_base(),
20
- "p50k_edit" => p50k_edit(),
21
- "r50k_base" => r50k_base(),
22
- _ => match get_tokenizer(model) {
23
- Some(Tokenizer::O200kHarmony) => o200k_harmony(),
24
- Some(Tokenizer::O200kBase) => o200k_base(),
25
- Some(Tokenizer::Cl100kBase) => cl100k_base(),
26
- Some(Tokenizer::P50kBase) => p50k_base(),
27
- Some(Tokenizer::P50kEdit) => p50k_edit(),
28
- Some(Tokenizer::R50kBase) | Some(Tokenizer::Gpt2) => r50k_base(),
29
- None => {
30
- return Err(Error::new(
31
- exception::arg_error(),
32
- format!("Model '{}' not supported.", model),
33
- ));
34
- }
35
- },
18
+ "o200k_harmony" => Some(Tokenizer::O200kHarmony),
19
+ "o200k_base" => Some(Tokenizer::O200kBase),
20
+ "cl100k_base" => Some(Tokenizer::Cl100kBase),
21
+ "p50k_base" => Some(Tokenizer::P50kBase),
22
+ "p50k_edit" => Some(Tokenizer::P50kEdit),
23
+ "r50k_base" => Some(Tokenizer::R50kBase),
24
+ _ => get_tokenizer(model),
25
+ }
26
+ }
27
+
28
+ // Returns the special tokens allowed when counting (all of the encoding's special
29
+ // tokens, matching `encode_with_special_tokens`). The set is built once per encoding
30
+ // and cached: `CoreBPE::special_tokens()` allocates a fresh set on every call, which
31
+ // is noticeable for o200k_harmony (~1,100 special tokens).
32
+ fn allowed_special(tokenizer: Tokenizer, bpe: &'static CoreBPE) -> &'static HashSet<&'static str> {
33
+ static SETS: [OnceLock<HashSet<&'static str>>; 6] = [const { OnceLock::new() }; 6];
34
+ let index = match tokenizer {
35
+ Tokenizer::O200kHarmony => 0,
36
+ Tokenizer::O200kBase => 1,
37
+ Tokenizer::Cl100kBase => 2,
38
+ Tokenizer::P50kBase => 3,
39
+ Tokenizer::P50kEdit => 4,
40
+ // Gpt2 resolves to the same r50k_base singleton.
41
+ Tokenizer::R50kBase | Tokenizer::Gpt2 => 5,
36
42
  };
37
- tokenizer_result.map_err(|e| Error::new(exception::runtime_error(), e.to_string()))
43
+ SETS[index].get_or_init(|| bpe.special_tokens())
38
44
  }
39
45
 
40
46
  // This function is exposed to Ruby.
41
- fn count_tokens(model: String, text: String) -> Result<usize, Error> {
42
- let bpe = get_bpe_from_model(&model)?;
43
- let tokens = bpe.encode_with_special_tokens(&text);
44
- Ok(tokens.len())
47
+ fn count_tokens(ruby: &Ruby, model: String, text: String) -> Result<usize, Error> {
48
+ let tokenizer = tokenizer_for(&model).ok_or_else(|| {
49
+ Error::new(
50
+ ruby.exception_arg_error(),
51
+ format!("Model '{}' not supported.", model),
52
+ )
53
+ })?;
54
+
55
+ // `bpe_for_tokenizer` returns a process-wide `&'static CoreBPE` singleton, so the
56
+ // vocabulary is decoded and the regexes are compiled once per encoding, not on
57
+ // every call. It currently never returns `Err` (a failed build panics inside
58
+ // tiktoken-rs's lazy static); the `map_err` only guards against future changes.
59
+ let bpe = bpe_for_tokenizer(tokenizer)
60
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))?;
61
+
62
+ // `count` (unlike `count_with_special_tokens`) reports tokenizer regex failures as an
63
+ // error instead of panicking, so Ruby gets a RuntimeError rather than `fatal`.
64
+ bpe.count(&text, allowed_special(tokenizer, bpe))
65
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))
45
66
  }
46
67
 
47
68
  #[magnus::init]
48
- fn init() -> Result<(), Error> {
49
- let module = define_module("JRRToken")?;
69
+ fn init(ruby: &Ruby) -> Result<(), Error> {
70
+ let module = ruby.define_module("JRRToken")?;
50
71
  module.define_module_function("count_tokens", function!(count_tokens, 2))?;
51
72
  Ok(())
52
73
  }
data/j_r_r_token.gemspec CHANGED
@@ -9,7 +9,7 @@ Gem::Specification.new do |spec|
9
9
  spec.email = ["loganbbres@gmail.com"]
10
10
 
11
11
  spec.summary = "Ruby wrapper for the tiktoken Rust library, providing fast tokenization for OpenAI models."
12
- spec.description = "JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling fast and efficient tokenization for OpenAI models. It supports multiple models including o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base."
12
+ spec.description = "JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling fast and efficient tokenization for OpenAI models. It supports the o200k_harmony, o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base encodings."
13
13
  spec.homepage = "https://github.com/LoganBresnahan/j_r_r_token"
14
14
  spec.license = "MIT"
15
15
  spec.required_ruby_version = ">= 3.0.0"
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JRRToken
4
- VERSION = "1.2.1"
4
+ VERSION = "1.3.0"
5
5
  end
data/sig/j_r_r_token.rbs CHANGED
@@ -1,4 +1,15 @@
1
1
  module JRRToken
2
2
  VERSION: String
3
- # See the writing guide of rbs: https://github.com/ruby/rbs#guides
3
+
4
+ # Native extension entry point (implemented in Rust).
5
+ def self.count_tokens: (String model, String text) -> Integer
6
+
7
+ class Error < StandardError
8
+ end
9
+
10
+ class Tokenizer
11
+ # Counts tokens in `text` (converted with #to_s) for the given model or encoding name.
12
+ # Raises ArgumentError for an unsupported model, RuntimeError if tokenization fails.
13
+ def self.count: (_ToS text, model: String) -> Integer
14
+ end
4
15
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: j_r_r_token
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.1
4
+ version: 1.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Logan Bresnahan
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-05-13 00:00:00.000000000 Z
11
+ date: 2026-11-23 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -53,8 +53,8 @@ dependencies:
53
53
  - !ruby/object:Gem::Version
54
54
  version: '0'
55
55
  description: JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling
56
- fast and efficient tokenization for OpenAI models. It supports multiple models including
57
- o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base.
56
+ fast and efficient tokenization for OpenAI models. It supports the o200k_harmony,
57
+ o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base encodings.
58
58
  email:
59
59
  - loganbbres@gmail.com
60
60
  executables: []