j_r_r_token 1.3.0-x86_64-linux → 2.0.0-x86_64-linux
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 +27 -0
- data/README.md +73 -13
- data/lib/j_r_r_token/3.0/j_r_r_token.so +0 -0
- data/lib/j_r_r_token/3.1/j_r_r_token.so +0 -0
- data/lib/j_r_r_token/3.2/j_r_r_token.so +0 -0
- data/lib/j_r_r_token/3.3/j_r_r_token.so +0 -0
- data/lib/j_r_r_token/3.4/j_r_r_token.so +0 -0
- data/lib/j_r_r_token/4.0/j_r_r_token.so +0 -0
- 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 +42 -5
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4773b81c295b6c4ddadeef6f2db97eafdcc35c65635a536cc43b668cb32d1cdc
|
|
4
|
+
data.tar.gz: 2b9050f0419010f6bca4bea769c24aa6481907f5a5b414de2c1ac2f647637922
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: dd26e09de03b041c1c18a2d2787a1732fd781af1803c708e10b4b8a2db766b4257e92336b2bae0747edb35489c023e4de7eae26025b8ada22c7f8fa8753de074
|
|
7
|
+
data.tar.gz: ea23d1dacf6c0c13b935cbaaf6f71122eecf8f00fe33f462c5f1b2bbcb723a335b275693d90fd05723595a0825cfb63e0fb2628b3b5b5ddcdfd8710ce4bcf50c
|
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/README.md
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<h1 align="center">JRRToken</h1>
|
|
6
|
-
<h2 align="center">
|
|
6
|
+
<h2 align="center">v2.0.0</h2>
|
|
7
7
|
|
|
8
8
|
<p align="center">(Just Ruby, Rust, & Tokens)</p>
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
12
|
-
JRRToken provides a high-performance, native Ruby interface
|
|
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', '~>
|
|
25
|
+
`gem 'j_r_r_token', '~> 2.0'`
|
|
26
26
|
|
|
27
27
|
#### Command Line
|
|
28
|
-
`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).
|
|
29
31
|
|
|
30
32
|
## Use
|
|
31
33
|
|
|
32
|
-
### 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
|
+
|
|
33
68
|
```Ruby
|
|
34
|
-
|
|
69
|
+
tok.count("<|endoftext|>") # => 7
|
|
70
|
+
tok.count("<|endoftext|>", special_tokens: :allow) # => 1
|
|
35
71
|
```
|
|
36
72
|
|
|
37
|
-
###
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
-
|
|
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.
|
|
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.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
data/lib/j_r_r_token/version.rb
CHANGED
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
|
-
|
|
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
|
-
#
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
|
26
|
-
# @param
|
|
27
|
-
# @return [
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
5
|
-
|
|
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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|