j_r_r_token 1.2.1 → 2.0.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 +4 -4
- data/CHANGELOG.md +51 -0
- data/Cargo.lock +42 -37
- data/README.md +96 -14
- data/ext/j_r_r_token/Cargo.toml +3 -2
- data/ext/j_r_r_token/src/lib.rs +273 -35
- data/j_r_r_token.gemspec +1 -1
- data/lib/j_r_r_token/version.rb +1 -1
- data/lib/j_r_r_token.rb +429 -13
- data/sig/j_r_r_token.rbs +49 -1
- metadata +4 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: bb8548223cf749fc4d55f9c4eb93d9f5e7b2acc069ec3960d196305c47c8ad52
|
|
4
|
+
data.tar.gz: c17e8fa425b615639f909efa2949831030749432f253a8c20ab25f46f700deac
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 9f5d841173c095abf7401283f9819b9776f25310a1548396f8c89c7ebfff9738f2583f303a8ee182a4601a23b2551ba081dc88e3873138c5adeb960981f6da93
|
|
7
|
+
data.tar.gz: 0d0333595971757702fe3dc899c87cfa6bc7f8e7621f314c1830bd318265f6ea53dd21b791b78a310653584ba0ad7fdd893266b742469dc0458ea011f63dd7eb
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
---
|
|
11
|
+
## [2.0.0] - 2026-11-22
|
|
12
|
+
### Breaking Change
|
|
13
|
+
- Removed the undocumented `JRRToken.count_tokens(model, text)` native entry point. Use `JRRToken::Tokenizer.count(text, model:)` or `JRRToken::Tokenizer.for_model(model).count(text)`.
|
|
14
|
+
- `JRRToken::Tokenizer` is now a native class whose instances are built only by `for_model`; `Tokenizer.new` and `Tokenizer.allocate` are private.
|
|
15
|
+
- Text that isn't valid in its encoding now raises `ArgumentError` ("invalid byte sequence in UTF-8") instead of `EncodingError`.
|
|
16
|
+
- Special-token strings in input text (e.g. `"<|endoftext|>"`) are now treated as **ordinary text by default** (`special_tokens: :text`), so untrusted input can't be counted as control tokens. In 1.x, `count` encoded them as single special tokens (`"<|endoftext|>"` on gpt-4o: 1 token in 1.x, 7 now). Pass `special_tokens: :allow` for the old behavior, or `:raise` to reject such input (Python tiktoken's default).
|
|
17
|
+
|
|
18
|
+
### New Functionality
|
|
19
|
+
- `JRRToken::Tokenizer.for_model(model)` returns a tokenizer instance for a model name or bare encoding name. Models that share an encoding return the same frozen instance (one per encoding), so instances are cheap to fetch and safe to share across threads.
|
|
20
|
+
- Instance methods: `#encoding` (e.g. `"o200k_base"`), `#count(text)`, `#encode(text)` (token ids) and `#decode(tokens)`. `decode` replaces bytes that don't form valid UTF-8 (a token slice cutting a multi-byte character) with U+FFFD, matching Python tiktoken's default, and raises `ArgumentError` for token ids not in the encoding.
|
|
21
|
+
- `special_tokens:` option on `count`, `encode`, `truncate` and `split` (and their class-level shortcuts): `:text` (default, plain text), `:allow` (encode as special tokens) or `:raise` (raise `JRRToken::SpecialTokenError`, a subclass of `ArgumentError`, naming the token found). All three modes use the error-reporting encode path, so the pathological-input case still raises `RuntimeError` rather than crashing.
|
|
22
|
+
- `#truncate(text, max_tokens:)` cuts `text` at a token boundary: the text of its first `max_tokens` tokens (fewer if needed to stay within budget), dropping a trailing character the cut would split. The result is always a prefix of the input, valid UTF-8, and `count(result)` (with the same `special_tokens:`) is guaranteed to be at most `max_tokens`. Like tiktoken's `decode(encode(text)[:n])` idiom, it is not necessarily the longest prefix that fits. Class shortcut: `Tokenizer.truncate(text, max_tokens:, model:)`.
|
|
23
|
+
- `#split(text)` returns the text of each token (e.g. `"hello world"` -> `["hello", " world"]`), honoring `special_tokens:`. A token's incomplete multi-byte character bytes are shown as U+FFFD, so joining the pieces doesn't always reproduce the text. Class shortcut: `Tokenizer.split(text, model:)`.
|
|
24
|
+
- `JRRToken.context_size(model)` returns the model's context window in tokens (e.g. `128_000` for `"gpt-4o"`), or `nil` if the model isn't in tiktoken-rs's table. Fine-tuned names resolve to their base model. Values come from tiktoken-rs's prefix-matched table as-is, so they can be stale or loose (e.g. bare `gpt-4-turbo` reports 8,192, `davinci-002` 2,049), and a name can have a context size without having a tokenizer (e.g. `gpt-6`, `o4`).
|
|
25
|
+
- `JRRToken.count_messages(messages, model:, special_tokens: :text)` estimates the prompt tokens for a list of chat messages, including per-message framing and reply priming, using OpenAI's cookbook formula. Constants and message handling mirror tiktoken-rs's `num_tokens_from_messages` and its async-openai adapter, verified to give identical results on OpenAI-shaped messages. Messages are Hashes with String or Symbol keys: `role`; `content` as a String, nil, or an Array of parts (text parts are joined, refusal parts count as the refusal, image/audio/file parts are skipped); and optional `name`, `refusal`, `function_call` and `tool_calls` (OpenAI's `{function: {...}}` and `{type: "custom", custom: {name:, input:}}` shapes, or flat `{name:, arguments:}`). A tool message's `tool_call_id` counts as its name, as tiktoken-rs does. It's an estimate: tool definitions and non-text content aren't counted. Only chat-model encodings (o200k_base, o200k_harmony, cl100k_base) are supported. It's built on the gem's own counting rather than calling upstream, so it honors `special_tokens:` and raises `RuntimeError` instead of crashing on pathological input.
|
|
26
|
+
- `#decode_bytes(tokens)` returns the exact bytes as a binary (ASCII-8BIT) String, with nothing replaced, for callers that need byte-exact output or join several token slices before converting to UTF-8.
|
|
27
|
+
- Token ids passed to `decode` / `decode_bytes` must be Integers; other numerics (e.g. `1.5`) raise `TypeError`.
|
|
28
|
+
- Class-level shortcuts for the new methods: `Tokenizer.encode(text, model:)`, `Tokenizer.decode(tokens, model:)` and `Tokenizer.decode_bytes(tokens, model:)`, alongside the existing `Tokenizer.count(text, model:)`.
|
|
29
|
+
- Binary (ASCII-8BIT) text, such as `File.binread` output or HTTP bodies, and US-ASCII text holding non-ASCII bytes (`File.read` with no locale set, e.g. in a Docker image without `LANG`) are now accepted when their bytes are valid UTF-8 (they previously raised `EncodingError`). The caller's string is not modified. Other encodings are transcoded as before, and returned strings are UTF-8.
|
|
30
|
+
- Tokenizers support Marshal: they dump as their encoding name and load back as the shared instance, so they can live inside cached or marshaled objects.
|
|
31
|
+
- RBS signatures cover the full public API.
|
|
32
|
+
|
|
33
|
+
### Change
|
|
34
|
+
- If the native extension can't be loaded, `require "j_r_r_token"` now raises `LoadError` (with the underlying reason) instead of printing a warning and failing later with a confusing error.
|
|
35
|
+
- README rewritten for the 2.0 API, with an "Upgrading to 2.0" section.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
## [1.3.0] - 2026-11-22
|
|
39
|
+
### Breaking Change
|
|
40
|
+
- 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.
|
|
41
|
+
|
|
42
|
+
### Fix
|
|
43
|
+
- 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.
|
|
44
|
+
|
|
45
|
+
### Change
|
|
46
|
+
- Bumped `tiktoken-rs` from 0.11.0 to 0.12.1, which vendors OpenAI's tiktoken 0.14.0 core.
|
|
47
|
+
- 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.*`).
|
|
48
|
+
- 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).
|
|
49
|
+
- 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.
|
|
50
|
+
- Building from source (the generic gem or `rake compile`) now requires Rust 1.85 or newer. Precompiled platform gems are unaffected.
|
|
51
|
+
- 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.
|
|
52
|
+
- 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.
|
|
53
|
+
- 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.
|
|
54
|
+
- 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.
|
|
55
|
+
- 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.
|
|
56
|
+
- 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.
|
|
57
|
+
- Gemspec description now lists `o200k_harmony`; added RBS signatures for `JRRToken::Tokenizer.count`.
|
|
58
|
+
- 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.
|
|
59
|
+
- 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.
|
|
60
|
+
|
|
10
61
|
---
|
|
11
62
|
## [1.2.1] - 2026-05-13
|
|
12
63
|
### Breaking Change
|
data/Cargo.lock
CHANGED
|
@@ -36,9 +36,9 @@ dependencies = [
|
|
|
36
36
|
"proc-macro2",
|
|
37
37
|
"quote",
|
|
38
38
|
"regex",
|
|
39
|
-
"rustc-hash
|
|
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.
|
|
67
|
+
version = "1.14.0"
|
|
68
68
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
69
|
-
checksum = "
|
|
69
|
+
checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
|
|
70
70
|
dependencies = [
|
|
71
71
|
"memchr",
|
|
72
72
|
"regex-automata",
|
|
73
|
-
"
|
|
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.
|
|
110
|
+
version = "0.19.2"
|
|
111
111
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
112
|
-
checksum = "
|
|
112
|
+
checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
|
|
113
113
|
dependencies = [
|
|
114
114
|
"bit-set",
|
|
115
115
|
"regex-automata",
|
|
@@ -136,6 +136,7 @@ name = "j_r_r_token"
|
|
|
136
136
|
version = "0.1.0"
|
|
137
137
|
dependencies = [
|
|
138
138
|
"magnus",
|
|
139
|
+
"regex",
|
|
139
140
|
"tiktoken-rs",
|
|
140
141
|
]
|
|
141
142
|
|
|
@@ -163,9 +164,9 @@ dependencies = [
|
|
|
163
164
|
|
|
164
165
|
[[package]]
|
|
165
166
|
name = "magnus"
|
|
166
|
-
version = "0.8.
|
|
167
|
+
version = "0.8.5"
|
|
167
168
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
168
|
-
checksum = "
|
|
169
|
+
checksum = "8137349730ade4d395b6cfb3fca073f09d6fdc35b276af17f5b974c44ccc3a21"
|
|
169
170
|
dependencies = [
|
|
170
171
|
"magnus-macros",
|
|
171
172
|
"rb-sys",
|
|
@@ -181,7 +182,7 @@ checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
|
|
|
181
182
|
dependencies = [
|
|
182
183
|
"proc-macro2",
|
|
183
184
|
"quote",
|
|
184
|
-
"syn",
|
|
185
|
+
"syn 2.0.104",
|
|
185
186
|
]
|
|
186
187
|
|
|
187
188
|
[[package]]
|
|
@@ -226,18 +227,18 @@ dependencies = [
|
|
|
226
227
|
|
|
227
228
|
[[package]]
|
|
228
229
|
name = "rb-sys"
|
|
229
|
-
version = "0.9.
|
|
230
|
+
version = "0.9.130"
|
|
230
231
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
231
|
-
checksum = "
|
|
232
|
+
checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
|
|
232
233
|
dependencies = [
|
|
233
234
|
"rb-sys-build",
|
|
234
235
|
]
|
|
235
236
|
|
|
236
237
|
[[package]]
|
|
237
238
|
name = "rb-sys-build"
|
|
238
|
-
version = "0.9.
|
|
239
|
+
version = "0.9.130"
|
|
239
240
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
240
|
-
checksum = "
|
|
241
|
+
checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
|
|
241
242
|
dependencies = [
|
|
242
243
|
"bindgen",
|
|
243
244
|
"lazy_static",
|
|
@@ -245,7 +246,7 @@ dependencies = [
|
|
|
245
246
|
"quote",
|
|
246
247
|
"regex",
|
|
247
248
|
"shell-words",
|
|
248
|
-
"syn",
|
|
249
|
+
"syn 2.0.104",
|
|
249
250
|
]
|
|
250
251
|
|
|
251
252
|
[[package]]
|
|
@@ -256,9 +257,9 @@ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
|
|
|
256
257
|
|
|
257
258
|
[[package]]
|
|
258
259
|
name = "regex"
|
|
259
|
-
version = "1.
|
|
260
|
+
version = "1.13.2"
|
|
260
261
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
261
|
-
checksum = "
|
|
262
|
+
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
|
|
262
263
|
dependencies = [
|
|
263
264
|
"aho-corasick",
|
|
264
265
|
"memchr",
|
|
@@ -268,9 +269,9 @@ dependencies = [
|
|
|
268
269
|
|
|
269
270
|
[[package]]
|
|
270
271
|
name = "regex-automata"
|
|
271
|
-
version = "0.4.
|
|
272
|
+
version = "0.4.19"
|
|
272
273
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
273
|
-
checksum = "
|
|
274
|
+
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
|
274
275
|
dependencies = [
|
|
275
276
|
"aho-corasick",
|
|
276
277
|
"memchr",
|
|
@@ -279,15 +280,9 @@ dependencies = [
|
|
|
279
280
|
|
|
280
281
|
[[package]]
|
|
281
282
|
name = "regex-syntax"
|
|
282
|
-
version = "0.8.
|
|
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"
|
|
283
|
+
version = "0.8.12"
|
|
289
284
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
290
|
-
checksum = "
|
|
285
|
+
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
|
291
286
|
|
|
292
287
|
[[package]]
|
|
293
288
|
name = "rustc-hash"
|
|
@@ -302,23 +297,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
|
302
297
|
checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
|
|
303
298
|
|
|
304
299
|
[[package]]
|
|
305
|
-
name = "
|
|
306
|
-
version = "1.0.
|
|
300
|
+
name = "serde_core"
|
|
301
|
+
version = "1.0.229"
|
|
307
302
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
308
|
-
checksum = "
|
|
303
|
+
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
|
309
304
|
dependencies = [
|
|
310
305
|
"serde_derive",
|
|
311
306
|
]
|
|
312
307
|
|
|
313
308
|
[[package]]
|
|
314
309
|
name = "serde_derive"
|
|
315
|
-
version = "1.0.
|
|
310
|
+
version = "1.0.229"
|
|
316
311
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
317
|
-
checksum = "
|
|
312
|
+
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
|
318
313
|
dependencies = [
|
|
319
314
|
"proc-macro2",
|
|
320
315
|
"quote",
|
|
321
|
-
"syn",
|
|
316
|
+
"syn 3.0.10",
|
|
322
317
|
]
|
|
323
318
|
|
|
324
319
|
[[package]]
|
|
@@ -344,19 +339,29 @@ dependencies = [
|
|
|
344
339
|
"unicode-ident",
|
|
345
340
|
]
|
|
346
341
|
|
|
342
|
+
[[package]]
|
|
343
|
+
name = "syn"
|
|
344
|
+
version = "3.0.10"
|
|
345
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
346
|
+
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
|
347
|
+
dependencies = [
|
|
348
|
+
"proc-macro2",
|
|
349
|
+
"quote",
|
|
350
|
+
"unicode-ident",
|
|
351
|
+
]
|
|
352
|
+
|
|
347
353
|
[[package]]
|
|
348
354
|
name = "tiktoken-rs"
|
|
349
|
-
version = "0.
|
|
355
|
+
version = "0.12.1"
|
|
350
356
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
351
|
-
checksum = "
|
|
357
|
+
checksum = "2aeff724640cfe13037336ddf35befdffd2909cbdb65cf041cc8a4cf8c584cfa"
|
|
352
358
|
dependencies = [
|
|
353
359
|
"anyhow",
|
|
354
360
|
"base64",
|
|
355
361
|
"bstr",
|
|
356
362
|
"fancy-regex",
|
|
357
|
-
"lazy_static",
|
|
358
363
|
"regex",
|
|
359
|
-
"rustc-hash
|
|
364
|
+
"rustc-hash",
|
|
360
365
|
]
|
|
361
366
|
|
|
362
367
|
[[package]]
|
data/README.md
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
5
|
+
<h1 align="center">JRRToken</h1>
|
|
6
|
+
<h2 align="center">v2.0.0</h2>
|
|
4
7
|
|
|
5
|
-
|
|
8
|
+
<p align="center">(Just Ruby, Rust, & Tokens)</p>
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
JRRToken provides a high-performance, native Ruby interface to OpenAI's tokenizers using the powerful [tiktoken-rs](https://github.com/zurawiki/tiktoken-rs) library. Count, encode, decode, split and truncate text, and estimate chat prompt sizes, for all modern and legacy OpenAI models, with the speed of Rust.
|
|
13
|
+
|
|
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,29 +22,83 @@ 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', '~>
|
|
25
|
+
`gem 'j_r_r_token', '~> 2.0'`
|
|
19
26
|
|
|
20
27
|
#### Command Line
|
|
21
|
-
`gem install j_r_r_token -v '~>
|
|
28
|
+
`gem install j_r_r_token -v '~> 2.0'`
|
|
29
|
+
|
|
30
|
+
Upgrading from 1.x? See [Upgrading to 2.0](#upgrading-to-20).
|
|
22
31
|
|
|
23
32
|
## Use
|
|
24
33
|
|
|
25
|
-
### Count tokens
|
|
34
|
+
### Count tokens (the model keyword is required)
|
|
35
|
+
```Ruby
|
|
36
|
+
JRRToken::Tokenizer.count("hello world!", model: "gpt-5.4") # => 3
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Get a tokenizer for a model
|
|
40
|
+
`for_model` accepts a model name (including fine-tunes like `ft:gpt-4o:org:name:id`) or a bare encoding name like `"o200k_base"`. Models that share an encoding return the same frozen instance, which is cheap to fetch and safe to share across threads.
|
|
41
|
+
|
|
42
|
+
```Ruby
|
|
43
|
+
tok = JRRToken::Tokenizer.for_model("gpt-4o") # => #<JRRToken::Tokenizer o200k_base>
|
|
44
|
+
tok.encoding # => "o200k_base"
|
|
45
|
+
tok.count("hello world!") # => 3
|
|
46
|
+
tok.encode("hello world!") # => [24912, 2375, 0]
|
|
47
|
+
tok.decode([24912, 2375, 0]) # => "hello world!"
|
|
48
|
+
tok.split("hello world!") # => ["hello", " world", "!"]
|
|
49
|
+
tok.truncate("The quick brown fox jumps over the lazy dog.", max_tokens: 5)
|
|
50
|
+
# => "The quick brown fox jumps"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Every instance method also has a class-level shortcut that takes `model:`, e.g. `JRRToken::Tokenizer.encode("hello", model: "gpt-4o")`.
|
|
54
|
+
|
|
55
|
+
- `decode` replaces bytes that don't form valid UTF-8 (a token slice that cuts a character in half) with U+FFFD, like Python tiktoken. `decode_bytes` returns the exact bytes as a binary String instead.
|
|
56
|
+
- `split` returns the text of each token, 1:1 with `encode`. Pieces of a character split across tokens (common for emoji and CJK) show as U+FFFD.
|
|
57
|
+
- `truncate` cuts at a token boundary: the result is always a prefix of the input, valid UTF-8, and at most `max_tokens` tokens. Like tiktoken's `decode(encode(text)[:n])`, it isn't necessarily the longest prefix that fits.
|
|
58
|
+
|
|
59
|
+
### Special tokens
|
|
60
|
+
Encodings reserve strings like `<|endoftext|>` as control tokens. `count`, `encode`, `truncate` and `split` take `special_tokens:` to decide what happens when they appear in your text:
|
|
61
|
+
|
|
62
|
+
| Mode | Behavior |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `:text` (default) | Treat them as ordinary text. Right for user-supplied input. |
|
|
65
|
+
| `:allow` | Encode them as single special tokens. |
|
|
66
|
+
| `:raise` | Raise `JRRToken::SpecialTokenError` (an `ArgumentError`), naming the token. Python tiktoken's default. |
|
|
67
|
+
|
|
26
68
|
```Ruby
|
|
27
|
-
|
|
69
|
+
tok.count("<|endoftext|>") # => 7
|
|
70
|
+
tok.count("<|endoftext|>", special_tokens: :allow) # => 1
|
|
28
71
|
```
|
|
29
72
|
|
|
30
|
-
###
|
|
73
|
+
### Count tokens in a chat conversation
|
|
74
|
+
`count_messages` estimates the prompt tokens for a list of chat messages, including the framing tokens each message adds, using OpenAI's cookbook formula (the same as tiktoken-rs's `num_tokens_from_messages`). Messages are OpenAI-shaped Hashes with String or Symbol keys.
|
|
75
|
+
|
|
31
76
|
```Ruby
|
|
32
|
-
|
|
77
|
+
messages = [
|
|
78
|
+
{ role: "system", content: "You are a helpful assistant." },
|
|
79
|
+
{ role: "user", content: "What is the capital of France?" }
|
|
80
|
+
]
|
|
81
|
+
JRRToken.count_messages(messages, model: "gpt-4o") # => 24
|
|
33
82
|
```
|
|
34
83
|
|
|
35
|
-
|
|
84
|
+
It's an estimate: tool definitions and image, audio and file content aren't counted. Only chat-model encodings (`o200k_base`, `o200k_harmony`, `cl100k_base`) are supported.
|
|
85
|
+
|
|
86
|
+
### Context window sizes
|
|
36
87
|
```Ruby
|
|
37
|
-
|
|
88
|
+
JRRToken.context_size("gpt-4o") # => 128000
|
|
89
|
+
JRRToken.context_size("unknown") # => nil
|
|
38
90
|
```
|
|
39
91
|
|
|
40
|
-
|
|
92
|
+
Values come from tiktoken-rs's model table as-is, so they can be stale for some models.
|
|
93
|
+
|
|
94
|
+
### Text input
|
|
95
|
+
Text is converted with `to_s`, so `JRRToken::Tokenizer.count(1234, model: "o200k_base")` works. Binary (ASCII-8BIT) strings, such as those from `File.binread` or HTTP bodies, and US-ASCII strings holding non-ASCII bytes (what `File.read` returns when no locale is set, e.g. in a Docker image without `LANG`), are read as UTF-8 when their bytes are valid UTF-8. Other encodings are transcoded. Returned strings are UTF-8.
|
|
96
|
+
|
|
97
|
+
### Errors
|
|
98
|
+
- An unsupported model name raises `ArgumentError`, and a model that isn't a String raises `TypeError`.
|
|
99
|
+
- Text that isn't valid in its encoding raises `ArgumentError`.
|
|
100
|
+
- `special_tokens: :raise` raises `JRRToken::SpecialTokenError` when the text contains a special token.
|
|
101
|
+
- 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
102
|
|
|
42
103
|
## Supported Models
|
|
43
104
|
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 +112,27 @@ The gem automatically maps dozens of model names and prefixes to the correct und
|
|
|
51
112
|
|
|
52
113
|
Fine-tuned models (`ft:<base>:org:name:id`) are automatically resolved to the same tokenizer as their base model.
|
|
53
114
|
|
|
115
|
+
## Upgrading to 2.0
|
|
116
|
+
- **Special tokens are plain text by default.** In 1.x, `count` encoded strings like `<|endoftext|>` as single special tokens. They now count as ordinary text (`<|endoftext|>` on gpt-4o: 1 token in 1.x, 7 in 2.0). Pass `special_tokens: :allow` to keep the 1.x behavior. Counts only change for text that contains special-token strings.
|
|
117
|
+
- **`JRRToken.count_tokens(model, text)` was removed.** Use `JRRToken::Tokenizer.count(text, model:)`.
|
|
118
|
+
- **`JRRToken::Tokenizer.new` is private.** Use `JRRToken::Tokenizer.for_model(model)`.
|
|
119
|
+
- **Invalid text raises `ArgumentError`** (1.x raised `EncodingError`), and binary or US-ASCII-labeled strings holding valid UTF-8 are now accepted.
|
|
120
|
+
- **A missing native extension raises `LoadError`** from `require "j_r_r_token"`. 1.x printed a warning and failed later.
|
|
121
|
+
|
|
122
|
+
`JRRToken::Tokenizer.count(text, model:)` otherwise works exactly as before.
|
|
123
|
+
|
|
124
|
+
## Performance and Memory
|
|
125
|
+
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.
|
|
126
|
+
|
|
127
|
+
To keep that one-time cost out of your first request, warm up the encodings you use at boot:
|
|
128
|
+
|
|
129
|
+
```Ruby
|
|
130
|
+
# e.g. config/initializers/j_r_r_token.rb
|
|
131
|
+
JRRToken::Tokenizer.for_model("gpt-4o").count("")
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
54
136
|
## Developing JRRToken Locally
|
|
55
137
|
|
|
56
138
|
### Install Ruby and Rust dependencies
|
|
@@ -58,7 +140,7 @@ Ruby >= 3.0.0
|
|
|
58
140
|
|
|
59
141
|
RubyGems >= 3.0.0
|
|
60
142
|
|
|
61
|
-
Rust
|
|
143
|
+
Rust >= 1.85
|
|
62
144
|
|
|
63
145
|
### Compile the Rust extension and run tests
|
|
64
146
|
Compile:
|
data/ext/j_r_r_token/Cargo.toml
CHANGED