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
- #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
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 66 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
182 183 184 185 186 187 188 189 190 191 192 193 194 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 182 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 |
# 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 * 0.90).to_i estimated = () return if estimated <= threshold log.warn "[llm][executor] action=context_compaction request_id=#{@request.id} " \ "estimated_tokens=#{estimated} context_window=#{context_window} threshold=#{threshold}" preserve_after = () recent = [preserve_after..] older = [0...preserve_after] target_tokens = threshold - (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
93 94 95 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 93 def () .sum { |m| ((m[:content] || m['content']).to_s.length / 4.0).ceil } end |
#last_user_message_index(messages) ⇒ Object
171 172 173 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 171 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
87 88 89 90 91 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 87 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
136 137 138 139 140 141 142 143 144 145 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 136 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
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 97 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
175 176 177 178 179 180 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 175 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
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/legion/llm/inference/executor/context_window.rb', line 147 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[truncated — #{content.length} chars total]") 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 |