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
- #resolved_context_window ⇒ Object
- #strip_leading_thinking_block(text) ⇒ Object
- #strip_thinking_from_history(messages) ⇒ Object
- #tool_result_message?(msg) ⇒ Boolean
- #trim_oversized_tool_results(messages) ⇒ Object
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 half = .size / 2 .last(half) end |
#empty_assistant_message?(msg) ⇒ Boolean
198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 198 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
187 188 189 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 187 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 |
#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
150 151 152 153 154 155 156 157 158 159 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 150 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
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 111 def strip_thinking_from_history() before_tokens = ContextAccounting.() preserve_after = () stripped_count = 0 result = .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 stripped_count += 1 msg.merge(content: cleaned) end 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 |
#tool_result_message?(msg) ⇒ Boolean
191 192 193 194 195 196 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 191 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
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 161 def trim_oversized_tool_results() max_chars = Legion::Settings[:llm][:tool_result_max_dispatch_chars].to_i return unless max_chars.positive? preserve_after = () trimmed_count = 0 result = .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 trimmed_count += 1 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 if trimmed_count.positive? log.info "[llm][executor] action=trim_tool_results request_id=#{@request.id} trimmed=#{trimmed_count} " \ "max_chars=#{max_chars} preserved_after=#{preserve_after}" end result end |