j_r_r_token 1.3.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2f3baf82fbf9b744b9f8a880ab523e178f5073ee1ee728868dc73dabd9a57b6c
4
- data.tar.gz: '09c452ed68be23c87398cd3f66675284f073fb2ea986668f108a6ca91769c299'
3
+ metadata.gz: bb8548223cf749fc4d55f9c4eb93d9f5e7b2acc069ec3960d196305c47c8ad52
4
+ data.tar.gz: c17e8fa425b615639f909efa2949831030749432f253a8c20ab25f46f700deac
5
5
  SHA512:
6
- metadata.gz: 9aaf19432b00274f29165467a415c982c36ce66ef9c71ae42e7b864ed344104f8afb00afa8aa3f81b8c456e8c0f7a2668a0ca919a8ad758a03712c231db32505
7
- data.tar.gz: 5e0ae9cf031fa5936f7180be731475831831a40983a98b36187de72f245a4beb9076da2849268bb160877989fd7b15c8b4152cfc49d3af2877ab11a7a58f2b10
6
+ metadata.gz: 9f5d841173c095abf7401283f9819b9776f25310a1548396f8c89c7ebfff9738f2583f303a8ee182a4601a23b2551ba081dc88e3873138c5adeb960981f6da93
7
+ data.tar.gz: 0d0333595971757702fe3dc899c87cfa6bc7f8e7621f314c1830bd318265f6ea53dd21b791b78a310653584ba0ad7fdd893266b742469dc0458ea011f63dd7eb
data/CHANGELOG.md CHANGED
@@ -7,6 +7,33 @@ 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
+
10
37
  ---
11
38
  ## [1.3.0] - 2026-11-22
12
39
  ### Breaking Change
data/Cargo.lock CHANGED
@@ -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
 
data/README.md CHANGED
@@ -3,13 +3,13 @@
3
3
  </p>
4
4
 
5
5
  <h1 align="center">JRRToken</h1>
6
- <h2 align="center">v1.3.0</h2>
6
+ <h2 align="center">v2.0.0</h2>
7
7
 
8
8
  <p align="center">(Just Ruby, Rust, &amp; Tokens)</p>
9
9
 
10
10
  ---
11
11
 
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.
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
13
 
14
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.
15
15
 
@@ -22,31 +22,82 @@ Extensive Model Support: Includes tokenizers for all modern and legacy OpenAI mo
22
22
  ## Install
23
23
 
24
24
  #### Gemfile
25
- `gem 'j_r_r_token', '~> 1.3'`
25
+ `gem 'j_r_r_token', '~> 2.0'`
26
26
 
27
27
  #### Command Line
28
- `gem install j_r_r_token -v '~> 1.3'`
28
+ `gem install j_r_r_token -v '~> 2.0'`
29
+
30
+ Upgrading from 1.x? See [Upgrading to 2.0](#upgrading-to-20).
29
31
 
30
32
  ## Use
31
33
 
32
- ### Count tokens for a specific model (the model keyword is required)
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
+
33
68
  ```Ruby
34
- count = JRRToken::Tokenizer.count("hello world!", model: "gpt-5.4")
69
+ tok.count("<|endoftext|>") # => 7
70
+ tok.count("<|endoftext|>", special_tokens: :allow) # => 1
35
71
  ```
36
72
 
37
- ### The gem recognizes many aliases, including older models
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
+
38
76
  ```Ruby
39
- count = JRRToken::Tokenizer.count("hello world!", model: "text-davinci-003")
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
40
82
  ```
41
83
 
42
- ### The count method calls .to_s on the argument if it is not a string
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
43
87
  ```Ruby
44
- count = JRRToken::Tokenizer.count(1234, model: "o200k_base")
88
+ JRRToken.context_size("gpt-4o") # => 128000
89
+ JRRToken.context_size("unknown") # => nil
45
90
  ```
46
91
 
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
+
47
97
  ### Errors
48
- - An unsupported model name raises `ArgumentError`.
49
- - A model that isn't a String (e.g. `nil` or a Symbol) raises `TypeError`.
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.
50
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.
51
102
 
52
103
  ## Supported Models
@@ -61,6 +112,15 @@ The gem automatically maps dozens of model names and prefixes to the correct und
61
112
 
62
113
  Fine-tuned models (`ft:<base>:org:name:id`) are automatically resolved to the same tokenizer as their base model.
63
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
+
64
124
  ## Performance and Memory
65
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.
66
126
 
@@ -68,7 +128,7 @@ To keep that one-time cost out of your first request, warm up the encodings you
68
128
 
69
129
  ```Ruby
70
130
  # e.g. config/initializers/j_r_r_token.rb
71
- JRRToken::Tokenizer.count("", model: "gpt-4o")
131
+ JRRToken::Tokenizer.for_model("gpt-4o").count("")
72
132
  ```
73
133
 
74
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.
@@ -11,3 +11,4 @@ crate-type = ["cdylib"]
11
11
  [dependencies]
12
12
  magnus = "0.8.5"
13
13
  tiktoken-rs = "0.12.1"
14
+ regex = "1.13"
@@ -1,6 +1,7 @@
1
1
  use std::{collections::HashSet, sync::OnceLock};
2
2
 
3
- use magnus::{function, Error, Ruby};
3
+ use magnus::{function, method, prelude::*, Error, RString, Ruby};
4
+ use regex::Regex;
4
5
  use tiktoken_rs::{
5
6
  bpe_for_tokenizer,
6
7
  tokenizer::{get_tokenizer, Tokenizer},
@@ -25,49 +26,265 @@ fn tokenizer_for(model: &str) -> Option<Tokenizer> {
25
26
  }
26
27
  }
27
28
 
28
- // Returns the special tokens allowed when counting (all of the encoding's special
29
+ // Canonical encoding name. `Gpt2` is an alias tiktoken-rs keeps for r50k_base.
30
+ fn encoding_name(tokenizer: Tokenizer) -> &'static str {
31
+ match tokenizer {
32
+ Tokenizer::O200kHarmony => "o200k_harmony",
33
+ Tokenizer::O200kBase => "o200k_base",
34
+ Tokenizer::Cl100kBase => "cl100k_base",
35
+ Tokenizer::P50kBase => "p50k_base",
36
+ Tokenizer::P50kEdit => "p50k_edit",
37
+ Tokenizer::R50kBase | Tokenizer::Gpt2 => "r50k_base",
38
+ }
39
+ }
40
+
41
+ fn unsupported_model(ruby: &Ruby, model: &str) -> Error {
42
+ Error::new(
43
+ ruby.exception_arg_error(),
44
+ format!("Model '{}' not supported.", model),
45
+ )
46
+ }
47
+
48
+ // Returns the special tokens allowed when encoding (all of the encoding's special
29
49
  // tokens, matching `encode_with_special_tokens`). The set is built once per encoding
30
50
  // and cached: `CoreBPE::special_tokens()` allocates a fresh set on every call, which
31
51
  // is noticeable for o200k_harmony (~1,100 special tokens).
32
52
  fn allowed_special(tokenizer: Tokenizer, bpe: &'static CoreBPE) -> &'static HashSet<&'static str> {
33
53
  static SETS: [OnceLock<HashSet<&'static str>>; 6] = [const { OnceLock::new() }; 6];
34
- let index = match tokenizer {
54
+ SETS[cache_slot(tokenizer)].get_or_init(|| bpe.special_tokens())
55
+ }
56
+
57
+ // Matches any of the encoding's special tokens, for `special_tokens: :raise`. Built once
58
+ // per encoding. Longest tokens come first so an overlapping match reports the full token.
59
+ // (The regex crate compiles a literal alternation like this to an Aho-Corasick search.)
60
+ fn special_token_regex(tokenizer: Tokenizer, bpe: &'static CoreBPE) -> &'static Regex {
61
+ static REGEXES: [OnceLock<Regex>; 6] = [const { OnceLock::new() }; 6];
62
+ REGEXES[cache_slot(tokenizer)].get_or_init(|| {
63
+ let mut tokens: Vec<&str> = allowed_special(tokenizer, bpe).iter().copied().collect();
64
+ tokens.sort_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));
65
+ let pattern = tokens
66
+ .iter()
67
+ .map(|token| regex::escape(token))
68
+ .collect::<Vec<_>>()
69
+ .join("|");
70
+ Regex::new(&pattern).expect("special token alternation is a valid regex")
71
+ })
72
+ }
73
+
74
+ // Per-encoding cache index. Gpt2 resolves to the same r50k_base singleton.
75
+ fn cache_slot(tokenizer: Tokenizer) -> usize {
76
+ match tokenizer {
35
77
  Tokenizer::O200kHarmony => 0,
36
78
  Tokenizer::O200kBase => 1,
37
79
  Tokenizer::Cl100kBase => 2,
38
80
  Tokenizer::P50kBase => 3,
39
81
  Tokenizer::P50kEdit => 4,
40
- // Gpt2 resolves to the same r50k_base singleton.
41
82
  Tokenizer::R50kBase | Tokenizer::Gpt2 => 5,
42
- };
43
- SETS[index].get_or_init(|| bpe.special_tokens())
83
+ }
84
+ }
85
+
86
+ /// A tokenizer for one encoding, exposed to Ruby as `JRRToken::Tokenizer`.
87
+ ///
88
+ /// Instances only hold the encoding; the heavy `CoreBPE` is the process-wide singleton
89
+ /// from `bpe_for_tokenizer`, so instances are cheap. The Ruby side builds one frozen
90
+ /// instance per encoding and hands those out from `Tokenizer.for_model`.
91
+ #[magnus::wrap(class = "JRRToken::Tokenizer", free_immediately, size)]
92
+ struct RbTokenizer {
93
+ tokenizer: Tokenizer,
94
+ }
95
+
96
+ impl RbTokenizer {
97
+ // Private constructor, `Tokenizer._build(encoding_name)`.
98
+ fn build(ruby: &Ruby, encoding: String) -> Result<Self, Error> {
99
+ let tokenizer = match encoding.as_str() {
100
+ "o200k_harmony" | "o200k_base" | "cl100k_base" | "p50k_base" | "p50k_edit"
101
+ | "r50k_base" => tokenizer_for(&encoding),
102
+ _ => None,
103
+ }
104
+ .ok_or_else(|| {
105
+ Error::new(
106
+ ruby.exception_arg_error(),
107
+ format!("Unknown encoding '{}'.", encoding),
108
+ )
109
+ })?;
110
+ Ok(Self { tokenizer })
111
+ }
112
+
113
+ fn bpe(&self, ruby: &Ruby) -> Result<&'static CoreBPE, Error> {
114
+ // `bpe_for_tokenizer` returns a process-wide `&'static CoreBPE` singleton, so the
115
+ // vocabulary is decoded and the regexes are compiled once per encoding, not on
116
+ // every call. It currently never returns `Err` (a failed build panics inside
117
+ // tiktoken-rs's lazy static); the `map_err` only guards against future changes.
118
+ bpe_for_tokenizer(self.tokenizer)
119
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))
120
+ }
121
+
122
+ fn encoding(&self) -> &'static str {
123
+ encoding_name(self.tokenizer)
124
+ }
125
+
126
+ // Encodes `text`. With `allow_special`, special-token strings (e.g. "<|endoftext|>")
127
+ // become their special token ids; otherwise they're encoded as ordinary text.
128
+ //
129
+ // Both paths use the fallible `CoreBPE::encode` (with an empty allowed set for plain
130
+ // text) rather than `encode_with_special_tokens` / `encode_ordinary`, which unwrap
131
+ // tokenizer regex failures and would panic (Ruby `fatal`) on pathological input.
132
+ fn encode_ranks(&self, ruby: &Ruby, text: &str, allow_special: bool) -> Result<Vec<u32>, Error> {
133
+ let bpe = self.bpe(ruby)?;
134
+ let none = HashSet::new();
135
+ let allowed = if allow_special {
136
+ allowed_special(self.tokenizer, bpe)
137
+ } else {
138
+ &none
139
+ };
140
+ bpe.encode(text, allowed)
141
+ .map(|(tokens, _)| tokens)
142
+ .map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))
143
+ }
144
+
145
+ // `Tokenizer#_count(text, allow_special)`
146
+ fn count(ruby: &Ruby, rb_self: &Self, text: String, allow_special: bool) -> Result<usize, Error> {
147
+ rb_self.encode_ranks(ruby, &text, allow_special).map(|tokens| tokens.len())
148
+ }
149
+
150
+ // `Tokenizer#_encode(text, allow_special)`
151
+ fn encode(
152
+ ruby: &Ruby,
153
+ rb_self: &Self,
154
+ text: String,
155
+ allow_special: bool,
156
+ ) -> Result<Vec<u32>, Error> {
157
+ rb_self.encode_ranks(ruby, &text, allow_special)
158
+ }
159
+
160
+ // `Tokenizer#_split(text, allow_special)`: the text of each token, 1:1 with `encode`.
161
+ // Bytes of a multi-byte character split across tokens (common for emoji and CJK) can't
162
+ // be shown on their own, so they become U+FFFD; use encode + decode_bytes for exact
163
+ // bytes.
164
+ fn split(
165
+ ruby: &Ruby,
166
+ rb_self: &Self,
167
+ text: String,
168
+ allow_special: bool,
169
+ ) -> Result<Vec<String>, Error> {
170
+ let tokens = rb_self.encode_ranks(ruby, &text, allow_special)?;
171
+ tokens
172
+ .iter()
173
+ .map(|token| {
174
+ rb_self
175
+ .decode_to_bytes(ruby, std::slice::from_ref(token))
176
+ .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
177
+ })
178
+ .collect()
179
+ }
180
+
181
+ // `Tokenizer#_find_special(text)`: the first special-token string in `text`, or nil.
182
+ fn find_special(ruby: &Ruby, rb_self: &Self, text: String) -> Result<Option<String>, Error> {
183
+ let bpe = rb_self.bpe(ruby)?;
184
+ Ok(special_token_regex(rb_self.tokenizer, bpe)
185
+ .find(&text)
186
+ .map(|m| m.as_str().to_owned()))
187
+ }
188
+
189
+ // `Tokenizer#_truncate(text, max_tokens, allow_special)`: `text` cut at a token
190
+ // boundary, i.e. the text of the first `max_tokens` tokens of its encoding (the
191
+ // `decode(encode(text)[..n])` idiom). This is not necessarily the longest prefix that
192
+ // fits: a slightly longer prefix can sometimes re-encode within budget, but finding it
193
+ // would need a character-level search (token count isn't monotonic in prefix length).
194
+ // Cost is one full encode of `text`, plus a re-encode of the result.
195
+ //
196
+ // Decoding the first `max_tokens` tokens yields a byte prefix of `text`; if the cut
197
+ // lands inside a multi-byte character, the partial character is dropped so the result
198
+ // is valid UTF-8. BPE boundaries can shift when a prefix is re-encoded, so the result
199
+ // is re-counted and shortened one token at a time until it fits; this guarantees
200
+ // `count(result) <= max_tokens`. It's almost always a single pass.
201
+ fn truncate(
202
+ ruby: &Ruby,
203
+ rb_self: &Self,
204
+ text: String,
205
+ max_tokens: usize,
206
+ allow_special: bool,
207
+ ) -> Result<String, Error> {
208
+ let tokens = rb_self.encode_ranks(ruby, &text, allow_special)?;
209
+ if tokens.len() <= max_tokens {
210
+ return Ok(text);
211
+ }
212
+ let mut keep = max_tokens;
213
+ loop {
214
+ let bytes = rb_self.decode_to_bytes(ruby, &tokens[..keep])?;
215
+ let valid_len = match std::str::from_utf8(&bytes) {
216
+ Ok(_) => bytes.len(),
217
+ Err(e) => e.valid_up_to(),
218
+ };
219
+ // A prefix of the decoded token bytes is a prefix of `text` (tokens concatenate
220
+ // to the original bytes), so slicing `text` keeps the caller's exact characters.
221
+ let prefix = text.get(..valid_len).ok_or_else(|| {
222
+ Error::new(
223
+ ruby.exception_runtime_error(),
224
+ "truncate: decoded tokens are not a prefix of the input text",
225
+ )
226
+ })?;
227
+ if keep == 0 || rb_self.encode_ranks(ruby, prefix, allow_special)?.len() <= max_tokens {
228
+ return Ok(prefix.to_owned());
229
+ }
230
+ keep -= 1;
231
+ }
232
+ }
233
+
234
+ fn decode_to_bytes(&self, ruby: &Ruby, tokens: &[u32]) -> Result<Vec<u8>, Error> {
235
+ let bpe = self.bpe(ruby)?;
236
+ bpe.decode_bytes(tokens).map_err(|e| {
237
+ Error::new(
238
+ ruby.exception_arg_error(),
239
+ format!("Invalid token {} for {}.", e.token, self.encoding()),
240
+ )
241
+ })
242
+ }
243
+
244
+ // `Tokenizer#_decode(tokens)`. Bytes that aren't valid UTF-8 (a token slice that cuts
245
+ // a multi-byte character) become U+FFFD, matching Python tiktoken's default
246
+ // `errors="replace"`. Unknown token ids raise ArgumentError.
247
+ fn decode(ruby: &Ruby, rb_self: &Self, tokens: Vec<u32>) -> Result<String, Error> {
248
+ let bytes = rb_self.decode_to_bytes(ruby, &tokens)?;
249
+ Ok(String::from_utf8_lossy(&bytes).into_owned())
250
+ }
251
+
252
+ // `Tokenizer#_decode_bytes(tokens)`: the exact bytes as a binary (ASCII-8BIT) String.
253
+ fn decode_bytes(ruby: &Ruby, rb_self: &Self, tokens: Vec<u32>) -> Result<RString, Error> {
254
+ let bytes = rb_self.decode_to_bytes(ruby, &tokens)?;
255
+ Ok(ruby.str_from_slice(&bytes))
256
+ }
257
+ }
258
+
259
+ // `JRRToken.context_size(model)`: the model's context window in tokens, from tiktoken-rs's
260
+ // model table, or nil if the model isn't in it. Accepts `ft:` fine-tune names.
261
+ fn context_size(model: String) -> Option<usize> {
262
+ tiktoken_rs::model::get_context_size(&model)
44
263
  }
45
264
 
46
- // This function is exposed to Ruby.
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()))
265
+ // `Tokenizer._encoding_for(model)`: resolves a model or encoding name to the canonical
266
+ // encoding name, raising ArgumentError for unsupported models.
267
+ fn encoding_for(ruby: &Ruby, model: String) -> Result<&'static str, Error> {
268
+ tokenizer_for(&model)
269
+ .map(encoding_name)
270
+ .ok_or_else(|| unsupported_model(ruby, &model))
66
271
  }
67
272
 
68
273
  #[magnus::init]
69
274
  fn init(ruby: &Ruby) -> Result<(), Error> {
70
275
  let module = ruby.define_module("JRRToken")?;
71
- module.define_module_function("count_tokens", function!(count_tokens, 2))?;
276
+ module.define_singleton_method("context_size", function!(context_size, 1))?;
277
+ let class = module.define_class("Tokenizer", ruby.class_object())?;
278
+ // Instances are only created through `_build` (and handed out by `for_model`).
279
+ class.undef_default_alloc_func();
280
+ class.define_singleton_method("_build", function!(RbTokenizer::build, 1))?;
281
+ class.define_singleton_method("_encoding_for", function!(encoding_for, 1))?;
282
+ class.define_private_method("_count", method!(RbTokenizer::count, 2))?;
283
+ class.define_private_method("_encode", method!(RbTokenizer::encode, 2))?;
284
+ class.define_private_method("_find_special", method!(RbTokenizer::find_special, 1))?;
285
+ class.define_private_method("_truncate", method!(RbTokenizer::truncate, 3))?;
286
+ class.define_private_method("_split", method!(RbTokenizer::split, 2))?;
287
+ class.define_private_method("_decode", method!(RbTokenizer::decode, 1))?;
288
+ class.define_private_method("_decode_bytes", method!(RbTokenizer::decode_bytes, 1))?;
72
289
  Ok(())
73
290
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JRRToken
4
- VERSION = "1.3.0"
4
+ VERSION = "2.0.0"
5
5
  end
data/lib/j_r_r_token.rb CHANGED
@@ -8,27 +8,443 @@ begin
8
8
  rescue LoadError
9
9
  begin
10
10
  require "j_r_r_token/j_r_r_token"
11
- rescue LoadError
12
- warn "Failed to load j_r_r_token native extension."
11
+ rescue LoadError => e
12
+ raise LoadError, "j_r_r_token native extension failed to load: #{e.message}"
13
13
  end
14
14
  end
15
15
 
16
16
  module JRRToken
17
17
  class Error < StandardError; end
18
18
 
19
- # This is the main public interface for the gem.
19
+ # @!method self.context_size(model)
20
+ # The model's context window in tokens (e.g. 128_000 for "gpt-4o"), or nil if the
21
+ # model isn't in tiktoken-rs's table. Fine-tuned names ("ft:gpt-4o:org:name:id")
22
+ # resolve to their base model. Defined by the native extension.
23
+ #
24
+ # Values come from tiktoken-rs's prefix-matched table as-is, so they can be stale or
25
+ # loose (e.g. bare "gpt-4-turbo" reports 8,192, "davinci-002" 2,049), and a name can
26
+ # have a context size without having a tokenizer (e.g. "gpt-6", "o4").
27
+ #
28
+ # @param model [String]
29
+ # @return [Integer, nil]
30
+ # @raise [TypeError] if model is not a String
31
+
32
+ # Encodings that chat models use; count_messages only supports these.
33
+ CHAT_ENCODINGS = %w[o200k_harmony o200k_base cl100k_base].freeze
34
+ private_constant :CHAT_ENCODINGS
35
+
36
+ # Estimates the prompt tokens for a list of chat messages, including the per-message
37
+ # framing tokens chat models add, using OpenAI's cookbook formula. The constants and the
38
+ # handling of OpenAI-shaped messages mirror tiktoken-rs 0.12.1's num_tokens_from_messages
39
+ # and its async-openai adapter (re-verify on tiktoken-rs bumps). It's an estimate: tool
40
+ # definitions and non-text content (images, audio, files) aren't counted, and providers
41
+ # can change their framing.
42
+ #
43
+ # Each message is a Hash with String or Symbol keys:
44
+ # - "role" (required).
45
+ # - "content": a String, nil, or an Array of content parts. "text" parts are joined and
46
+ # counted; "refusal" parts are joined and counted as the refusal; "image_url",
47
+ # "input_audio" and "file" parts are skipped (not counted). Unknown part types raise.
48
+ # - optional "name", "refusal", "function_call" ({name:, arguments:}) and "tool_calls":
49
+ # an Array of {function: {name:, arguments:}} or {type: "custom", custom: {name:, input:}}
50
+ # as in the OpenAI API, or flat {name:, arguments:}.
51
+ # - for "tool" messages, "tool_call_id" is counted as the name, as tiktoken-rs does.
52
+ # Other keys are ignored.
53
+ #
54
+ # JRRToken.count_messages([{role: "user", content: "Hello!"}], model: "gpt-4o") # => 9
55
+ #
56
+ # @param messages [Array<Hash>]
57
+ # @param model [String] a chat model (o200k_base, o200k_harmony or cl100k_base encoding)
58
+ # @param special_tokens [Symbol] :text (default), :allow or :raise; see Tokenizer
59
+ # @return [Integer]
60
+ # @raise [ArgumentError] for an unsupported model or a malformed message
61
+ def self.count_messages(messages, model:, special_tokens: :text)
62
+ tokenizer = Tokenizer.for_model(model)
63
+ unless CHAT_ENCODINGS.include?(tokenizer.encoding)
64
+ raise ArgumentError, "count_messages supports chat models (o200k_base, o200k_harmony or " \
65
+ "cl100k_base encodings); '#{model}' uses #{tokenizer.encoding}."
66
+ end
67
+ list = Array.try_convert(messages) or raise TypeError, "messages must be an Array, got #{messages.class}"
68
+
69
+ # gpt-3.5-turbo-0301 used different framing (kept for parity with tiktoken-rs).
70
+ per_message, per_name = model == "gpt-3.5-turbo-0301" ? [4, -1] : [3, 1]
71
+ count = ->(text) { tokenizer.count(text, special_tokens: special_tokens) }
72
+
73
+ total = 3 # every reply is primed with <|start|>assistant<|message|>
74
+ list.each_with_index do |raw, index|
75
+ message = MessageFields.new(raw, index)
76
+ total += per_message
77
+ total += count.(message.role)
78
+ content, refusal = message.content_and_refusal
79
+ total += count.(content) if content
80
+ if (name = message.name)
81
+ total += count.(name) + per_name
82
+ end
83
+ total += count.(refusal) if refusal
84
+ message.function_calls.each do |function_name, arguments|
85
+ total += count.(function_name) + count.(arguments) + 1
86
+ end
87
+ end
88
+ total
89
+ end
90
+
91
+ # Reads a chat message Hash with String or Symbol keys. Internal to count_messages.
92
+ class MessageFields
93
+ NON_TEXT_PARTS = %w[image_url input_audio file].freeze
94
+
95
+ def initialize(message, index)
96
+ @index = index
97
+ @message = Hash.try_convert(message) or
98
+ raise TypeError, "message #{index} must be a Hash, got #{message.class}"
99
+ end
100
+
101
+ def role
102
+ @role ||= string_field(@message, "role", required: true)
103
+ end
104
+
105
+ # The name, or for "tool" messages without one, the tool_call_id (as tiktoken-rs counts it).
106
+ def name
107
+ name = string_field(@message, "name")
108
+ name ||= string_field(@message, "tool_call_id") if role == "tool"
109
+ name
110
+ end
111
+
112
+ # [content_text_or_nil, refusal_or_nil]. Text parts are joined with ""; refusal parts are
113
+ # joined and take precedence over a "refusal" field.
114
+ def content_and_refusal
115
+ content = value(@message, "content")
116
+ refusal_field = string_field(@message, "refusal")
117
+ case content
118
+ when nil then [nil, refusal_field]
119
+ when String then [content, refusal_field]
120
+ when Array
121
+ texts = []
122
+ refusals = []
123
+ content.each_with_index do |raw_part, i|
124
+ part = Hash.try_convert(raw_part) or
125
+ raise TypeError, "message #{@index} content part #{i} must be a Hash, got #{raw_part.class}"
126
+ type = string_field(part, "type", required: true, label: "content[#{i}].type")
127
+ case type
128
+ when "text" then texts << string_field(part, "text", required: true, label: "content[#{i}].text")
129
+ when "refusal" then refusals << string_field(part, "refusal", required: true, label: "content[#{i}].refusal")
130
+ when *NON_TEXT_PARTS
131
+ next # not countable as text; skipped, as tiktoken-rs does
132
+ else
133
+ raise ArgumentError, "message #{@index} content part #{i} has unknown type \"#{type}\""
134
+ end
135
+ end
136
+ [join(texts), join(refusals) || refusal_field]
137
+ else
138
+ raise TypeError, "message #{@index} \"content\" must be a String, Array or nil, got #{content.class}"
139
+ end
140
+ end
141
+
142
+ # [[name, arguments], ...] from function_call and tool_calls.
143
+ def function_calls
144
+ calls = []
145
+ function_call = value(@message, "function_call")
146
+ calls << function_pair(function_call, "function_call") if function_call
147
+ raw_calls = value(@message, "tool_calls")
148
+ return calls unless raw_calls
149
+
150
+ tool_calls = Array.try_convert(raw_calls) or
151
+ raise TypeError, "message #{@index} \"tool_calls\" must be an Array, got #{raw_calls.class}"
152
+ tool_calls.each_with_index do |raw_call, i|
153
+ label = "tool_calls[#{i}]"
154
+ tool_call = Hash.try_convert(raw_call) or
155
+ raise TypeError, "message #{@index} #{label} must be a Hash, got #{raw_call.class}"
156
+ if (custom = value(tool_call, "custom"))
157
+ calls << custom_pair(custom, "#{label}.custom")
158
+ elsif (function = value(tool_call, "function"))
159
+ calls << function_pair(function, "#{label}.function")
160
+ else
161
+ calls << function_pair(tool_call, label)
162
+ end
163
+ end
164
+ calls
165
+ end
166
+
167
+ private
168
+
169
+ def value(hash, key)
170
+ hash.fetch(key) { hash.fetch(key.to_sym, nil) }
171
+ end
172
+
173
+ def string_field(hash, key, required: false, label: key)
174
+ field = value(hash, key)
175
+ if field.nil?
176
+ raise ArgumentError, "message #{@index} is missing \"#{label}\"" if required
177
+
178
+ return nil
179
+ end
180
+ raise TypeError, "message #{@index} \"#{label}\" must be a String, got #{field.class}" unless field.is_a?(String)
181
+
182
+ field
183
+ end
184
+
185
+ def join(texts)
186
+ texts.empty? ? nil : texts.join
187
+ end
188
+
189
+ def function_pair(raw_call, label)
190
+ call = hash_for(raw_call, label)
191
+ [string_field(call, "name", required: true, label: "#{label}.name"),
192
+ string_field(call, "arguments", required: true, label: "#{label}.arguments")]
193
+ end
194
+
195
+ def custom_pair(raw_call, label)
196
+ call = hash_for(raw_call, label)
197
+ [string_field(call, "name", required: true, label: "#{label}.name"),
198
+ string_field(call, "input", required: true, label: "#{label}.input")]
199
+ end
200
+
201
+ def hash_for(raw, label)
202
+ Hash.try_convert(raw) or raise TypeError, "message #{@index} #{label} must be a Hash, got #{raw.class}"
203
+ end
204
+ end
205
+ private_constant :MessageFields
206
+
207
+ # Raised with `special_tokens: :raise` when the text contains a special-token string
208
+ # such as "<|endoftext|>".
209
+ class SpecialTokenError < ArgumentError; end
210
+
211
+ # A tokenizer for one encoding (e.g. o200k_base). The class itself is defined by the
212
+ # native extension; this file adds the public Ruby interface.
213
+ #
214
+ # tok = JRRToken::Tokenizer.for_model("gpt-4o")
215
+ # tok.encoding # => "o200k_base"
216
+ # tok.count("hello world") # => 2
217
+ # tok.encode("hello world") # => [24912, 2375]
218
+ #
219
+ # Every instance method also has a class-level shortcut that takes `model:`:
220
+ #
221
+ # JRRToken::Tokenizer.count("hello world", model: "gpt-4o") # => 2
222
+ #
223
+ # == Special tokens
224
+ #
225
+ # `count`, `encode` and `truncate` take `special_tokens:`, which controls what happens
226
+ # when the text contains a special-token string such as "<|endoftext|>":
227
+ #
228
+ # - `:text` (default): treat it as ordinary text. Right for user-supplied input.
229
+ # - `:allow`: encode it as the single special token.
230
+ # - `:raise`: raise JRRToken::SpecialTokenError.
231
+ #
232
+ # == Text
233
+ #
234
+ # Text is converted with #to_s. Binary (ASCII-8BIT) strings, such as File.binread or
235
+ # HTTP bodies, and US-ASCII strings holding non-ASCII bytes (File.read with no locale set)
236
+ # are read as UTF-8 when their bytes are valid UTF-8; other encodings are transcoded to
237
+ # UTF-8. Invalid input raises ArgumentError. Returned strings are UTF-8.
20
238
  class Tokenizer
21
- # Counts tokens for a given text using a specified model name.
22
- # The underlying Rust extension will handle mapping the model name
23
- # to the correct tokenizer.
239
+ ENCODINGS = %w[o200k_harmony o200k_base cl100k_base p50k_base p50k_edit r50k_base].freeze
240
+ SPECIAL_TOKEN_MODES = %i[text allow raise].freeze
241
+
242
+ # One shared, frozen instance per encoding. Instances only hold the encoding; the
243
+ # tokenizer data itself is built lazily on first use and cached process-wide.
244
+ INSTANCES = ENCODINGS.to_h do |name|
245
+ instance = _build(name)
246
+ instance.instance_variable_set(:@encoding, name)
247
+ [name, instance.freeze]
248
+ end.freeze
249
+ private_constant :INSTANCES
250
+
251
+ private_class_method :_build, :_encoding_for, :new, :allocate
252
+
253
+ class << self
254
+ # Returns the tokenizer for a model name (e.g. "gpt-4o", "ft:gpt-4o:org:name:id")
255
+ # or a bare encoding name (e.g. "o200k_base"). Models that share an encoding return
256
+ # the same frozen instance.
257
+ #
258
+ # @param model [String]
259
+ # @return [JRRToken::Tokenizer]
260
+ # @raise [ArgumentError] if the model is not supported
261
+ def for_model(model)
262
+ INSTANCES.fetch(_encoding_for(model))
263
+ end
264
+
265
+ # @return [Integer] the number of tokens in `text`
266
+ def count(text, model:, special_tokens: :text)
267
+ for_model(model).count(text, special_tokens: special_tokens)
268
+ end
269
+
270
+ # @return [Array<Integer>] the token ids for `text`
271
+ def encode(text, model:, special_tokens: :text)
272
+ for_model(model).encode(text, special_tokens: special_tokens)
273
+ end
274
+
275
+ # @return [String] `text` cut at a token boundary to fit `max_tokens` tokens
276
+ def truncate(text, max_tokens:, model:, special_tokens: :text)
277
+ for_model(model).truncate(text, max_tokens: max_tokens, special_tokens: special_tokens)
278
+ end
279
+
280
+ # @return [Array<String>] the text of each token in `text`
281
+ def split(text, model:, special_tokens: :text)
282
+ for_model(model).split(text, special_tokens: special_tokens)
283
+ end
284
+
285
+ # @return [String] the text for the token ids
286
+ def decode(tokens, model:)
287
+ for_model(model).decode(tokens)
288
+ end
289
+
290
+ # @return [String] the exact bytes for the token ids, as a binary String
291
+ def decode_bytes(tokens, model:)
292
+ for_model(model).decode_bytes(tokens)
293
+ end
294
+ end
295
+
296
+ # @return [String] the encoding name, e.g. "o200k_base" (frozen)
297
+ attr_reader :encoding
298
+
299
+ # Counts the tokens in `text` (converted with #to_s).
300
+ #
301
+ # @param special_tokens [Symbol] :text (default), :allow or :raise; see the class docs
302
+ # @return [Integer]
303
+ # @raise [JRRToken::SpecialTokenError] with `special_tokens: :raise`
304
+ def count(text, special_tokens: :text)
305
+ text = utf8_text(text)
306
+ _count(text, allow_special?(text, special_tokens))
307
+ end
308
+
309
+ # Encodes `text` (converted with #to_s) into token ids.
310
+ #
311
+ # @param special_tokens [Symbol] :text (default), :allow or :raise; see the class docs
312
+ # @return [Array<Integer>]
313
+ # @raise [JRRToken::SpecialTokenError] with `special_tokens: :raise`
314
+ def encode(text, special_tokens: :text)
315
+ text = utf8_text(text)
316
+ _encode(text, allow_special?(text, special_tokens))
317
+ end
318
+
319
+ # Returns `text` (converted with #to_s) cut at a token boundary: the text of its first
320
+ # `max_tokens` tokens (fewer if needed to stay within budget), dropping a trailing
321
+ # character the cut would split. The result is always a prefix of the input, valid
322
+ # UTF-8, and `count(result, special_tokens:)` is at most `max_tokens`. Text that
323
+ # already fits is returned unchanged. It is not necessarily the longest prefix that
324
+ # fits. Runs in time linear in the length of `text` (one full encode).
24
325
  #
25
- # @param text [String] The text to tokenize.
26
- # @param model [String] The name of the model (e.g., "gpt-4o", "gpt-3.5-turbo").
27
- # @return [Integer] The number of tokens.
28
- def self.count(text, model:)
29
- # This calls the `count_tokens` function from our Rust code,
30
- # passing both the model and the text.
31
- JRRToken.count_tokens(model, text.to_s)
326
+ # @param max_tokens [Integer] a non-negative token budget
327
+ # @param special_tokens [Symbol] :text (default), :allow or :raise; see the class docs
328
+ # @return [String]
329
+ # @raise [JRRToken::SpecialTokenError] with `special_tokens: :raise`
330
+ def truncate(text, max_tokens:, special_tokens: :text)
331
+ raise TypeError, "max_tokens must be an Integer, got #{max_tokens.class}" unless max_tokens.is_a?(Integer)
332
+ raise ArgumentError, "max_tokens must be non-negative, got #{max_tokens}" if max_tokens.negative?
333
+
334
+ text = utf8_text(text)
335
+ _truncate(text, max_tokens, allow_special?(text, special_tokens))
336
+ end
337
+
338
+ # Splits `text` (converted with #to_s) into the text of each of its tokens, e.g.
339
+ # "hello world" -> ["hello", " world"]. Pieces stay 1:1 with #encode's ids. Bytes of a
340
+ # multi-byte character split across tokens (common for emoji and CJK) are shown as
341
+ # U+FFFD, so joining the pieces doesn't always reproduce `text`; for exact bytes, use
342
+ # `encode(text).map { |id| decode_bytes([id]) }`.
343
+ #
344
+ # @param special_tokens [Symbol] :text (default), :allow or :raise; see the class docs
345
+ # @return [Array<String>]
346
+ # @raise [JRRToken::SpecialTokenError] with `special_tokens: :raise`
347
+ def split(text, special_tokens: :text)
348
+ text = utf8_text(text)
349
+ _split(text, allow_special?(text, special_tokens))
350
+ end
351
+
352
+ # Decodes token ids back into text. Bytes that don't form valid UTF-8 (for example,
353
+ # a slice of tokens that cuts a multi-byte character in half) become U+FFFD.
354
+ #
355
+ # @param tokens [Array<Integer>]
356
+ # @return [String]
357
+ # @raise [ArgumentError] if a token id is not part of this encoding
358
+ def decode(tokens)
359
+ _decode(token_ids(tokens))
360
+ end
361
+
362
+ # Decodes token ids into their exact bytes, returned as a binary (ASCII-8BIT) String.
363
+ # Unlike #decode, nothing is replaced, so partial characters are preserved (useful
364
+ # when joining the output of several token slices before converting to UTF-8).
365
+ #
366
+ # @param tokens [Array<Integer>]
367
+ # @return [String]
368
+ # @raise [ArgumentError] if a token id is not part of this encoding
369
+ def decode_bytes(tokens)
370
+ _decode_bytes(token_ids(tokens))
371
+ end
372
+
373
+ # Instances are immutable and shared (one per encoding), so like Integer and Symbol,
374
+ # copying returns the receiver itself.
375
+ def dup
376
+ self
377
+ end
378
+
379
+ def clone(freeze: nil)
380
+ unless [nil, true, false].include?(freeze)
381
+ raise ArgumentError, "unexpected value for freeze: #{freeze.class}"
382
+ end
383
+ raise ArgumentError, "can't unfreeze #{self.class.name}" if freeze == false
384
+
385
+ self
386
+ end
387
+
388
+ def inspect
389
+ "#<#{self.class.name} #{encoding}>"
390
+ end
391
+ alias to_s inspect
392
+
393
+ # Marshal support: a tokenizer is dumped as its encoding name and loads back as the
394
+ # shared instance, so it can live inside cached or marshaled objects.
395
+ def _dump(_level)
396
+ encoding
397
+ end
398
+
399
+ def self._load(encoding)
400
+ for_model(encoding)
401
+ end
402
+
403
+ private
404
+
405
+ # Binary strings, and US-ASCII strings with non-ASCII bytes (File.read in a process with
406
+ # no locale, e.g. a Docker image without LANG), usually hold mislabeled UTF-8.
407
+ def utf8_text(text)
408
+ text = text.to_s
409
+ if text.encoding == Encoding::BINARY || (text.encoding == Encoding::US_ASCII && !text.ascii_only?)
410
+ utf8 = text.dup.force_encoding(Encoding::UTF_8)
411
+ return utf8 if utf8.valid_encoding?
412
+
413
+ raise ArgumentError, "invalid byte sequence in UTF-8 (#{text.encoding} text must contain UTF-8 bytes)"
414
+ end
415
+ raise ArgumentError, "invalid byte sequence in #{text.encoding}" unless text.valid_encoding?
416
+
417
+ text
418
+ end
419
+
420
+ # Validates the `special_tokens:` mode, enforces :raise, and returns whether special
421
+ # tokens should be encoded as such.
422
+ def allow_special?(text, mode)
423
+ unless SPECIAL_TOKEN_MODES.include?(mode)
424
+ raise ArgumentError, "special_tokens must be one of :text, :allow or :raise, got #{mode.inspect}"
425
+ end
426
+
427
+ if mode == :raise
428
+ token = _find_special(text)
429
+ if token
430
+ raise SpecialTokenError,
431
+ "Text contains the special token #{token.inspect}. Pass special_tokens: :text " \
432
+ "to treat it as plain text, or special_tokens: :allow to encode it as a special token."
433
+ end
434
+ end
435
+
436
+ mode == :allow
437
+ end
438
+
439
+ def token_ids(tokens)
440
+ array = Array.try_convert(tokens)
441
+ raise TypeError, "no implicit conversion of #{tokens.class} into Array" unless array
442
+ unless array.all?(Integer)
443
+ bad = array.find { |id| !id.is_a?(Integer) }
444
+ raise TypeError, "token ids must be Integers, got #{bad.class}"
445
+ end
446
+
447
+ array
32
448
  end
33
449
  end
34
450
  end
data/sig/j_r_r_token.rbs CHANGED
@@ -1,15 +1,52 @@
1
1
  module JRRToken
2
2
  VERSION: String
3
3
 
4
- # Native extension entry point (implemented in Rust).
5
- def self.count_tokens: (String model, String text) -> Integer
4
+ type special_tokens_mode = :text | :allow | :raise
5
+
6
+ type message_key = String | Symbol
7
+ type message = Hash[message_key, untyped]
6
8
 
7
9
  class Error < StandardError
8
10
  end
9
11
 
12
+ # Raised with `special_tokens: :raise` when text contains a special-token string.
13
+ class SpecialTokenError < ArgumentError
14
+ end
15
+
16
+ # The model's context window in tokens, or nil if the model isn't in tiktoken-rs's table.
17
+ def self.context_size: (String model) -> Integer?
18
+
19
+ # Estimated prompt tokens for chat messages (framing and reply priming included).
20
+ def self.count_messages: (Array[message] messages, model: String, ?special_tokens: special_tokens_mode) -> Integer
21
+
10
22
  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
23
+ ENCODINGS: Array[String]
24
+ SPECIAL_TOKEN_MODES: Array[special_tokens_mode]
25
+
26
+ # The shared, frozen tokenizer for a model or bare encoding name.
27
+ def self.for_model: (String model) -> Tokenizer
28
+
29
+ def self.count: (_ToS text, model: String, ?special_tokens: special_tokens_mode) -> Integer
30
+ def self.encode: (_ToS text, model: String, ?special_tokens: special_tokens_mode) -> Array[Integer]
31
+ def self.decode: (Array[Integer] tokens, model: String) -> String
32
+ def self.decode_bytes: (Array[Integer] tokens, model: String) -> String
33
+ def self.truncate: (_ToS text, max_tokens: Integer, model: String, ?special_tokens: special_tokens_mode) -> String
34
+ def self.split: (_ToS text, model: String, ?special_tokens: special_tokens_mode) -> Array[String]
35
+ def self._load: (String encoding) -> Tokenizer
36
+
37
+ # The encoding name, e.g. "o200k_base" (frozen).
38
+ attr_reader encoding: String
39
+
40
+ def count: (_ToS text, ?special_tokens: special_tokens_mode) -> Integer
41
+ def encode: (_ToS text, ?special_tokens: special_tokens_mode) -> Array[Integer]
42
+ def decode: (Array[Integer] tokens) -> String
43
+ def decode_bytes: (Array[Integer] tokens) -> String
44
+ def truncate: (_ToS text, max_tokens: Integer, ?special_tokens: special_tokens_mode) -> String
45
+ def split: (_ToS text, ?special_tokens: special_tokens_mode) -> Array[String]
46
+ def dup: () -> self
47
+ def clone: (?freeze: bool?) -> self
48
+ def inspect: () -> String
49
+ def to_s: () -> String
50
+ def _dump: (Integer level) -> String
14
51
  end
15
52
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: j_r_r_token
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Logan Bresnahan