j_r_r_token 1.2.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +51 -0
- data/Cargo.lock +42 -37
- data/README.md +96 -14
- data/ext/j_r_r_token/Cargo.toml +3 -2
- data/ext/j_r_r_token/src/lib.rs +273 -35
- data/j_r_r_token.gemspec +1 -1
- data/lib/j_r_r_token/version.rb +1 -1
- data/lib/j_r_r_token.rb +429 -13
- data/sig/j_r_r_token.rbs +49 -1
- metadata +4 -4
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,4 +1,52 @@
|
|
|
1
1
|
module JRRToken
|
|
2
2
|
VERSION: String
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
type special_tokens_mode = :text | :allow | :raise
|
|
5
|
+
|
|
6
|
+
type message_key = String | Symbol
|
|
7
|
+
type message = Hash[message_key, untyped]
|
|
8
|
+
|
|
9
|
+
class Error < StandardError
|
|
10
|
+
end
|
|
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
|
+
|
|
22
|
+
class Tokenizer
|
|
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
|
|
51
|
+
end
|
|
4
52
|
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: j_r_r_token
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version:
|
|
4
|
+
version: 2.0.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Logan Bresnahan
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: exe
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-
|
|
11
|
+
date: 2026-11-23 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: bundler
|
|
@@ -53,8 +53,8 @@ dependencies:
|
|
|
53
53
|
- !ruby/object:Gem::Version
|
|
54
54
|
version: '0'
|
|
55
55
|
description: JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling
|
|
56
|
-
fast and efficient tokenization for OpenAI models. It supports
|
|
57
|
-
o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base.
|
|
56
|
+
fast and efficient tokenization for OpenAI models. It supports the o200k_harmony,
|
|
57
|
+
o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base encodings.
|
|
58
58
|
email:
|
|
59
59
|
- loganbbres@gmail.com
|
|
60
60
|
executables: []
|