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

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(messages, target_tokens)
  return messages if estimate_message_tokens(messages) <= target_tokens

  filtered = messages.reject do |msg|
    role = (msg[:role] || msg['role']).to_s
    role == 'tool' && (msg[:content] || msg['content']).to_s.length > 500
  end
  messages = 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 messages if estimate_message_tokens(messages) <= target_tokens

  half = messages.size / 2
  messages.last(half)
end

#empty_assistant_message?(msg) ⇒ Boolean

Returns:

  • (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 empty_assistant_message?(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(messages)
  context_window = resolved_context_window
  @context_accounting[:component_status][:context_window] = :observed
  return messages unless context_window&.positive?

  threshold = (context_window * 0.90).to_i
  estimated = estimate_message_tokens(messages)
  return messages 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 = last_user_message_index(messages)
  recent = messages[preserve_after..]
  older = messages[0...preserve_after]

  target_tokens = threshold - estimate_message_tokens(recent)
  compacted = compact_to_fit(older, target_tokens)

  result = compacted + recent
  after_tokens = estimate_message_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] = messages.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:  messages.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=#{messages.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 estimate_message_tokens(messages)
  messages.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 last_user_message_index(messages)
  messages.rindex { |m| (m[:role] || m['role']).to_s == 'user' } || messages.size
end

#native_dispatch_messagesObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/legion/llm/inference/executor/context_window.rb', line 12

def native_dispatch_messages
  messages = apply_conversation_breakpoint(@request.messages)
  rejected = messages.count { |m| empty_assistant_message?(m) }
  if rejected.positive?
    log.warn "[llm][executor] action=strip_empty_assistants request_id=#{@request.id} removed=#{rejected}"
    messages = messages.reject { |m| empty_assistant_message?(m) }
  end
  messages = strip_thinking_from_history(messages)
  messages = trim_oversized_tool_results(messages)
  enforce_context_window(messages)
end

#resolved_context_windowObject



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(messages)
  before_tokens = ContextAccounting.estimate_message_tokens(messages)
  preserve_after = last_user_message_index(messages)
  stripped_count = 0
  result = messages.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.estimate_message_tokens(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:  messages.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

Returns:

  • (Boolean)


175
176
177
178
179
180
# File 'lib/legion/llm/inference/executor/context_window.rb', line 175

def tool_result_message?(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(messages)
  max_chars = Legion::Settings[:llm][:tool_result_max_dispatch_chars].to_i
  return messages unless max_chars.positive?

  preserve_after = last_user_message_index(messages)
  trimmed_count = 0
  result = messages.each_with_index.map do |msg, idx|
    next msg if idx >= preserve_after
    next msg unless tool_result_message?(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