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



186
187
188
189
190
191
192
193
194
195
# File 'lib/legion/llm/fleet/handler.rb', line 186

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



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/legion/llm/fleet/handler.rb', line 66

def build_response(correlation_id, response, message_context: {})
  log.debug "[llm][fleet][handler] action=build_response correlation_id=#{correlation_id}"
  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



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

def call_local_llm(payload)
  log.debug "[llm][fleet][handler] action=call_local_llm request_type=#{payload[:request_type]} model=#{payload[:model]}"
  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



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
227
228
229
230
# File 'lib/legion/llm/fleet/handler.rb', line 201

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



261
262
263
264
265
# File 'lib/legion/llm/fleet/handler.rb', line 261

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

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

.extract_field(response, field) ⇒ Object



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
175
176
177
178
# File 'lib/legion/llm/fleet/handler.rb', line 150

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



253
254
255
256
257
258
259
# File 'lib/legion/llm/fleet/handler.rb', line 253

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



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

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

.extract_token(response, field) ⇒ Object



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

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



129
130
131
132
133
134
135
136
# File 'lib/legion/llm/fleet/handler.rb', line 129

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
28
29
# File 'lib/legion/llm/fleet/handler.rb', line 12

def handle_fleet_request(payload)
  payload = normalize_payload(payload)
  message_context = payload[:message_context] || {}
  log.debug '[llm][fleet][handler] action=handle_fleet_request.enter ' \
            "request_type=#{payload[:request_type]} model=#{payload[:model]} provider=#{payload[:provider]}"

  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



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/legion/llm/fleet/handler.rb', line 267

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)


180
181
182
183
184
# File 'lib/legion/llm/fleet/handler.rb', line 180

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



247
248
249
250
251
# File 'lib/legion/llm/fleet/handler.rb', line 247

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

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

.nested_fetch(hash, *keys) ⇒ Object



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

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



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

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



123
124
125
126
127
# File 'lib/legion/llm/fleet/handler.rb', line 123

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



146
147
148
# File 'lib/legion/llm/fleet/handler.rb', line 146

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



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

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, operation: 'llm.fleet.handler.publish_reply')
end

.require_auth?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/legion/llm/fleet/handler.rb', line 42

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

.unavailable_responseObject



197
198
199
# File 'lib/legion/llm/fleet/handler.rb', line 197

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

.valid_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


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

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, handled: true, operation: 'llm.fleet.handler.valid_token')
  false
end