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



182
183
184
185
186
187
188
189
190
191
# File 'lib/legion/llm/fleet/handler.rb', line 182

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, message_context: {}) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/legion/llm/fleet/handler.rb', line 63

def build_response(correlation_id, response, message_context: {})
  model = extract_field(response, :model)
  {
    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:           model,
    model_id:        model,
    message_context: optional_message_context(message_context)
  }.compact
end

.call_local_llm(payload) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/legion/llm/fleet/handler.rb', line 44

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



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/legion/llm/fleet/handler.rb', line 197

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



257
258
259
260
261
# File 'lib/legion/llm/fleet/handler.rb', line 257

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

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

.extract_field(response, field) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/legion/llm/fleet/handler.rb', line 146

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



249
250
251
252
253
254
255
# File 'lib/legion/llm/fleet/handler.rb', line 249

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



238
239
240
241
# File 'lib/legion/llm/fleet/handler.rb', line 238

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

.extract_token(response, field) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/legion/llm/fleet/handler.rb', line 105

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

.fetch_option(hash, key) ⇒ Object



125
126
127
128
129
130
131
132
# File 'lib/legion/llm/fleet/handler.rb', line 125

def fetch_option(hash, key)
  return nil unless hash.respond_to?(:key?)

  string_key = key.to_s
  return hash[string_key] if hash.key?(string_key)

  hash[key] if hash.key?(key)
end

.handle_fleet_request(payload) ⇒ Object



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

def handle_fleet_request(payload)
  payload = normalize_payload(payload)
  message_context = payload[:message_context] || {}

  if Dispatcher.fleet_enabled? && !valid_token?(payload[:signed_token])
    error_response = { success: false, error: 'invalid_token',
                       message_context: optional_message_context(message_context) }.compact
    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, message_context: message_context)
  publish_reply(payload[:reply_to], payload[:correlation_id], response_hash) if payload[:reply_to]
  response_hash
end

.hash_token(response, field) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/legion/llm/fleet/handler.rb', line 263

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)


176
177
178
179
180
# File 'lib/legion/llm/fleet/handler.rb', line 176

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



243
244
245
246
247
# File 'lib/legion/llm/fleet/handler.rb', line 243

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

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

.nested_fetch(hash, *keys) ⇒ Object



134
135
136
137
138
139
140
# File 'lib/legion/llm/fleet/handler.rb', line 134

def nested_fetch(hash, *keys)
  keys.reduce(hash) do |current, key|
    return nil unless current.respond_to?(:key?)

    fetch_option(current, key)
  end
end

.normalize_messages(messages) ⇒ Object



228
229
230
231
232
233
234
235
236
# File 'lib/legion/llm/fleet/handler.rb', line 228

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

.normalize_payload(payload) ⇒ Object



119
120
121
122
123
# File 'lib/legion/llm/fleet/handler.rb', line 119

def normalize_payload(payload)
  return {} unless payload.is_a?(Hash)

  payload.transform_keys { |key| key.respond_to?(:to_sym) ? key.to_sym : key }
end

.optional_message_context(message_context) ⇒ Object



142
143
144
# File 'lib/legion/llm/fleet/handler.rb', line 142

def optional_message_context(message_context)
  message_context.nil? || message_context.empty? ? nil : message_context
end

.publish_reply(reply_to, correlation_id, response_hash) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/legion/llm/fleet/handler.rb', line 80

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

  if defined?(Legion::LLM::Transport::Messages::FleetResponse)
    publish_result = Legion::LLM::Transport::Messages::FleetResponse.new(
      **response_hash, reply_to: reply_to, fleet_correlation_id: correlation_id
    ).publish
    log.warn("[llm][fleet][handler] action=reply_publish_failed correlation_id=#{correlation_id} status=#{publish_result[:status]}") if
      publish_result.is_a?(Hash) && publish_result[:accepted] == false
    return publish_result
  end

  payload = Legion::JSON.dump(response_hash)
  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)


40
41
42
# File 'lib/legion/llm/fleet/handler.rb', line 40

def require_auth?
  Legion::LLM::Settings.value(:routing, :fleet, :require_auth) == true
end

.unavailable_responseObject



193
194
195
# File 'lib/legion/llm/fleet/handler.rb', line 193

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

.valid_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
# File 'lib/legion/llm/fleet/handler.rb', line 29

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