Module: Legion::LLM::Inference::Executor::ContextWindow
- Included in:
- Legion::LLM::Inference::Executor
- Defined in:
- lib/legion/llm/inference/executor/context_window.rb
Overview
ContextWindow methods extracted from Executor verbatim (P4b §1.5, refactor-under-green). Functional message-list transformations: empty/thinking/tool-result trimming and context-window-aware compaction. Operates on the messages argument; reads
Instance Method Summary collapse
- #compact_to_fit(messages, target_tokens) ⇒ Object
- #empty_assistant_message?(msg) ⇒ Boolean
- #enforce_context_window(messages) ⇒ Object
- #estimate_message_tokens(messages) ⇒ Object
- #estimate_tool_token_budget ⇒ Object
- #last_user_message_index(messages) ⇒ Object
- #native_dispatch_messages ⇒ Object
-
#reduce_messages_for_dispatch(messages) ⇒ Object
Lane-INDEPENDENT reduction applied before dispatch: empty-assistant prune + leading-thinking strip + oversized-tool-result trim.
- #resolved_context_window ⇒ Object
- #strip_leading_thinking_block(text) ⇒ Object
- #strip_thinking_from_history(messages) ⇒ Object
-
#strip_thinking_pure(messages) ⇒ Object
Pure leading-thinking strip.
- #tool_result_message?(msg) ⇒ Boolean
- #trim_oversized_tool_results(messages) ⇒ Object
-
#trim_oversized_tool_results_pure(messages) ⇒ Object
Pure oversized-tool-result trim.
Instance Method Details
#compact_to_fit(messages, target_tokens) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 69 def compact_to_fit(, target_tokens) return if () <= target_tokens filtered = .reject do |msg| role = (msg[:role] || msg['role']).to_s role == 'tool' && (msg[:content] || msg['content']).to_s.length > 500 end = filtered.map do |msg| role = (msg[:role] || msg['role']).to_s next msg unless role == 'tool' content = (msg[:content] || msg['content']).to_s content.length > 200 ? msg.merge(content: "#{content[0, 200]}\n[compacted]") : msg end return if () <= target_tokens = .last(.size / 2) while .size > 2 && () > target_tokens end |
#empty_assistant_message?(msg) ⇒ Boolean
219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 219 def (msg) return false unless msg.is_a?(Hash) return false unless (msg[:role] || msg['role']).to_s == 'assistant' content = msg[:content] || msg['content'] has_content = content.is_a?(String) ? !content.strip.empty? : !content.nil? return false if has_content tool_calls = msg[:tool_calls] || msg['tool_calls'] return false if tool_calls.is_a?(Array) && tool_calls.any? true end |
#enforce_context_window(messages) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 24 def enforce_context_window() context_window = resolved_context_window @context_accounting[:component_status][:context_window] = :observed return unless context_window&.positive? threshold = (context_window * Legion::Settings[:llm][:context_curation][:context_window_threshold]).to_i tool_budget = estimate_tool_token_budget = threshold - tool_budget estimated = () return if estimated <= log.warn "[llm][executor] action=context_compaction request_id=#{@request.id} " \ "estimated_tokens=#{estimated} context_window=#{context_window} " \ "threshold=#{threshold} tool_budget=#{tool_budget} available=#{}" preserve_after = () recent = [preserve_after..] older = [0...preserve_after] target_tokens = - (recent) compacted = compact_to_fit(older, target_tokens) result = compacted + recent after_tokens = (result) saved = [estimated - after_tokens, 0].max @context_accounting[:tokens][:context_window_saved_estimated_tokens] += saved @context_accounting[:counts][:context_window_message_count_before] = .size @context_accounting[:counts][:context_window_message_count_after] = result.size @context_accounting[:events] << ContextAccounting.event( event_type: :context_window_enforcement, component: :context_window, before_tokens: estimated, after_tokens: after_tokens, before_count: .size, after_count: result.size, metadata: { context_window: context_window, threshold: threshold } ) log.info "[llm][executor] action=context_compaction_complete request_id=#{@request.id} " \ "before=#{.size} after=#{result.size} " \ "tokens_before=#{estimated} tokens_after=#{after_tokens}" result end |
#estimate_message_tokens(messages) ⇒ Object
96 97 98 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 96 def () .sum { |m| ((m[:content] || m['content']).to_s.length / 4.0).ceil } end |
#estimate_tool_token_budget ⇒ Object
100 101 102 103 104 105 106 107 108 109 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 100 def estimate_tool_token_budget tools = @request.tools return 0 if tools.nil? || tools.empty? tool_list = tools.is_a?(Hash) ? tools.values : Array(tools) tool_list.sum do |tool| json_repr = tool.respond_to?(:to_h) ? Legion::JSON.dump(tool.to_h) : tool.to_s (json_repr.length / 3.5).ceil end end |
#last_user_message_index(messages) ⇒ Object
208 209 210 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 208 def () .rindex { |m| (m[:role] || m['role']).to_s == 'user' } || .size end |
#native_dispatch_messages ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 12 def = apply_conversation_breakpoint(@request.) rejected = .count { |m| (m) } if rejected.positive? log.warn "[llm][executor] action=strip_empty_assistants request_id=#{@request.id} removed=#{rejected}" = .reject { |m| (m) } end = strip_thinking_from_history() = trim_oversized_tool_results() enforce_context_window() end |
#reduce_messages_for_dispatch(messages) ⇒ Object
Lane-INDEPENDENT reduction applied before dispatch: empty-assistant prune + leading-thinking strip + oversized-tool-result trim. PURE — no call it to measure exactly what native_dispatch_messages will send (minus the lane-dependent enforce_context_window compaction, which is correctly excluded from routing since it depends on the chosen lane).
117 118 119 120 121 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 117 def () msgs = Array().reject { |m| (m) } msgs = strip_thinking_pure(msgs) trim_oversized_tool_results_pure(msgs) end |
#resolved_context_window ⇒ Object
90 91 92 93 94 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 90 def resolved_context_window @resolved_offering_metadata&.dig(:limits, :context_window) || @resolved_offering_metadata&.dig(:context_window) || @resolved_offering_metadata&.dig('limits', 'context_window') end |
#strip_leading_thinking_block(text) ⇒ Object
167 168 169 170 171 172 173 174 175 176 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 167 def strip_leading_thinking_block(text) result = text.lstrip THINKING_TAG_PAIRS.each do |open_tag, close_tag| next unless result.start_with?(open_tag) close_idx = result.index(close_tag, open_tag.length) return close_idx ? result[(close_idx + close_tag.length)..].lstrip : '' end text end |
#strip_thinking_from_history(messages) ⇒ Object
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 141 def strip_thinking_from_history() before_tokens = ContextAccounting.() result = strip_thinking_pure() stripped_count = .zip(result).count { |before, after| before != after } after_tokens = ContextAccounting.(result) saved = [before_tokens - after_tokens, 0].max @context_accounting[:component_status][:thinking_strip] = :observed if saved.positive? @context_accounting[:tokens][:stripped_thinking_estimated_tokens] += saved @context_accounting[:counts][:stripped_thinking_message_count] += stripped_count @context_accounting[:events] << ContextAccounting.event( event_type: :thinking_stripped, component: :stripped_thinking, before_tokens: before_tokens, after_tokens: after_tokens, before_count: .size, after_count: result.size, metadata: { stripped_count: stripped_count } ) end log.info "[llm][executor] action=strip_thinking_history request_id=#{@request.id} stripped=#{stripped_count}" if stripped_count.positive? result end |
#strip_thinking_pure(messages) ⇒ Object
Pure leading-thinking strip. Shared by strip_thinking_from_history (which adds accounting) and reduce_messages_for_dispatch.
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 125 def strip_thinking_pure() preserve_after = () .each_with_index.map do |msg, idx| next msg if idx >= preserve_after next msg unless (msg[:role] || msg['role']).to_s == 'assistant' content = msg[:content] || msg['content'] next msg unless content.is_a?(String) cleaned = strip_leading_thinking_block(content) next msg if cleaned == content msg.merge(content: cleaned) end end |
#tool_result_message?(msg) ⇒ Boolean
212 213 214 215 216 217 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 212 def (msg) return false unless msg.is_a?(Hash) role = (msg[:role] || msg['role']).to_s role == 'tool' || msg.key?(:tool_call_id) || msg.key?('tool_call_id') end |
#trim_oversized_tool_results(messages) ⇒ Object
198 199 200 201 202 203 204 205 206 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 198 def trim_oversized_tool_results() result = trim_oversized_tool_results_pure() trimmed_count = .zip(result).count { |before, after| before != after } if trimmed_count.positive? log.info "[llm][executor] action=trim_tool_results request_id=#{@request.id} trimmed=#{trimmed_count} " \ "max_chars=#{Legion::Settings[:llm][:tool_result_max_dispatch_chars].to_i}" end result end |
#trim_oversized_tool_results_pure(messages) ⇒ Object
Pure oversized-tool-result trim. Shared by trim_oversized_tool_results (which adds logging) and reduce_messages_for_dispatch.
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 180 def trim_oversized_tool_results_pure() max_chars = Legion::Settings[:llm][:tool_result_max_dispatch_chars].to_i return unless max_chars.positive? preserve_after = () .each_with_index.map do |msg, idx| next msg if idx >= preserve_after next msg unless (msg) content = msg[:content] || msg['content'] next msg unless content.is_a?(String) && content.length > max_chars msg.merge(content: "#{content[0, max_chars]}\n\n[TRUNCATED: showing first #{max_chars} of #{content.length} chars. " \ 'If you need more content, make multiple smaller targeted requests ' \ '(e.g. read specific line ranges, grep for specific patterns, or request smaller sections).]') end end |