ruby_llm-tokenizer 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9c7e5f2afe7b48ff4ad5185afee11b931f499c52777ee2873e28ea232880aa72
4
+ data.tar.gz: 4609b223108101ac0cabd6f3fb5b9d757f95bf2e6501fe00b7d749670aa74987
5
+ SHA512:
6
+ metadata.gz: 425438a6b8b8e1c2f53b79ae81bcc5b1a4eed6fcf8d9200ca0be5e17241f8d87d1e15c5cd37b2869c9fee4caa859df59e522b570c0a9f66ff241a93fa20821f2
7
+ data.tar.gz: a96c74f1f8619bbd8cbf1a923d19d1ea576c0cf0ec2751befa1982502a38765e1dc805128ad5957a088ebae935d96209bb6af995eee5f890b69fc20c004c6287
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-06-05
4
+
5
+ - Initial release.
6
+ - `RubyLLM::Tokenizer.count`, `.analyze`, `.truncate` covering OpenAI (tiktoken)
7
+ and open-weight (Hugging Face `tokenizers`) model families.
8
+ - `RubyLLM::Tokenizer.truncate` accepts plain strings and stream-like `Enumerable`
9
+ inputs (for example `File.foreach(...)`) for exact token-aware truncation.
10
+ - `truncate` validates `max_tokens` explicitly and raises `ArgumentError` for
11
+ non-integer or negative values.
12
+ - Data-driven model registry (`lib/ruby_llm/tokenizer/models.yml`) with runtime
13
+ `.register` for custom patterns.
14
+ - Opt-in approximate tokenizer for Anthropic Claude via
15
+ `RubyLLM::Tokenizer.enable_claude_approximation!`.
16
+ - GitHub Actions CI workflow (`.github/workflows/ci.yml`) — runs RSpec on Ruby 3.1–3.4
17
+ for every push and pull request; includes an enforced RuboCop lint step.
18
+ - CI badge in README.
19
+ - README now documents that `HUGGING_FACE_HUB_TOKEN` is accepted as an alternative to
20
+ `HF_TOKEN` for Hugging Face gated repository access.
21
+ - Hugging Face tokenizers fetched from the Hub are persisted under `cache_dir` for
22
+ later offline reuse.
23
+
24
+
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Sal Scotto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # ruby_llm-tokenizer
2
+
3
+ [![CI](https://github.com/washu/ruby_llm-tokenizer/actions/workflows/ci.yml/badge.svg)](https://github.com/washu/ruby_llm-tokenizer/actions/workflows/ci.yml)
4
+ [![Gem Version](https://badge.fury.io/rb/ruby_llm-tokenizer.svg)](https://rubygems.org/gems/ruby_llm-tokenizer)
5
+
6
+ Local, model-aware token counting for [ruby_llm](https://github.com/crmne/ruby_llm).
7
+ A pure-Ruby facade over Hugging Face [`tokenizers`](https://github.com/ankane/tokenizers-ruby) and OpenAI [`tiktoken_ruby`](https://github.com/IAPark/tiktoken_ruby) that maps model identifiers (`gpt-4o`, `llama-3`, `mistral`, ...) to the correct tokenizer and exposes a small API for counting, analyzing, and truncating text against a model's context window — without making an LLM API call.
8
+ No Rust toolchain required: cross-compiled binaries are inherited from the upstream gems.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ bundle add ruby_llm-tokenizer
14
+ ```
15
+
16
+ Or:
17
+
18
+ ```bash
19
+ gem install ruby_llm-tokenizer
20
+ ```
21
+
22
+ Requires Ruby >= 3.1.
23
+
24
+ ## Usage
25
+
26
+ ```ruby
27
+ require "ruby_llm/tokenizer"
28
+
29
+ # Count tokens
30
+ RubyLLM::Tokenizer.count("Hello, world!", model: "gpt-4o")
31
+ # => 4
32
+
33
+ # Detailed breakdown
34
+ analysis = RubyLLM::Tokenizer.analyze("Hello, world!", model: "gpt-4o")
35
+ analysis.ids # => [13225, 11, 2375, 0]
36
+ analysis.tokens # => ["Hello", ",", " world", "!"]
37
+ analysis.count # => 4
38
+ analysis.model # => "tiktoken:o200k_base"
39
+
40
+ # Truncate to fit a context window
41
+ RubyLLM::Tokenizer.truncate(
42
+ huge_log,
43
+ max_tokens: 30_000,
44
+ model: "gpt-4o",
45
+ overflow: :truncate_left # drop oldest content; default is :truncate_right
46
+ )
47
+
48
+ # Stream/Enumerable inputs work too
49
+ RubyLLM::Tokenizer.truncate(
50
+ File.foreach("huge_log.txt"),
51
+ max_tokens: 30_000,
52
+ model: "gpt-4o",
53
+ overflow: :truncate_left
54
+ )
55
+ ```
56
+
57
+ For stream-like inputs, `truncate` accepts any `Enumerable` of chunks (for example
58
+ `File.foreach(...)`) and incrementally applies the same exact token-limit semantics as
59
+ string input. This avoids requiring callers to materialize the original source text up
60
+ front and avoids some duplicate tokenization work during truncation, though the
61
+ implementation may still retain the kept portion in memory.
62
+
63
+ ## Supported model families (built-in)
64
+
65
+ | Family | Backend | Encoding / Repo |
66
+ |-----------------------------------------------------------|-----------------|------------------------------------------|
67
+ | All OpenAI families (gpt-3.5/4/4o/4.1/4.5/5, o-series, gpt-oss, embeddings, ft:, legacy) | `tiktoken_auto` | resolved via `Tiktoken.encoding_for_model` |
68
+ | `llama-3` / `meta-llama` | `hugging_face` | `meta-llama/Meta-Llama-3-8B-Instruct` |
69
+ | `mistral` / `mixtral` | `hugging_face` | `mistralai/Mistral-7B-Instruct-v0.2` |
70
+ | `deepseek` | `hugging_face` | `deepseek-ai/DeepSeek-V2` |
71
+ | `qwen` | `hugging_face` | `Qwen/Qwen2.5-7B-Instruct` |
72
+
73
+ OpenAI model resolution is delegated to `tiktoken_ruby` — new OpenAI models become available on `bundle update tiktoken_ruby` with no change to this gem. Override a specific model at runtime with `RubyLLM::Tokenizer.register(...)`.
74
+
75
+ OpenAI encodings are bundled with `tiktoken_ruby` (no network needed). Hugging Face `tokenizer.json` files are downloaded lazily on first use, then persisted under `cache_dir` for later offline reuse. Some HF repos (Llama 3, recent Mistral) are gated and require an HF token — see [Configuration](#configuration).
76
+
77
+ ## Claude / Anthropic
78
+
79
+ Anthropic does not publish Claude's tokenizer. By default, `model: "claude-..."` raises `UnknownModelError`.
80
+
81
+ You can opt in to an approximate count (uses `o200k_base` as a stand-in; typically within 5–15% of the real number):
82
+
83
+ ```ruby
84
+ RubyLLM::Tokenizer.enable_claude_approximation!
85
+ RubyLLM::Tokenizer.count("Hello", model: "claude-3-5-sonnet-20241022")
86
+ # warns once, then returns an approximate Integer
87
+ ```
88
+
89
+ Do not use approximate counts to enforce hard context limits — leave headroom, or call Anthropic's `count_tokens` endpoint for exact numbers.
90
+
91
+ ## Registering custom models
92
+
93
+ ```ruby
94
+ RubyLLM::Tokenizer.register(
95
+ match: /^my-finetuned-llama/,
96
+ backend: :hugging_face,
97
+ repo: "my-org/my-finetuned-llama-tokenizer"
98
+ )
99
+
100
+ RubyLLM::Tokenizer.register(
101
+ match: "gpt-4o-2024-internal",
102
+ backend: :tiktoken,
103
+ encoding: "o200k_base"
104
+ )
105
+ ```
106
+
107
+ User registrations take precedence over built-ins.
108
+
109
+ ## Configuration
110
+
111
+ ```ruby
112
+ RubyLLM::Tokenizer.configure do |c|
113
+ c.cache_dir = Pathname("/tmp/ruby_llm_tokenizer") # default: ~/.cache/ruby_llm/tokenizer; stores downloaded HF tokenizers
114
+ c.offline = false # if true, never hits the HF Hub
115
+ c.hf_token = ENV["HF_TOKEN"] # also reads HUGGING_FACE_HUB_TOKEN
116
+ c.approximate_warn = true # warn on first approximate use
117
+ end
118
+ ```
119
+
120
+ ## Errors
121
+
122
+ | Class | Raised when |
123
+ |------------------------------------------------|-------------------------------------------------------------|
124
+ | `RubyLLM::Tokenizer::UnknownModelError` | No registered pattern matches the given model id |
125
+ | `RubyLLM::Tokenizer::BackendError` | Underlying tokenizer engine failed to load or encode |
126
+ | `RubyLLM::Tokenizer::CacheError` | `offline: true` and the local tokenizer.json is missing |
127
+ | `RubyLLM::Tokenizer::ContextExceededError` | Raised when a token count exceeds a defined limit (reserved for future use) |
128
+
129
+
130
+ ## Development
131
+
132
+ ```bash
133
+ bin/setup
134
+ bundle exec rspec
135
+ bin/console
136
+ ```
137
+
138
+ ## Releasing
139
+
140
+ ```bash
141
+ SKIP_PUSH=1 ./build_release.sh
142
+ ./build_release.sh
143
+ GEM_HOST_OTP=123456 ./build_release.sh
144
+ ```
145
+
146
+ - `SKIP_PUSH=1` builds the gem and verifies the release artifact without publishing.
147
+ - Running `./build_release.sh` normally builds and pushes, letting `gem push` prompt for MFA.
148
+ - `GEM_HOST_OTP=...` passes an explicit RubyGems OTP when you want a non-interactive push.
149
+
150
+ ## Contributing
151
+
152
+ Bug reports and pull requests are welcome on GitHub at https://github.com/washu/ruby_llm-tokenizer.
153
+
154
+ ## License
155
+
156
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLLM
4
+ module Tokenizer
5
+ Analysis = Struct.new(:tokens, :ids, :model, keyword_init: true) do
6
+ def count
7
+ ids.size
8
+ end
9
+
10
+ def to_h
11
+ { tokens: tokens, ids: ids, model: model, count: count }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tiktoken"
4
+
5
+ module RubyLLM
6
+ module Tokenizer
7
+ module Backend
8
+ # Approximate tokenizer for models with no published tokenizer (notably
9
+ # Anthropic Claude). Wraps a tiktoken encoding as a stand-in. Token counts
10
+ # are typically within ~5-15% of the model's true count and should not be
11
+ # used for hard limits.
12
+ class Approximate < Tiktoken
13
+ def initialize(encoding: "o200k_base")
14
+ super
15
+ @warned = false
16
+ @warn_mutex = Mutex.new
17
+ end
18
+
19
+ def encode(text)
20
+ warn_once
21
+ super
22
+ end
23
+
24
+ def identifier
25
+ "approximate:#{encoding_name}"
26
+ end
27
+
28
+ private
29
+
30
+ def warn_once
31
+ return if @warned
32
+ return unless RubyLLM::Tokenizer.configuration.approximate_warn
33
+
34
+ @warn_mutex.synchronize do
35
+ return if @warned
36
+
37
+ Kernel.warn(warning_message)
38
+ @warned = true
39
+ end
40
+ end
41
+
42
+ def warning_message
43
+ "[ruby_llm-tokenizer] Using approximate tokenizer (#{encoding_name}). " \
44
+ "Counts may differ from the model's true tokenizer by ~5-15%. " \
45
+ "Silence with: RubyLLM::Tokenizer.configure { |c| c.approximate_warn = false }"
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "tokenizers"
5
+ require_relative "../backend"
6
+
7
+ module RubyLLM
8
+ module Tokenizer
9
+ module Backend
10
+ class HuggingFace < Base
11
+ attr_reader :repo, :revision
12
+
13
+ def initialize(repo:, revision: nil)
14
+ super()
15
+ @repo = repo
16
+ @revision = revision
17
+ @tokenizer = load_tokenizer
18
+ end
19
+
20
+ def encode(text)
21
+ @tokenizer.encode(text.to_s).ids
22
+ end
23
+
24
+ def decode(ids)
25
+ @tokenizer.decode(Array(ids), skip_special_tokens: true)
26
+ end
27
+
28
+ def analyze(text)
29
+ encoding = @tokenizer.encode(text.to_s)
30
+ Analysis.new(tokens: encoding.tokens, ids: encoding.ids, model: identifier)
31
+ end
32
+
33
+ def identifier
34
+ "hugging_face:#{repo}#{"@#{revision}" if revision}"
35
+ end
36
+
37
+ private
38
+
39
+ def load_tokenizer
40
+ config = RubyLLM::Tokenizer.configuration
41
+ config.offline ? load_from_disk(config) : load_from_hub(config)
42
+ rescue CacheError
43
+ raise
44
+ rescue StandardError => e
45
+ raise BackendError, "Failed to load Hugging Face tokenizer #{@repo.inspect}: #{e.message}"
46
+ end
47
+
48
+ def load_from_disk(config)
49
+ path = local_tokenizer_path(config)
50
+ raise CacheError, "Tokenizer not cached at #{path}" unless File.exist?(path)
51
+
52
+ ::Tokenizers.from_file(path.to_s)
53
+ end
54
+
55
+ def load_from_hub(config)
56
+ args = { auth_token: config.hf_token }.compact
57
+ args[:revision] = @revision if @revision
58
+ tokenizer = ::Tokenizers.from_pretrained(@repo, **args)
59
+ persist_to_cache(tokenizer, config)
60
+ tokenizer
61
+ end
62
+
63
+ def local_tokenizer_path(config)
64
+ config.cache_dir.join(@repo.tr("/", "-"), "tokenizer.json")
65
+ end
66
+
67
+ def persist_to_cache(tokenizer, config)
68
+ path = local_tokenizer_path(config)
69
+ FileUtils.mkdir_p(path.dirname)
70
+ tokenizer.save(path.to_s)
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tiktoken_ruby"
4
+ require_relative "../backend"
5
+
6
+ module RubyLLM
7
+ module Tokenizer
8
+ module Backend
9
+ class Tiktoken < Base
10
+ attr_reader :encoding_name
11
+
12
+ def initialize(encoding:)
13
+ super()
14
+ @encoding_name = encoding.to_s
15
+ @encoding = ::Tiktoken.get_encoding(@encoding_name)
16
+ raise BackendError, "Unknown tiktoken encoding: #{encoding.inspect}" if @encoding.nil?
17
+ rescue StandardError => e
18
+ raise BackendError, "Failed to load tiktoken encoding #{encoding.inspect}: #{e.message}"
19
+ end
20
+
21
+ def encode(text)
22
+ @encoding.encode(text.to_s)
23
+ end
24
+
25
+ def decode(ids)
26
+ @encoding.decode(Array(ids))
27
+ end
28
+
29
+ def identifier
30
+ "tiktoken:#{encoding_name}"
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "analysis"
4
+ require_relative "errors"
5
+
6
+ module RubyLLM
7
+ module Tokenizer
8
+ module Backend
9
+ class Base
10
+ def encode(_text)
11
+ raise NotImplementedError, "#{self.class}#encode must be implemented"
12
+ end
13
+
14
+ def decode(_ids)
15
+ raise NotImplementedError, "#{self.class}#decode must be implemented"
16
+ end
17
+
18
+ def count(text)
19
+ encode(text).size
20
+ end
21
+
22
+ def analyze(text)
23
+ ids = encode(text)
24
+ Analysis.new(tokens: ids.map { |id| decode_single(id) }, ids: ids, model: identifier)
25
+ end
26
+
27
+ def truncate(text, max_tokens:, overflow: :truncate_right)
28
+ validate_max_tokens!(max_tokens)
29
+ validate_overflow!(overflow)
30
+ return "" if max_tokens.zero?
31
+
32
+ if text.respond_to?(:to_str) || !text.respond_to?(:each)
33
+ truncate_string(text.to_s, max_tokens: max_tokens, overflow: overflow)
34
+ else
35
+ truncate_stream(text, max_tokens: max_tokens, overflow: overflow)
36
+ end
37
+ end
38
+
39
+ def identifier
40
+ self.class.name.split("::").last.downcase
41
+ end
42
+
43
+ private
44
+
45
+ def truncate_string(text, max_tokens:, overflow:)
46
+ ids = encode(text)
47
+ return text if ids.size <= max_tokens
48
+
49
+ decode(kept_ids(ids, max_tokens: max_tokens, overflow: overflow))
50
+ end
51
+
52
+ def truncate_stream(stream, max_tokens:, overflow:)
53
+ if overflow == :truncate_right
54
+ truncate_stream_right(stream, max_tokens)
55
+ else
56
+ truncate_stream_left(stream, max_tokens)
57
+ end
58
+ end
59
+
60
+ def truncate_stream_right(stream, max_tokens)
61
+ buffer = +""
62
+
63
+ each_chunk(stream) do |chunk|
64
+ buffer << chunk
65
+ ids = encode(buffer)
66
+ return decode(kept_ids(ids, max_tokens: max_tokens, overflow: :truncate_right)) if ids.size > max_tokens
67
+ end
68
+
69
+ buffer
70
+ end
71
+
72
+ def truncate_stream_left(stream, max_tokens)
73
+ buffer = +""
74
+
75
+ each_chunk(stream) do |chunk|
76
+ buffer << chunk
77
+ ids = encode(buffer)
78
+ buffer = decode(kept_ids(ids, max_tokens: max_tokens, overflow: :truncate_left)) if ids.size > max_tokens
79
+ end
80
+
81
+ buffer
82
+ end
83
+
84
+ def kept_ids(ids, max_tokens:, overflow:)
85
+ overflow == :truncate_right ? ids.first(max_tokens) : ids.last(max_tokens)
86
+ end
87
+
88
+ def each_chunk(stream)
89
+ stream.each do |chunk|
90
+ next if chunk.nil?
91
+
92
+ piece = chunk.to_s
93
+ next if piece.empty?
94
+
95
+ yield piece
96
+ end
97
+ end
98
+
99
+ def validate_max_tokens!(max_tokens)
100
+ raise ArgumentError, "max_tokens must be an Integer" unless max_tokens.is_a?(Integer)
101
+ raise ArgumentError, "max_tokens must be >= 0" if max_tokens.negative?
102
+ end
103
+
104
+ def validate_overflow!(overflow)
105
+ return if %i[truncate_right truncate_left].include?(overflow)
106
+
107
+ raise ArgumentError, "Unknown overflow strategy: #{overflow.inspect}"
108
+ end
109
+
110
+ def decode_single(id)
111
+ decode([id])
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+
5
+ module RubyLLM
6
+ module Tokenizer
7
+ class Configuration
8
+ attr_accessor :cache_dir, :offline, :hf_token, :approximate_warn
9
+
10
+ def initialize
11
+ @cache_dir = default_cache_dir
12
+ @offline = false
13
+ @hf_token = ENV["HF_TOKEN"] || ENV.fetch("HUGGING_FACE_HUB_TOKEN", nil)
14
+ @approximate_warn = true
15
+ end
16
+
17
+ def default_cache_dir
18
+ base = ENV["XDG_CACHE_HOME"] || File.join(Dir.home, ".cache")
19
+ Pathname.new(File.join(base, "ruby_llm", "tokenizer"))
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLLM
4
+ module Tokenizer
5
+ class Error < StandardError; end
6
+
7
+ class UnknownModelError < Error; end
8
+
9
+ class BackendError < Error; end
10
+
11
+ class CacheError < Error; end
12
+
13
+ class ContextExceededError < Error
14
+ attr_reader :token_count, :limit, :model
15
+
16
+ def initialize(message = nil, token_count: nil, limit: nil, model: nil)
17
+ super(message)
18
+ @token_count = token_count
19
+ @limit = limit
20
+ @model = model
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,43 @@
1
+ # Built-in model -> backend mapping. First match wins.
2
+ # Users can override or extend via RubyLLM::Tokenizer.register(...).
3
+ #
4
+ # `match` is either a literal string (exact match) or `/regex/flags` (parsed
5
+ # as a Regexp). Supported flags: i, m, x.
6
+
7
+ # --- OpenAI: delegated to tiktoken_ruby's built-in model->encoding table ------
8
+ # This covers every OpenAI model identifier tiktoken_ruby knows about:
9
+ # - GPT family: gpt-3.5, gpt-4, gpt-4o, gpt-4.1, gpt-4.5, gpt-5, gpt-oss-*,
10
+ # chatgpt-4o, Azure-style gpt-35-turbo
11
+ # - o-series: o1, o3, o4-mini (and `-*` suffixed variants)
12
+ # - Embeddings: text-embedding-ada-002, text-embedding-3-{small,large}
13
+ # - Legacy completions: text-davinci-*, davinci/curie/babbage/ada, code-*,
14
+ # davinci-002, babbage-002
15
+ # - Fine-tunes: ft:gpt-*, ft:davinci-002, ft:babbage-002
16
+ # - Codex: codex-mini, code-cushman-*, davinci-codex
17
+ #
18
+ # New OpenAI models become available on `bundle update tiktoken_ruby` — no PR
19
+ # to this file required. Override a specific model at runtime with
20
+ # RubyLLM::Tokenizer.register(...).
21
+
22
+ - match: "/^(gpt-|gpt[0-9]|chatgpt-|o[1-9]|text-|code-|davinci\\b|curie\\b|babbage\\b|ada\\b|ft:|codex-)/"
23
+ backend: tiktoken_auto
24
+
25
+ # --- Open weights: Hugging Face backend (tokenizer.json fetched lazily) -------
26
+ # Some repos below are gated and require HF_TOKEN. Override with
27
+ # RubyLLM::Tokenizer.register(...) if you want a different mirror.
28
+
29
+ - match: "/^(llama-?3|meta-llama)/i"
30
+ backend: hugging_face
31
+ repo: meta-llama/Meta-Llama-3-8B-Instruct
32
+
33
+ - match: "/^(mistral|mixtral)/i"
34
+ backend: hugging_face
35
+ repo: mistralai/Mistral-7B-Instruct-v0.2
36
+
37
+ - match: "/^deepseek/i"
38
+ backend: hugging_face
39
+ repo: deepseek-ai/DeepSeek-V2
40
+
41
+ - match: "/^qwen/i"
42
+ backend: hugging_face
43
+ repo: Qwen/Qwen2.5-7B-Instruct
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require_relative "errors"
5
+ require_relative "backend/tiktoken"
6
+ require_relative "backend/hugging_face"
7
+ require_relative "backend/approximate"
8
+
9
+ module RubyLLM
10
+ module Tokenizer
11
+ class Registry
12
+ Entry = Struct.new(:match, :backend, :options, keyword_init: true) do
13
+ def matches?(model)
14
+ case match
15
+ when Regexp then match.match?(model.to_s)
16
+ when String then match == model.to_s
17
+ else false
18
+ end
19
+ end
20
+ end
21
+
22
+ DEFAULTS_PATH = File.join(File.dirname(__FILE__), "models.yml")
23
+
24
+ def self.load_default
25
+ new.tap { |r| r.load_defaults_from(DEFAULTS_PATH) }
26
+ end
27
+
28
+ def initialize
29
+ @entries = []
30
+ @cache = {}
31
+ end
32
+
33
+ # User registrations take precedence over built-ins.
34
+ def register(match:, backend:, **options)
35
+ @entries.unshift(Entry.new(match: match, backend: backend.to_sym, options: options))
36
+ @cache.clear
37
+ self
38
+ end
39
+
40
+ def resolve(model)
41
+ key = model.to_s
42
+ return @cache[key] if @cache.key?(key)
43
+
44
+ entry = @entries.find { |e| e.matches?(model) }
45
+ @cache[key] = entry && build_backend(entry, key)
46
+ end
47
+
48
+ def entries
49
+ @entries.dup
50
+ end
51
+
52
+ def clear
53
+ @entries.clear
54
+ @cache.clear
55
+ self
56
+ end
57
+
58
+ def load_defaults_from(path)
59
+ data = YAML.load_file(path) || []
60
+ data.each { |entry| @entries.push(build_entry(entry)) }
61
+ @cache.clear
62
+ self
63
+ end
64
+
65
+ def self.parse_match(value)
66
+ if value.is_a?(String) && (md = value.match(%r{\A/(.*)/([imx]*)\z}))
67
+ flags = 0
68
+ flags |= Regexp::IGNORECASE if md[2].include?("i")
69
+ flags |= Regexp::MULTILINE if md[2].include?("m")
70
+ flags |= Regexp::EXTENDED if md[2].include?("x")
71
+ Regexp.new(md[1], flags)
72
+ else
73
+ value
74
+ end
75
+ end
76
+
77
+ private
78
+
79
+ def build_entry(raw)
80
+ Entry.new(
81
+ match: parse_entry_match(raw),
82
+ backend: parse_entry_backend(raw),
83
+ options: entry_options(raw)
84
+ )
85
+ end
86
+
87
+ def entry_options(raw)
88
+ raw.except("match", "backend").transform_keys(&:to_sym)
89
+ end
90
+
91
+ def parse_entry_match(raw)
92
+ match = self.class.parse_match(raw.fetch("match"))
93
+ return match if match.is_a?(String) || match.is_a?(Regexp)
94
+
95
+ raise BackendError, "Invalid model matcher: #{match.inspect}"
96
+ end
97
+
98
+ def parse_entry_backend(raw)
99
+ backend = raw.fetch("backend")
100
+ return backend.to_sym if backend.is_a?(String) || backend.is_a?(Symbol)
101
+
102
+ raise BackendError, "Invalid backend identifier: #{backend.inspect}"
103
+ end
104
+
105
+ def build_backend(entry, model)
106
+ case entry.backend
107
+ when :tiktoken then Backend::Tiktoken.new(**entry.options)
108
+ when :tiktoken_auto then build_tiktoken_auto(model)
109
+ when :hugging_face then Backend::HuggingFace.new(**entry.options)
110
+ when :approximate then Backend::Approximate.new(**entry.options)
111
+ else
112
+ raise BackendError, "Unknown backend: #{entry.backend.inspect}"
113
+ end
114
+ end
115
+
116
+ def build_tiktoken_auto(model)
117
+ enc = ::Tiktoken.encoding_for_model(model)
118
+ if enc.nil?
119
+ raise UnknownModelError,
120
+ "tiktoken_ruby has no encoding mapping for #{model.inspect}. " \
121
+ "Either upgrade tiktoken_ruby or register an explicit mapping with " \
122
+ "RubyLLM::Tokenizer.register(match: #{model.inspect}, backend: :tiktoken, encoding: \"...\")."
123
+ end
124
+
125
+ Backend::Tiktoken.new(encoding: enc.name)
126
+ end
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLLM
4
+ module Tokenizer
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tokenizer/version"
4
+ require_relative "tokenizer/errors"
5
+ require_relative "tokenizer/configuration"
6
+ require_relative "tokenizer/analysis"
7
+ require_relative "tokenizer/registry"
8
+
9
+ module RubyLLM
10
+ module Tokenizer
11
+ class << self
12
+ def count(text, model:)
13
+ backend_for(model).count(text)
14
+ end
15
+
16
+ def analyze(text, model:)
17
+ backend_for(model).analyze(text)
18
+ end
19
+
20
+ def truncate(text, max_tokens:, model:, overflow: :truncate_right)
21
+ backend_for(model).truncate(text, max_tokens: max_tokens, overflow: overflow)
22
+ end
23
+
24
+ def register(match:, backend:, **)
25
+ registry.register(match: match, backend: backend, **)
26
+ end
27
+
28
+ # Opt-in: route any "claude*" model to an approximation backend.
29
+ # Counts are not exact. See Backend::Approximate for caveats.
30
+ def enable_claude_approximation!(encoding: "o200k_base")
31
+ registry.register(match: /^claude/i, backend: :approximate, encoding: encoding)
32
+ end
33
+
34
+ def configure
35
+ yield configuration
36
+ end
37
+
38
+ def configuration
39
+ @configuration ||= Configuration.new
40
+ end
41
+
42
+ def registry
43
+ @registry ||= Registry.load_default
44
+ end
45
+
46
+ def reset!
47
+ @configuration = nil
48
+ @registry = nil
49
+ end
50
+
51
+ private
52
+
53
+ def backend_for(model)
54
+ registry.resolve(model) ||
55
+ raise(UnknownModelError, "No tokenizer configured for model: #{model.inspect}")
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,51 @@
1
+ module RubyLLM
2
+ module Tokenizer
3
+ VERSION: String
4
+
5
+ class Registry
6
+ end
7
+
8
+ class Error < StandardError
9
+ end
10
+
11
+ class UnknownModelError < Error
12
+ end
13
+
14
+ class BackendError < Error
15
+ end
16
+
17
+ class CacheError < Error
18
+ end
19
+
20
+ class ContextExceededError < Error
21
+ attr_reader token_count: Integer?
22
+ attr_reader limit: Integer?
23
+ attr_reader model: String?
24
+ end
25
+
26
+ class Configuration
27
+ attr_accessor cache_dir: untyped
28
+ attr_accessor offline: bool
29
+ attr_accessor hf_token: String?
30
+ attr_accessor approximate_warn: bool
31
+ end
32
+
33
+ class Analysis
34
+ attr_reader tokens: Array[String]
35
+ attr_reader ids: Array[Integer]
36
+ attr_reader model: String
37
+ def count: () -> Integer
38
+ def to_h: () -> Hash[Symbol, untyped]
39
+ end
40
+
41
+ def self.count: (String text, model: String) -> Integer
42
+ def self.analyze: (String text, model: String) -> Analysis
43
+ def self.truncate: ((String | ::Enumerable[untyped]) text, max_tokens: Integer, model: String, ?overflow: Symbol) -> String
44
+ def self.register: (match: Regexp | String, backend: Symbol, **untyped) -> Registry
45
+ def self.enable_claude_approximation!: (?encoding: String) -> Registry
46
+ def self.configure: () { (Configuration) -> void } -> void
47
+ def self.configuration: () -> Configuration
48
+ def self.registry: () -> Registry
49
+ def self.reset!: () -> void
50
+ end
51
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ruby_llm-tokenizer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sal Scotto
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: tiktoken_ruby
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.0.9
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.0.9
26
+ - !ruby/object:Gem::Dependency
27
+ name: tokenizers
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '0.5'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '0.5'
40
+ description: |
41
+ Pure-Ruby facade over Hugging Face `tokenizers` and OpenAI `tiktoken_ruby`
42
+ that maps ruby_llm model identifiers (gpt-4o, llama-3, mistral, ...) to the
43
+ correct tokenizer and exposes a small API for counting, analyzing, and
44
+ truncating text against a model's context window. Includes an opt-in
45
+ approximation backend for models with no published tokenizer (Claude).
46
+ email:
47
+ - sal.scotto@gmail.com
48
+ executables: []
49
+ extensions: []
50
+ extra_rdoc_files: []
51
+ files:
52
+ - ".rspec"
53
+ - CHANGELOG.md
54
+ - CODE_OF_CONDUCT.md
55
+ - LICENSE.txt
56
+ - README.md
57
+ - Rakefile
58
+ - lib/ruby_llm/tokenizer.rb
59
+ - lib/ruby_llm/tokenizer/analysis.rb
60
+ - lib/ruby_llm/tokenizer/backend.rb
61
+ - lib/ruby_llm/tokenizer/backend/approximate.rb
62
+ - lib/ruby_llm/tokenizer/backend/hugging_face.rb
63
+ - lib/ruby_llm/tokenizer/backend/tiktoken.rb
64
+ - lib/ruby_llm/tokenizer/configuration.rb
65
+ - lib/ruby_llm/tokenizer/errors.rb
66
+ - lib/ruby_llm/tokenizer/models.yml
67
+ - lib/ruby_llm/tokenizer/registry.rb
68
+ - lib/ruby_llm/tokenizer/version.rb
69
+ - sig/ruby_llm/tokenizer.rbs
70
+ homepage: https://github.com/washu/ruby_llm-tokenizer
71
+ licenses:
72
+ - MIT
73
+ metadata:
74
+ homepage_uri: https://github.com/washu/ruby_llm-tokenizer
75
+ source_code_uri: https://github.com/washu/ruby_llm-tokenizer/tree/main
76
+ changelog_uri: https://github.com/washu/ruby_llm-tokenizer/blob/main/CHANGELOG.md
77
+ rubygems_mfa_required: 'true'
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: 3.3.0
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubygems_version: 3.6.9
93
+ specification_version: 4
94
+ summary: Local, model-aware token counting for ruby_llm.
95
+ test_files: []