j_r_r_token 1.1.0 → 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: 52cec2e717280a266a6c1a83c629dbb2944b781fb54401f6729e8cfc947d9a03
4
- data.tar.gz: 6a6e3b673858c11cb5b13cef84e995d63eefbdca5a3af032b8b4d4eff016152a
3
+ metadata.gz: 2f3baf82fbf9b744b9f8a880ab523e178f5073ee1ee728868dc73dabd9a57b6c
4
+ data.tar.gz: '09c452ed68be23c87398cd3f66675284f073fb2ea986668f108a6ca91769c299'
5
5
  SHA512:
6
- metadata.gz: dec556e6d7428f0950761653555ce6f8b6a92adf461ea333693d3b2132bff7d6d71bd38fa553307cd9c6bb762f4e1041c27ed2a3619636979675457b711a440b
7
- data.tar.gz: e00f149423a9288b835628c8204ef777551a45365b3176e1648235f24c50d071c37622cd26a56993cf619fa8ea8d303201e76c25e6295c11e19e1a1310742a24
6
+ metadata.gz: 9aaf19432b00274f29165467a415c982c36ce66ef9c71ae42e7b864ed344104f8afb00afa8aa3f81b8c456e8c0f7a2668a0ca919a8ad758a03712c231db32505
7
+ data.tar.gz: 5e0ae9cf031fa5936f7180be731475831831a40983a98b36187de72f245a4beb9076da2849268bb160877989fd7b15c8b4152cfc49d3af2877ab11a7a58f2b10
data/CHANGELOG.md CHANGED
@@ -7,6 +7,51 @@ 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
+
34
+ ---
35
+ ## [1.2.1] - 2026-05-13
36
+ ### Breaking Change
37
+ - Minimum Ruby version raised from 2.7.0 to 3.0.0. Ruby 2.7 has been EOL since March 2023 and is no longer supported by upstream `rake-compiler-dock` (1.11.0+) which `rb_sys` uses for cross-compiling native gems. Production environments on Ruby 3.0+ are unaffected.
38
+
39
+ ### New Functionality
40
+ - Added `o200k_harmony` tokenizer with support for `gpt-oss-20b` and `gpt-oss-120b`.
41
+ - Added support for additional model aliases now recognized by `tiktoken-rs` 0.11: `gpt-5-mini`, `gpt-5-nano`, `gpt-5.x` decimal variants (e.g. `gpt-5.4`, `gpt-5.4-pro`, `gpt-5.2-codex`), `gpt-4.5-*`, `o1`, `o3`, `o4-mini`, `codex-mini`, `codex-mini-latest`, and `ft:gpt-5` fine-tunes.
42
+ - Fine-tuned model resolution (`ft:` prefix) is now handled natively by the upstream `get_tokenizer` mapping, so any future ft: bases are picked up automatically.
43
+
44
+ ### Change
45
+ - Bumped `tiktoken-rs` from 0.7 to 0.11.
46
+ - Bumped `magnus` from 0.6 to 0.8 (with the `old-api` feature enabled to preserve current bindings). Still supports Ruby >= 3.0.
47
+ - Refactored Rust model dispatch to delegate to `tiktoken_rs::tokenizer::get_tokenizer` instead of maintaining a parallel alias list. The gem now stays in sync with upstream OpenAI tiktoken automatically on each `tiktoken-rs` bump.
48
+ - CI matrix trimmed: dropped deprecated `macos-13`; consolidated to `ubuntu-latest`, `ubuntu-24.04-arm`, `macos-latest`, `macos-15-intel`. Added Ruby 4.0 to both test and cross-gem builds.
49
+
50
+ ---
51
+ ## [1.2.0] - 2026-05-13
52
+ ### Note
53
+ - Partial release. The `arm-linux` cross-compile leg failed because upstream `rake-compiler-dock` 1.11.0+ dropped Ruby 2.7, so the published artifact set is incomplete. Please use 1.2.1 instead, which drops Ruby 2.7 from the support matrix and ships a complete set of platform gems.
54
+
10
55
  ---
11
56
  ## [1.1.0] - 2025-08-26
12
57
  ### New Functionality
data/Cargo.lock CHANGED
@@ -13,9 +13,9 @@ dependencies = [
13
13
 
14
14
  [[package]]
15
15
  name = "anyhow"
16
- version = "1.0.98"
16
+ version = "1.0.102"
17
17
  source = "registry+https://github.com/rust-lang/crates.io-index"
18
- checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
18
+ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
19
19
 
20
20
  [[package]]
21
21
  name = "base64"
@@ -25,38 +25,36 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
25
25
 
26
26
  [[package]]
27
27
  name = "bindgen"
28
- version = "0.69.5"
28
+ version = "0.72.1"
29
29
  source = "registry+https://github.com/rust-lang/crates.io-index"
30
- checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
30
+ checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
31
31
  dependencies = [
32
32
  "bitflags",
33
33
  "cexpr",
34
34
  "clang-sys",
35
35
  "itertools",
36
- "lazy_static",
37
- "lazycell",
38
36
  "proc-macro2",
39
37
  "quote",
40
38
  "regex",
41
39
  "rustc-hash",
42
40
  "shlex",
43
- "syn",
41
+ "syn 2.0.104",
44
42
  ]
45
43
 
46
44
  [[package]]
47
45
  name = "bit-set"
48
- version = "0.5.3"
46
+ version = "0.8.0"
49
47
  source = "registry+https://github.com/rust-lang/crates.io-index"
50
- checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
48
+ checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
51
49
  dependencies = [
52
50
  "bit-vec",
53
51
  ]
54
52
 
55
53
  [[package]]
56
54
  name = "bit-vec"
57
- version = "0.6.3"
55
+ version = "0.8.0"
58
56
  source = "registry+https://github.com/rust-lang/crates.io-index"
59
- checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
57
+ checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
60
58
 
61
59
  [[package]]
62
60
  name = "bitflags"
@@ -66,13 +64,13 @@ checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
66
64
 
67
65
  [[package]]
68
66
  name = "bstr"
69
- version = "1.12.0"
67
+ version = "1.14.0"
70
68
  source = "registry+https://github.com/rust-lang/crates.io-index"
71
- checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4"
69
+ checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
72
70
  dependencies = [
73
71
  "memchr",
74
72
  "regex-automata",
75
- "serde",
73
+ "serde_core",
76
74
  ]
77
75
 
78
76
  [[package]]
@@ -109,9 +107,9 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
109
107
 
110
108
  [[package]]
111
109
  name = "fancy-regex"
112
- version = "0.13.0"
110
+ version = "0.19.2"
113
111
  source = "registry+https://github.com/rust-lang/crates.io-index"
114
- checksum = "531e46835a22af56d1e3b66f04844bed63158bc094a628bec1d321d9b4c44bf2"
112
+ checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
115
113
  dependencies = [
116
114
  "bit-set",
117
115
  "regex-automata",
@@ -147,12 +145,6 @@ version = "1.5.0"
147
145
  source = "registry+https://github.com/rust-lang/crates.io-index"
148
146
  checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
149
147
 
150
- [[package]]
151
- name = "lazycell"
152
- version = "1.3.0"
153
- source = "registry+https://github.com/rust-lang/crates.io-index"
154
- checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
155
-
156
148
  [[package]]
157
149
  name = "libc"
158
150
  version = "0.2.174"
@@ -171,9 +163,9 @@ dependencies = [
171
163
 
172
164
  [[package]]
173
165
  name = "magnus"
174
- version = "0.6.4"
166
+ version = "0.8.5"
175
167
  source = "registry+https://github.com/rust-lang/crates.io-index"
176
- checksum = "b1597ef40aa8c36be098249e82c9a20cf7199278ac1c1a1a995eeead6a184479"
168
+ checksum = "8137349730ade4d395b6cfb3fca073f09d6fdc35b276af17f5b974c44ccc3a21"
177
169
  dependencies = [
178
170
  "magnus-macros",
179
171
  "rb-sys",
@@ -183,13 +175,13 @@ dependencies = [
183
175
 
184
176
  [[package]]
185
177
  name = "magnus-macros"
186
- version = "0.6.0"
178
+ version = "0.8.0"
187
179
  source = "registry+https://github.com/rust-lang/crates.io-index"
188
- checksum = "5968c820e2960565f647819f5928a42d6e874551cab9d88d75e3e0660d7f71e3"
180
+ checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
189
181
  dependencies = [
190
182
  "proc-macro2",
191
183
  "quote",
192
- "syn",
184
+ "syn 2.0.104",
193
185
  ]
194
186
 
195
187
  [[package]]
@@ -234,18 +226,18 @@ dependencies = [
234
226
 
235
227
  [[package]]
236
228
  name = "rb-sys"
237
- version = "0.9.116"
229
+ version = "0.9.130"
238
230
  source = "registry+https://github.com/rust-lang/crates.io-index"
239
- checksum = "7059846f68396df83155779c75336ca24567741cb95256e6308c9fcc370e8dad"
231
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
240
232
  dependencies = [
241
233
  "rb-sys-build",
242
234
  ]
243
235
 
244
236
  [[package]]
245
237
  name = "rb-sys-build"
246
- version = "0.9.116"
238
+ version = "0.9.130"
247
239
  source = "registry+https://github.com/rust-lang/crates.io-index"
248
- checksum = "ac217510df41b9ffc041573e68d7a02aaff770c49943c7494441c4b224b0ecd0"
240
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
249
241
  dependencies = [
250
242
  "bindgen",
251
243
  "lazy_static",
@@ -253,20 +245,20 @@ dependencies = [
253
245
  "quote",
254
246
  "regex",
255
247
  "shell-words",
256
- "syn",
248
+ "syn 2.0.104",
257
249
  ]
258
250
 
259
251
  [[package]]
260
252
  name = "rb-sys-env"
261
- version = "0.1.2"
253
+ version = "0.2.3"
262
254
  source = "registry+https://github.com/rust-lang/crates.io-index"
263
- checksum = "a35802679f07360454b418a5d1735c89716bde01d35b1560fc953c1415a0b3bb"
255
+ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
264
256
 
265
257
  [[package]]
266
258
  name = "regex"
267
- version = "1.11.1"
259
+ version = "1.13.2"
268
260
  source = "registry+https://github.com/rust-lang/crates.io-index"
269
- checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
261
+ checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
270
262
  dependencies = [
271
263
  "aho-corasick",
272
264
  "memchr",
@@ -276,9 +268,9 @@ dependencies = [
276
268
 
277
269
  [[package]]
278
270
  name = "regex-automata"
279
- version = "0.4.9"
271
+ version = "0.4.19"
280
272
  source = "registry+https://github.com/rust-lang/crates.io-index"
281
- checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
273
+ checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
282
274
  dependencies = [
283
275
  "aho-corasick",
284
276
  "memchr",
@@ -287,15 +279,15 @@ dependencies = [
287
279
 
288
280
  [[package]]
289
281
  name = "regex-syntax"
290
- version = "0.8.5"
282
+ version = "0.8.12"
291
283
  source = "registry+https://github.com/rust-lang/crates.io-index"
292
- checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
284
+ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
293
285
 
294
286
  [[package]]
295
287
  name = "rustc-hash"
296
- version = "1.1.0"
288
+ version = "2.1.2"
297
289
  source = "registry+https://github.com/rust-lang/crates.io-index"
298
- checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
290
+ checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
299
291
 
300
292
  [[package]]
301
293
  name = "seq-macro"
@@ -304,23 +296,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
304
296
  checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
305
297
 
306
298
  [[package]]
307
- name = "serde"
308
- version = "1.0.219"
299
+ name = "serde_core"
300
+ version = "1.0.229"
309
301
  source = "registry+https://github.com/rust-lang/crates.io-index"
310
- checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
302
+ checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
311
303
  dependencies = [
312
304
  "serde_derive",
313
305
  ]
314
306
 
315
307
  [[package]]
316
308
  name = "serde_derive"
317
- version = "1.0.219"
309
+ version = "1.0.229"
318
310
  source = "registry+https://github.com/rust-lang/crates.io-index"
319
- checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
311
+ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
320
312
  dependencies = [
321
313
  "proc-macro2",
322
314
  "quote",
323
- "syn",
315
+ "syn 3.0.10",
324
316
  ]
325
317
 
326
318
  [[package]]
@@ -346,17 +338,27 @@ dependencies = [
346
338
  "unicode-ident",
347
339
  ]
348
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
+
349
352
  [[package]]
350
353
  name = "tiktoken-rs"
351
- version = "0.7.0"
354
+ version = "0.12.1"
352
355
  source = "registry+https://github.com/rust-lang/crates.io-index"
353
- checksum = "25563eeba904d770acf527e8b370fe9a5547bacd20ff84a0b6c3bc41288e5625"
356
+ checksum = "2aeff724640cfe13037336ddf35befdffd2909cbdb65cf041cc8a4cf8c584cfa"
354
357
  dependencies = [
355
358
  "anyhow",
356
359
  "base64",
357
360
  "bstr",
358
361
  "fancy-regex",
359
- "lazy_static",
360
362
  "regex",
361
363
  "rustc-hash",
362
364
  ]
data/README.md CHANGED
@@ -1,12 +1,19 @@
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
- Supports Ruby >= 2.7.0
16
+ Supports Ruby >= 3.0.0
10
17
 
11
18
  Extensive Model Support: Includes tokenizers for all modern and legacy OpenAI models, recognizing dozens of model aliases automatically.
12
19
 
@@ -15,16 +22,16 @@ 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.1'`
25
+ `gem 'j_r_r_token', '~> 1.3'`
19
26
 
20
27
  #### Command Line
21
- `gem install j_r_r_token -v '~> 1.1'`
28
+ `gem install j_r_r_token -v '~> 1.3'`
22
29
 
23
30
  ## Use
24
31
 
25
32
  ### Count tokens for a specific model (the model keyword is required)
26
33
  ```Ruby
27
- count = JRRToken::Tokenizer.count("hello world!", model: "gpt-5")
34
+ count = JRRToken::Tokenizer.count("hello world!", model: "gpt-5.4")
28
35
  ```
29
36
 
30
37
  ### The gem recognizes many aliases, including older models
@@ -37,25 +44,43 @@ 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
- 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.
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.
44
54
 
45
- - o200k_base Models (e.g., gpt-5, gpt-4.1, gpt-4o)
46
- - cl100k_base Models (e.g., gpt-4, gpt-3.5)
55
+ - o200k_harmony Models (e.g., gpt-oss-20b, gpt-oss-120b)
56
+ - o200k_base Models (e.g., gpt-5.4, gpt-5-mini, gpt-4.5, gpt-4.1, gpt-4o, o1, o3, o4-mini, codex-mini)
57
+ - cl100k_base Models (e.g., gpt-4, gpt-3.5-turbo, text-embedding-3-small)
47
58
  - p50k_base Models (e.g., text-davinci-003)
48
59
  - r50k_base Models (e.g., gpt-2)
49
60
  - p50k_edit Models
50
61
 
62
+ Fine-tuned models (`ft:<base>:org:name:id`) are automatically resolved to the same tokenizer as their base model.
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
+
51
76
  ## Developing JRRToken Locally
52
77
 
53
78
  ### Install Ruby and Rust dependencies
54
- Ruby >= 2.7.0
79
+ Ruby >= 3.0.0
55
80
 
56
81
  RubyGems >= 3.0.0
57
82
 
58
- Rust edition 2021
83
+ Rust >= 1.85
59
84
 
60
85
  ### Compile the Rust extension and run tests
61
86
  Compile:
@@ -9,5 +9,5 @@ publish = false
9
9
  crate-type = ["cdylib"]
10
10
 
11
11
  [dependencies]
12
- magnus = { version = "0.6" }
13
- tiktoken-rs = { version= "0.7" }
12
+ magnus = "0.8.5"
13
+ tiktoken-rs = "0.12.1"
@@ -1,65 +1,73 @@
1
- use magnus::{define_module, exception, function, Error};
2
- use tiktoken_rs::{cl100k_base, o200k_base, p50k_base, p50k_edit, r50k_base, CoreBPE};
1
+ use std::{collections::HashSet, sync::OnceLock};
3
2
 
4
- // Helper function to get the correct tokenizer based on the model name.
5
- // This logic is adapted from the tiktoken-rs library.
6
- fn get_bpe_from_model(model: &str) -> Result<CoreBPE, Error> {
7
- let tokenizer = match model {
8
- // --- O200k Base Models ---
9
- "o200k_base" | "gpt-5" | "gpt-4.1" | "chatgpt-4o-latest" | "gpt-4o" => o200k_base(),
10
- // --- Cl100k Base Models ---
11
- "cl100k_base" | "gpt-4" | "ft:gpt-4" | "gpt-3.5-turbo" | "gpt-3.5" | "gpt-35-turbo"
12
- | "davinci-002" | "babbage-002" | "text-embedding-ada-002"
13
- | "text-embedding-3-small" | "text-embedding-3-large" => cl100k_base(),
14
- // --- P50k Base Models ---
15
- "p50k_base" | "text-davinci-003" | "text-davinci-002" | "code-davinci-002"
16
- | "code-davinci-001" | "code-cushman-002" | "code-cushman-001"
17
- | "davinci-codex" | "cushman-codex" => p50k_base(),
18
- // --- R50k Base (GPT-2) Models ---
19
- "r50k_base" | "gpt2" | "gpt-2" | "text-davinci-001" | "text-curie-001"
20
- | "text-babbage-001" | "text-ada-001" | "davinci" | "curie" | "babbage" | "ada"
21
- | "text-similarity-davinci-001" | "text-similarity-curie-001"
22
- | "text-similarity-babbage-001" | "text-similarity-ada-001"
23
- | "text-search-davinci-doc-001" | "text-search-curie-doc-001"
24
- | "text-search-babbage-doc-001" | "text-search-ada-doc-001"
25
- | "code-search-babbage-code-001" | "code-search-ada-code-001" => r50k_base(),
26
- // --- P50k Edit Models ---
27
- "p50k_edit" | "text-davinci-edit-001" | "code-davinci-edit-001" => p50k_edit(),
28
- // --- Fallback for Prefixes ---
29
- _ => {
30
- let o200k_prefixes = [
31
- "o1-", "o3-", "o4-", "gpt-5-", "gpt-4.1-", "chatgpt-4o-", "gpt-4o-", "ft:gpt-4o",
32
- ];
33
-
34
- let cl100k_prefixes = [
35
- "gpt-4-", "gpt-3.5-turbo-", "gpt-35-turbo-", "ft:gpt-4:",
36
- "ft:gpt-4-", "ft:gpt-3.5-turbo", "ft:davinci-002", "ft:babbage-002",
37
- ];
3
+ use magnus::{function, Error, Ruby};
4
+ use tiktoken_rs::{
5
+ bpe_for_tokenizer,
6
+ tokenizer::{get_tokenizer, Tokenizer},
7
+ CoreBPE,
8
+ };
38
9
 
10
+ // Resolves a model name (or bare encoding name) to a tokenizer.
11
+ // Model -> tokenizer dispatch is delegated to `tiktoken_rs::tokenizer::get_tokenizer`,
12
+ // which is kept in sync with upstream OpenAI tiktoken. It handles `ft:` prefix
13
+ // stripping, GPT-5/4.5/4.1/4o families, o1/o3/o4-mini reasoning models, gpt-oss
14
+ // (harmony), codex-mini, and all legacy aliases.
15
+ fn tokenizer_for(model: &str) -> Option<Tokenizer> {
16
+ match model {
17
+ // Bare encoding names — callers may pass these directly.
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
+ }
39
27
 
40
- if o200k_prefixes.iter().any(|prefix| model.starts_with(prefix)) {
41
- o200k_base()
42
- } else if cl100k_prefixes.iter().any(|prefix| model.starts_with(prefix)) {
43
- cl100k_base()
44
- } else {
45
- let err_msg = format!("Model '{}' not supported.", model);
46
- return Err(Error::new(exception::arg_error(), err_msg));
47
- }
48
- }
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,
49
42
  };
50
- tokenizer.map_err(|e| Error::new(exception::runtime_error(), e.to_string()))
43
+ SETS[index].get_or_init(|| bpe.special_tokens())
51
44
  }
52
45
 
53
46
  // This function is exposed to Ruby.
54
- fn count_tokens(model: String, text: String) -> Result<usize, Error> {
55
- let bpe = get_bpe_from_model(&model)?;
56
- let tokens = bpe.encode_with_special_tokens(&text);
57
- 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()))
58
66
  }
59
67
 
60
68
  #[magnus::init]
61
- fn init() -> Result<(), Error> {
62
- let module = define_module("JRRToken")?;
69
+ fn init(ruby: &Ruby) -> Result<(), Error> {
70
+ let module = ruby.define_module("JRRToken")?;
63
71
  module.define_module_function("count_tokens", function!(count_tokens, 2))?;
64
72
  Ok(())
65
73
  }
data/j_r_r_token.gemspec CHANGED
@@ -9,10 +9,10 @@ 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
- spec.required_ruby_version = ">= 2.7.0"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
16
  spec.required_rubygems_version = ">= 3.0.0"
17
17
 
18
18
  spec.metadata["allowed_push_host"] = "https://rubygems.org"
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JRRToken
4
- VERSION = "1.1.0"
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.1.0
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: 2025-08-27 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: []
@@ -90,7 +90,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
90
90
  requirements:
91
91
  - - ">="
92
92
  - !ruby/object:Gem::Version
93
- version: 2.7.0
93
+ version: 3.0.0
94
94
  required_rubygems_version: !ruby/object:Gem::Requirement
95
95
  requirements:
96
96
  - - ">="