Module: Legion::LLM::Inference::Steps::TriggerMatch

Includes:
Logging, Legion::Logging::Helper
Included in:
Executor
Defined in:
lib/legion/llm/inference/steps/trigger_match.rb

Instance Method Summary collapse

Instance Method Details

#step_trigger_matchObject



14
15
16
17
18
19
20
21
22
23
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/steps/trigger_match.rb', line 14

def step_trigger_match
  start_time = nil
  unless defined?(::Legion::Tools::TriggerIndex)
    log_step_debug(:trigger_match, :skipped, reason: :trigger_index_unavailable)
    return
  end
  if ::Legion::Tools::TriggerIndex.empty?
    log_step_debug(:trigger_match, :skipped, reason: :trigger_index_empty)
    return
  end

  start_time = ::Time.now

  text = extract_recent_text
  word_set = normalize_message_words(text)
  if word_set.empty?
    log_step_debug(:trigger_match, :skipped, reason: :no_words)
    return
  end
  log_step_debug(:trigger_match, :scanning, word_count: word_set.size)

  matched, per_word = ::Legion::Tools::TriggerIndex.match(word_set)
  subtract_always_loaded(matched)
  if matched.empty?
    log_step_debug(:trigger_match, :no_matches)
    return
  end

  limit = trigger_tool_limit
  @triggered_tools = if matched.size <= limit
                       matched.to_a
                     else
                       rank_and_cap(matched, per_word, limit)
                     end

  if @triggered_tools.any?
    names = @triggered_tools.map(&:tool_name)
    @enrichments['tool:trigger_match'] = {
      content:   "#{@triggered_tools.size} tools matched via trigger words",
      data:      { tool_count: @triggered_tools.size, tool_names: names },
      timestamp: ::Time.now
    }
  end

  record_trigger_match_timeline(@triggered_tools.size, start_time)
  log_step_debug(:trigger_match, :matched, matched_count: matched.size, injected_count: @triggered_tools.size, limit: limit)
rescue StandardError => e
  @warnings << "Trigger match error: #{e.message}"
  handle_exception(e, level: :warn, operation: 'llm.pipeline.steps.trigger_match')
  record_trigger_match_timeline(0, start_time)
end