Class: RubyLLM::Toolbox::Truncator
- Inherits:
-
Object
- Object
- RubyLLM::Toolbox::Truncator
- Defined in:
- lib/ruby_llm/toolbox/truncator.rb
Overview
Token-budgets a string so a single tool result can never blow up the context window. Keeps the head and the tail (the two ends an agent most often needs) and elides the middle. Counting goes through ruby_llm-tokenizer; if no tokenizer backend is available for the model, it falls back to a ~4-chars-per-token heuristic so a tool never crashes just because a tokenizer gem isn’t installed.
Constant Summary collapse
- MARKER_RESERVE =
tokens held back for the elision marker
16
Instance Method Summary collapse
- #call(text) ⇒ Object
-
#initialize(model:, max_tokens:) ⇒ Truncator
constructor
A new instance of Truncator.
Constructor Details
#initialize(model:, max_tokens:) ⇒ Truncator
Returns a new instance of Truncator.
16 17 18 19 |
# File 'lib/ruby_llm/toolbox/truncator.rb', line 16 def initialize(model:, max_tokens:) @model = model @max_tokens = [max_tokens.to_i, 1].max end |
Instance Method Details
#call(text) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/ruby_llm/toolbox/truncator.rb', line 21 def call(text) text = text.to_s total = count(text) return text if total <= @max_tokens budget = [@max_tokens - MARKER_RESERVE, 2].max head_budget = (budget * 0.6).floor tail_budget = budget - head_budget head = take(text, head_budget, from: :head) tail = take(text, tail_budget, from: :tail) cut = total - count(head) - count(tail) "#{head}\n\n…[truncated ~#{cut} tokens]…\n\n#{tail}" end |