Module: Legion::LLM::Fleet::Handler

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/fleet/handler.rb

Class Method Summary collapse

Class Method Details

.availability_method_for(payload) ⇒ Object



158
159
160
161
162
163
164
165
166
167
# File 'lib/legion/llm/fleet/handler.rb', line 158

def availability_method_for(payload)
  case payload[:request_type]&.to_s
  when 'structured'
    :structured_direct
  when 'embed'
    :embed_direct
  else
    :chat_direct
  end
end

.build_response(correlation_id, response) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/legion/llm/fleet/handler.rb', line 72

def build_response(correlation_id, response)
  {
    correlation_id:  correlation_id,
    success:         extract_success(response),
    error:           extract_error(response),
    response:        response,
    input_tokens:    extract_token(response, :input_tokens),
    output_tokens:   extract_token(response, :output_tokens),
    thinking_tokens: extract_token(response, :thinking_tokens),
    provider:        extract_field(response, :provider),
    model_id:        extract_field(response, :model)
  }.compact
end

.call_local_llm(payload) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/legion/llm/fleet/handler.rb', line 53

def call_local_llm(payload)
  return unavailable_response unless llm_available_for?(payload)

  case payload[:request_type]&.to_s
  when 'structured'
    Legion::LLM.structured_direct(
      messages: payload[:messages],
      schema:   payload[:schema],
      model:    payload[:model],
      provider: payload[:provider]
    )
  when 'embed'
    text = payload[:text] || extract_terminal_content(payload[:messages])
    Legion::LLM.embed_direct(text, model: payload[:model], provider: payload[:provider])
  else
    execute_chat_request(payload)
  end
end

.execute_chat_request(payload) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/legion/llm/fleet/handler.rb', line 173

def execute_chat_request(payload)
  if payload[:message]
    return Legion::LLM.chat_direct(
      model:    payload[:model],
      provider: payload[:provider],
      intent:   payload[:intent],
      tier:     payload[:tier],
      message:  payload[:message]
    )
  end

  messages = normalize_messages(payload[:messages])
  prompt = extract_terminal_content(messages)
  return { success: false, error: 'invalid_request' } if prompt.nil?

  session = Legion::LLM.send(
    :chat_single,
    model:    payload[:model],
    provider: payload[:provider],
    intent:   payload[:intent],
    tier:     payload[:tier],
    tools:    payload[:tools]
  )
  session.with_instructions(payload[:system]) if payload[:system] && session.respond_to?(:with_instructions)

  prior_messages = messages.size > 1 ? messages[0..-2] : []
  prior_messages.each { |message| session.add_message(message) }

  session.ask(prompt)
end

.extract_error(response) ⇒ Object



233
234
235
236
237
# File 'lib/legion/llm/fleet/handler.rb', line 233

def extract_error(response)
  return unless response.is_a?(Hash)

  response[:error] || response['error']
end

.extract_field(response, field) ⇒ Object



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
149
150
# File 'lib/legion/llm/fleet/handler.rb', line 122

def extract_field(response, field)
  if response.is_a?(Hash)
    direct = response[field] || response[field.to_s]
    return direct unless direct.nil?

    meta = response[:meta] || response['meta']
    if meta.is_a?(Hash)
      meta_value = meta[field] || meta[field.to_s]
      return meta_value unless meta_value.nil?
    end

    routing = response[:routing] || response['routing']
    if routing.is_a?(Hash)
      routing_value = routing[field] || routing[field.to_s]
      return routing_value unless routing_value.nil?
    end

    return nil
  end

  if response.respond_to?(:routing) && response.routing.is_a?(Hash)
    routing_value = response.routing[field] || response.routing[field.to_s]
    return routing_value unless routing_value.nil?
  end

  return nil unless response.respond_to?(field)

  response.public_send(field)
end

.extract_success(response) ⇒ Object



225
226
227
228
229
230
231
# File 'lib/legion/llm/fleet/handler.rb', line 225

def extract_success(response)
  return response[:success] if response.is_a?(Hash) && response.key?(:success)
  return response['success'] if response.is_a?(Hash) && response.key?('success')
  return false if extract_error(response)

  true
end

.extract_terminal_content(messages) ⇒ Object



214
215
216
217
# File 'lib/legion/llm/fleet/handler.rb', line 214

def extract_terminal_content(messages)
  normalized = normalize_messages(messages)
  message_content(normalized.last)
end

.extract_token(response, field) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/legion/llm/fleet/handler.rb', line 108

def extract_token(response, field)
  return hash_token(response, field) if response.is_a?(Hash)

  if response.respond_to?(:tokens) && response.tokens.is_a?(Hash)
    token_key = { input_tokens: :input, output_tokens: :output, thinking_tokens: :thinking }[field]
    value = response.tokens[token_key] || response.tokens[token_key.to_s]
    return value.to_i if value
  end

  return 0 unless response.respond_to?(field)

  response.public_send(field).to_i
end

.handle_fleet_request(payload) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/legion/llm/fleet/handler.rb', line 12

def handle_fleet_request(payload)
  if Dispatcher.fleet_enabled? && !valid_token?(payload[:signed_token])
    error_response = { success: false, error: 'invalid_token' }
    publish_reply(payload[:reply_to], payload[:correlation_id], error_response) if payload[:reply_to]
    return error_response
  end

  response = call_local_llm(payload)
  response_hash = build_response(payload[:correlation_id], response)
  publish_reply(payload[:reply_to], payload[:correlation_id], response_hash) if payload[:reply_to]
  response_hash
end

.hash_token(response, field) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/legion/llm/fleet/handler.rb', line 239

def hash_token(response, field)
  direct = response[field] || response[field.to_s]
  return direct.to_i if direct

  meta = response[:meta] || response['meta']
  if meta.is_a?(Hash)
    meta_key = { input_tokens: :tokens_in, output_tokens: :tokens_out, thinking_tokens: :thinking_tokens }[field]
    meta_value = meta[meta_key] || meta[meta_key.to_s]
    return meta_value.to_i if meta_value
  end

  tokens = response[:tokens] || response['tokens']
  if tokens.is_a?(Hash)
    token_key = { input_tokens: :input, output_tokens: :output, thinking_tokens: :thinking }[field]
    token_value = tokens[token_key] || tokens[token_key.to_s]
    return token_value.to_i if token_value
  end

  0
end

.llm_available_for?(payload) ⇒ Boolean

Returns:

  • (Boolean)


152
153
154
155
156
# File 'lib/legion/llm/fleet/handler.rb', line 152

def llm_available_for?(payload)
  return false unless defined?(Legion::LLM)

  Legion::LLM.respond_to?(availability_method_for(payload), true)
end

.message_content(message) ⇒ Object



219
220
221
222
223
# File 'lib/legion/llm/fleet/handler.rb', line 219

def message_content(message)
  return unless message.is_a?(Hash)

  message[:content] || message['content']
end

.normalize_messages(messages) ⇒ Object



204
205
206
207
208
209
210
211
212
# File 'lib/legion/llm/fleet/handler.rb', line 204

def normalize_messages(messages)
  Array(messages).map do |message|
    next message unless message.is_a?(Hash)

    message.each_with_object({}) do |(key, value), normalized|
      normalized[key.respond_to?(:to_sym) ? key.to_sym : key] = value
    end
  end
end

.publish_reply(reply_to, correlation_id, response_hash) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/legion/llm/fleet/handler.rb', line 86

def publish_reply(reply_to, correlation_id, response_hash)
  return unless defined?(Legion::Transport)

  payload = if defined?(Legion::JSON)
              Legion::JSON.dump(response_hash)
            else
              require 'json'
              ::JSON.generate(response_hash)
            end

  channel = Legion::Transport.connection.create_channel
  channel.default_exchange.publish(
    payload,
    routing_key:    reply_to,
    correlation_id: correlation_id,
    content_type:   'application/json'
  )
  channel.close
rescue StandardError => e
  handle_exception(e, level: :warn)
end

.require_auth?Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/legion/llm/fleet/handler.rb', line 36

def require_auth?
  return false unless defined?(Legion::Settings)

  settings = begin
    Legion::Settings[:llm]
  rescue StandardError => e
    handle_exception(e, level: :debug, operation: 'llm.fleet.handler.require_auth')
    nil
  end
  return false unless settings.is_a?(Hash)

  fleet = settings.dig(:routing, :fleet)
  return false unless fleet.is_a?(Hash)

  fleet.fetch(:require_auth, false)
end

.unavailable_responseObject



169
170
171
# File 'lib/legion/llm/fleet/handler.rb', line 169

def unavailable_response
  { success: false, error: 'llm_not_available' }
end

.valid_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
# File 'lib/legion/llm/fleet/handler.rb', line 25

def valid_token?(token)
  return true unless require_auth?
  return false if token.nil?
  return true unless defined?(Legion::Crypt)

  !Legion::Crypt.validate_jwt(token).nil?
rescue StandardError => e
  handle_exception(e, level: :debug)
  false
end