Module: Legion::LLM::Inference

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/inference.rb,
lib/legion/llm/inference/steps.rb,
lib/legion/llm/inference/prompt.rb,
lib/legion/llm/inference/profile.rb,
lib/legion/llm/inference/request.rb,
lib/legion/llm/inference/tracing.rb,
lib/legion/llm/inference/executor.rb,
lib/legion/llm/inference/response.rb,
lib/legion/llm/inference/timeline.rb,
lib/legion/llm/inference/steps/rbac.rb,
lib/legion/llm/inference/gaia_caller.rb,
lib/legion/llm/inference/conversation.rb,
lib/legion/llm/inference/steps/debate.rb,
lib/legion/llm/inference/steps/billing.rb,
lib/legion/llm/inference/steps/logging.rb,
lib/legion/llm/inference/embed_pipeline.rb,
lib/legion/llm/inference/route_attempts.rb,
lib/legion/llm/inference/steps/metering.rb,
lib/legion/llm/inference/attempt_context.rb,
lib/legion/llm/inference/audit_publisher.rb,
lib/legion/llm/inference/steps/gut_check.rb,
lib/legion/llm/inference/steps/rag_guard.rb,
lib/legion/llm/inference/tool_dispatcher.rb,
lib/legion/llm/inference/executor/routing.rb,
lib/legion/llm/inference/native_tool_loop.rb,
lib/legion/llm/inference/steps/tool_calls.rb,
lib/legion/llm/inference/steps/rag_context.rb,
lib/legion/llm/inference/context_accounting.rb,
lib/legion/llm/inference/steps/prompt_cache.rb,
lib/legion/llm/inference/steps/token_budget.rb,
lib/legion/llm/inference/steps/tool_history.rb,
lib/legion/llm/inference/enrichment_injector.rb,
lib/legion/llm/inference/executor/escalation.rb,
lib/legion/llm/inference/steps/gaia_advisory.rb,
lib/legion/llm/inference/steps/mcp_discovery.rb,
lib/legion/llm/inference/steps/post_response.rb,
lib/legion/llm/inference/steps/tier_assigner.rb,
lib/legion/llm/inference/steps/trigger_match.rb,
lib/legion/llm/inference/steps/classification.rb,
lib/legion/llm/inference/steps/skill_injector.rb,
lib/legion/llm/inference/steps/span_annotator.rb,
lib/legion/llm/inference/steps/sticky_helpers.rb,
lib/legion/llm/inference/steps/sticky_persist.rb,
lib/legion/llm/inference/steps/sticky_runners.rb,
lib/legion/llm/inference/steps/tool_discovery.rb,
lib/legion/llm/inference/executor/context_window.rb,
lib/legion/llm/inference/executor/tool_injection.rb,
lib/legion/llm/inference/steps/knowledge_capture.rb,
lib/legion/llm/inference/executor/payload_builder.rb,
lib/legion/llm/inference/steps/confidence_scoring.rb

Defined Under Namespace

Modules: AuditPublisher, ContextAccounting, Conversation, EmbedPipeline, EnrichmentInjector, GaiaCaller, NativeToolLoop, Profile, Prompt, RouteAttempts, Steps, Tracing Classes: AttemptContext, Executor, Request, Response, Timeline

Constant Summary collapse

FRAMEWORK_KEYS =
%i[request_id source timestamp datetime task_id parent_id master_id
check_subtask generate_task catch_exceptions worker_id principal_id
principal_type caller].freeze
RESPONSE_CACHE_OPERATION =

SSOT v3 §20.1 operation for the chat_direct response cache probe.

:chat
AUTO_ROUTING_MODEL_KEY =
'legionio'
ToolDispatcher =
Tools::Dispatcher

Class Method Summary collapse

Class Method Details

.apply_response_guards(result, kwargs) ⇒ Object



674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'lib/legion/llm/inference.rb', line 674

def apply_response_guards(result, kwargs)
  context = kwargs[:context]
  response_text = result[:response] || result[:content]
  guard_result = Hooks::ResponseGuard.guard_response(
    response: response_text, context: context
  )

  log.warn "[llm][inference] response_guard passed=#{guard_result[:passed]}" unless guard_result[:passed]

  result.merge(_guard_result: guard_result)
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.apply_response_guards')
  result
end

.ask(message:, model: nil, provider: nil, intent: nil, tier: nil, context: {}, identity: nil) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
135
136
137
138
# File 'lib/legion/llm/inference.rb', line 83

def ask(message:, model: nil, provider: nil, intent: nil, tier: nil,
        context: {}, identity: nil, &)
  started_at = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  log_inference_request(
    request_type:       :ask,
    requested_model:    model,
    requested_provider: provider,
    intent:             intent,
    tier:               tier,
    message:            message,
    kwargs:             { context: context, identity: identity }
  )

  # L9 (annotated dual topology — a design call, not a defect fix): one
  # ask() surface, two execution topologies. With a remote daemon
  # configured the request goes over the wire and the daemon runs the
  # governed pipeline there; without one the same governed pipeline runs
  # in-process (ask_direct -> chat_direct). Both paths meter/audit where
  # they execute; the historical ungoverned ask_direct gap is closed
  # (0.12.16). The split is explicit and recorded here so the topology is
  # a known edge; collapsing it is a design decision.
  if Call::DaemonClient.available?
    result = daemon_ask(message: message, model: model, provider: provider,
                        context: context, tier: tier, identity: identity)
    if result
      log_inference_response(
        request_type:       :ask,
        requested_model:    model,
        requested_provider: provider,
        result:             result,
        duration_ms:        elapsed_ms_since(started_at)
      )
      return result
    end
  end

  result = ask_direct(message: message, model: model, provider: provider,
                      intent: intent, tier: tier, &)
  log_inference_response(
    request_type:       :ask,
    requested_model:    model,
    requested_provider: provider,
    result:             result,
    duration_ms:        elapsed_ms_since(started_at)
  )
  result
rescue StandardError => e
  log_inference_error(
    request_type:       :ask,
    requested_model:    model,
    requested_provider: provider,
    error:              e,
    duration_ms:        elapsed_ms_since(started_at)
  )
  raise
end

.ask_direct(message:, model: nil, provider: nil, intent: nil, tier: nil) ⇒ Object

rubocop:disable Legion/Framework/NoDirectDispatch ask_direct is a deprecated shim. The previous body routed through chat_direct_raw, an ungoverned path that bypasses metering/audit — the same compliance gap that motivated the chat_direct/embed_direct/ structured_direct deprecation in 0.12.16. It now routes through the governed pipeline via chat_direct and adapts the response to the legacy {status:, response:, meta:} shape ask() callers expect.



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/legion/llm/inference.rb', line 523

def ask_direct(message:, model: nil, provider: nil, intent: nil, tier: nil, &)
  Legion::LLM::Deprecation.warn_once(:ask_direct, replacement: 'Legion::LLM.ask')
  assert_external_allowed! if effective_tier_is_external?(tier, provider)

  result = chat_direct(
    model:    model,
    provider: provider,
    intent:   intent,
    tier:     tier,
    message:  message,
    &
  )

  return result if result.is_a?(Hash) && result[:deferred]
  # M2: the meta model is the Selection-reported model (meta[:model]) or
  # the requested model — no configured default fabricated pre-Selection.
  return normalize_ask_direct_hash(result, fallback_model: model) if result.is_a?(Hash)

  response, resolved_model = resolve_ask_direct_response(result, message, model, &)

  {
    status:   :done,
    response: response.content,
    meta:     {
      tier:       :direct,
      model:      resolved_model,
      tokens_in:  response.respond_to?(:input_tokens) ? response.input_tokens : nil,
      tokens_out: response.respond_to?(:output_tokens) ? response.output_tokens : nil
    }
  }
end

.assert_external_allowed!Object Also known as: assert_cloud_allowed!



890
891
892
893
894
895
896
897
# File 'lib/legion/llm/inference.rb', line 890

def assert_external_allowed!
  return unless enterprise_privacy?

  emit_privacy_blocked_audit
  raise Legion::LLM::PrivacyModeError,
        'External LLM tiers are disabled: enterprise_data_privacy is enabled. ' \
        'Only local and fleet tiers are permitted.'
end

.blocked_hook_response(blocked) ⇒ Object



669
670
671
672
# File 'lib/legion/llm/inference.rb', line 669

def blocked_hook_response(blocked)
  reason = blocked[:reason] || blocked['reason'] || blocked[:message] || blocked['message'] || 'request blocked by hook'
  { error: 'request_blocked', message: reason.to_s }
end

.cacheable?(cache_opt, temperature, message) ⇒ Boolean

Returns:

  • (Boolean)


689
690
691
692
# File 'lib/legion/llm/inference.rb', line 689

def cacheable?(cache_opt, temperature, message)
  effective_temp = temperature.nil? ? Legion::Settings[:llm][:default_temperature] : temperature
  cache_opt != false && effective_temp.to_f.zero? && message && Cache.enabled?
end

.caller_descriptor(caller_context) ⇒ Object



430
431
432
433
434
435
436
437
438
439
# File 'lib/legion/llm/inference.rb', line 430

def caller_descriptor(caller_context)
  return caller_context unless caller_context.is_a?(Hash)

  source = caller_context[:source] || caller_context['source']
  path = caller_context[:path] || caller_context['path']
  return "#{source}:#{path}" if source && path
  return source.to_s if source

  caller_context.inspect
end

.chat(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil, max_escalations: nil, quality_check: nil, message: nil, **kwargs) ⇒ Object

Public inference entry points — these are the methods delegated from Legion::LLM



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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/legion/llm/inference.rb', line 33

def chat(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil,
         max_escalations: nil, quality_check: nil, message: nil, **kwargs, &)
  started_at = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  log_inference_request(
    request_type:       :chat,
    requested_model:    model,
    requested_provider: provider,
    intent:             intent,
    tier:               tier,
    message:            message,
    kwargs:             kwargs
  )

  # M2: the span label carries the REQUESTED model (nil when the request
  # is unconstrained) — it must not assert a configured default the
  # Selection may never pick.
  result = if defined?(Legion::Telemetry::OpenInference)
             Legion::Telemetry::OpenInference.llm_span(
               model:    model&.to_s,
               provider: provider&.to_s,
               input:    message
             ) do |_span|
               dispatch_chat(model: model, provider: provider, intent: intent, tier: tier, escalate: escalate,
                             max_escalations: max_escalations, quality_check: quality_check, message: message, **kwargs, &)
             end
           else
             dispatch_chat(model: model, provider: provider, intent: intent, tier: tier,
                           escalate: escalate, max_escalations: max_escalations,
                           quality_check: quality_check, message: message, **kwargs, &)
           end

  log_inference_response(
    request_type:       :chat,
    requested_model:    model,
    requested_provider: provider,
    result:             result,
    duration_ms:        elapsed_ms_since(started_at)
  )
  result
rescue StandardError => e
  log_inference_error(
    request_type:       :chat,
    requested_model:    model,
    requested_provider: provider,
    error:              e,
    duration_ms:        elapsed_ms_since(started_at)
  )
  raise
end

.chat_direct(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil, max_escalations: nil, quality_check: nil, message: nil) ⇒ Object

rubocop:disable Legion/Framework/NoDirectDispatch chat_direct is a deprecated shim per CHANGELOG 0.12.16 that routes through the governed pipeline; see Legion::LLM::Deprecation.warn_once.



143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/legion/llm/inference.rb', line 143

def chat_direct(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil,
                max_escalations: nil, quality_check: nil, message: nil, **, &)
  Legion::LLM::Deprecation.warn_once(:chat_direct, replacement: 'Legion::LLM.chat')

  if Thread.current[:legion_llm_in_pipeline] || !pipeline_enabled? || !message
    return chat_direct_raw(model: model, provider: provider, intent: intent, tier: tier,
                           escalate: escalate, max_escalations: max_escalations,
                           quality_check: quality_check, message: message, **, &)
  end

  chat_direct_governed(model: model, provider: provider, intent: intent, tier: tier,
                       escalate: escalate, max_escalations: max_escalations,
                       quality_check: quality_check, message: message, **, &)
end

.chat_direct_governed(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil, max_escalations: nil, quality_check: nil, message: nil, **kwargs) ⇒ Object

rubocop:enable Legion/Framework/NoDirectDispatch



159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
203
204
205
206
207
208
# File 'lib/legion/llm/inference.rb', line 159

def chat_direct_governed(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil,
                         max_escalations: nil, quality_check: nil, message: nil, **kwargs, &)
  log.debug(
    "[llm][inference] chat_direct_governed.enter model=#{model} provider=#{provider} " \
    "intent=#{intent} tier=#{tier} message_present=#{!message.nil?}"
  )

  assert_external_allowed! if effective_tier_is_external?(tier, provider)

  caller_hash = kwargs.delete(:caller) || { requested_by: { type: :system, identity: 'legion:internal:chat_direct' } }
  cache_opt = kwargs.delete(:cache) { true }
  temperature = kwargs.delete(:temperature)
  kwargs.delete(:urgency)

  # SSOT v3 §20.1: select first, then probe the response cache by the exact
  # Selection identity — before any callable acquisition. There is no
  # pre-routing response cache (M2): a hit served without a Selection would
  # outlive the lane that produced it — no inventory generation check, no
  # metering/audit of the serving. When the SSOT inventory path is inactive
  # the probe returns nil and the response is dispatched uncached.
  cache_key = nil
  ssot_cache = ssot_response_cache(message: message, model: model, provider: provider,
                                   tier: tier, temperature: temperature, cache_opt: cache_opt,
                                   shape: response_cache_shape(kwargs))
  if ssot_cache
    return ssot_cache[:response] if ssot_cache[:hit]

    cache_key = ssot_cache[:key]
  end

  # SSOT v3: no default provider/model and no legacy fallback. An
  # unconstrained request (no provider/model/tier pin) is a valid
  # unconstrained SSOT selection — next_lane ranks all eligible lanes.
  # There is one engine (Prompt.dispatch -> Executor -> RoutingSession).
  result = Prompt.dispatch(
    message,
    intent: intent, tier: tier, provider: provider, model: model,
    escalate: escalate, max_escalations: max_escalations,
    quality_check: quality_check, caller: caller_hash,
    temperature: temperature, **kwargs.except(:messages)
  )

  if cache_key && result.is_a?(Hash)
    ttl = Legion::Settings[:llm][:prompt_caching][:response_cache][:ttl_seconds]
    Cache.set(cache_key, result, ttl: ttl)
  end

  log.debug("[llm][inference] chat_direct_governed.exit result_class=#{result.class}")
  result
end

.chat_direct_raw(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil, max_escalations: nil, quality_check: nil, message: nil, **kwargs) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/legion/llm/inference.rb', line 210

def chat_direct_raw(model: nil, provider: nil, intent: nil, tier: nil, escalate: nil,
                    max_escalations: nil, quality_check: nil, message: nil, **kwargs, &)
  log.debug(
    "[llm][inference] chat_direct_raw.enter model=#{model} provider=#{provider} intent=#{intent} " \
    "tier=#{tier} escalate=#{escalate} message_present=#{!message.nil?} kwargs=#{kwargs.keys.sort}"
  )
  cache_opt = kwargs.delete(:cache) { true }
  temperature = kwargs.delete(:temperature)

  escalate = escalation_enabled? if escalate.nil?

  # SSOT v3 §20.1: select first, then probe the response cache by the exact
  # Selection identity — before any callable acquisition. There is no
  # pre-routing response cache (M2) — see chat_direct_governed.
  cache_key = nil
  ssot_cache = ssot_response_cache(message: message, model: model, provider: provider,
                                   tier: tier, temperature: temperature, cache_opt: cache_opt,
                                   shape: response_cache_shape(kwargs))
  if ssot_cache
    return ssot_cache[:response] if ssot_cache[:hit]

    cache_key = ssot_cache[:key]
  end

  urgency = kwargs.delete(:urgency) { :normal }
  deferred = try_defer(intent: intent, urgency: urgency, model: model, provider: provider, message: message, **kwargs)
  return deferred if deferred

  log.debug(
    "[llm][inference] chat_direct_raw.dispatch model=#{model} provider=#{provider} " \
    "escalate=#{escalate} message_present=#{!message.nil?}"
  )
  # SSOT v3 single engine: retry/failover is inherent to the RoutingSession
  # loop, so there is no separate escalation chain and no chat_single legacy
  # selector — both collapse to one Prompt.dispatch -> Executor call.
  result = Prompt.dispatch(
    message,
    intent: intent, tier: tier, provider: provider, model: model,
    escalate: escalate, max_escalations: max_escalations,
    quality_check: quality_check, caller: kwargs[:caller],
    temperature: temperature, **kwargs.except(:messages, :caller), &
  )
  log.debug("[llm][inference] chat_direct_raw.exit result_class=#{result.class} result_nil=#{result.nil?}")

  if cache_key && result.is_a?(Hash)
    ttl = Legion::Settings[:llm][:prompt_caching][:response_cache][:ttl_seconds]
    Cache.set(cache_key, result, ttl: ttl)
  end

  result
end

.chat_via_pipeline(&block) ⇒ Object



492
493
494
495
496
# File 'lib/legion/llm/inference.rb', line 492

def chat_via_pipeline(**, &block)
  request = Request.from_chat_args(**)
  executor = Executor.new(request)
  block ? executor.call_stream(&block) : executor.call
end

.daemon_ask(message:, model: nil, provider: nil, context: {}, tier: nil) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/legion/llm/inference.rb', line 498

def daemon_ask(message:, model: nil, provider: nil, context: {}, tier: nil, **)
  result = Call::DaemonClient.chat(
    message: message, model: model, provider: provider,
    context: context, tier_preference: tier || :auto
  )

  case result[:status]
  when :immediate, :created
    result[:body]
  when :accepted
    Cache::Response.poll(result[:request_id])
  when :denied
    raise Legion::LLM::DaemonDeniedError, result.dig(:error, :message) || 'Access denied'
  when :rate_limited
    raise Legion::LLM::DaemonRateLimitedError, "Rate limited. Retry after #{result[:retry_after]}s"
  end
end

.direct_chat_session?(result) ⇒ Boolean

rubocop:enable Legion/Framework/NoDirectDispatch

Returns:

  • (Boolean)


556
557
558
# File 'lib/legion/llm/inference.rb', line 556

def direct_chat_session?(result)
  result.respond_to?(:ask) && result.respond_to?(:model) && !result.respond_to?(:content)
end

.dispatch_chat(model:, provider:, intent:, tier:, escalate:, max_escalations:, quality_check:, message:, **kwargs) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/legion/llm/inference.rb', line 441

def dispatch_chat(model:, provider:, intent:, tier:, escalate:, max_escalations:, quality_check:, message:, **kwargs, &)
  log.debug(
    "[llm][inference] dispatch_chat.enter model=#{model} provider=#{provider} intent=#{intent} " \
    "tier=#{tier} escalate=#{escalate} max_escalations=#{max_escalations} " \
    "quality_check=#{quality_check} message_present=#{!message.nil?} kwargs=#{kwargs.keys.sort}"
  )
  if (message || kwargs[:messages]) && !block_given?
    return Prompt.dispatch(
      message || kwargs[:messages],
      intent: intent, tier: tier, provider: provider, model: model,
      escalate: escalate, max_escalations: max_escalations,
      quality_check: quality_check, **kwargs.except(:messages)
    )
  end

  if (message || kwargs[:messages]) && block_given?
    return chat_via_pipeline(model: model, provider: provider, intent: intent, tier: tier,
                             message: message, escalate: escalate, max_escalations: max_escalations,
                             quality_check: quality_check, **kwargs, &)
  end

  messages = message.is_a?(Array) ? message : [{ role: 'user', content: message.to_s }]

  # M2: hooks see the requested model (nil when the request is
  # unconstrained) — no configured default asserted pre-Selection.
  if defined?(Legion::LLM::Hooks)
    blocked = Legion::LLM::Hooks.run_before(messages: messages, model: model)
    return blocked[:response] || blocked_hook_response(blocked) if blocked
  end

  result = chat_direct_raw(model: model, provider: provider, intent: intent, tier: tier,
                           escalate: escalate, max_escalations: max_escalations,
                           quality_check: quality_check, message: message, **kwargs)

  if defined?(Legion::LLM::Hooks)
    blocked = Legion::LLM::Hooks.run_after(response: result, messages: messages, model: model)
    return blocked[:response] || blocked_hook_response(blocked) if blocked
  end

  result = apply_response_guards(result, kwargs) if response_guards_enabled? && result.is_a?(Hash)
  log.debug("[llm][inference] dispatch_chat.exit result_class=#{result.class} result_nil=#{result.nil?}")
  result
end

.effective_tier_is_external?(tier, provider) ⇒ Boolean Also known as: effective_tier_is_cloud?

Returns:

  • (Boolean)


901
902
903
904
905
906
907
908
# File 'lib/legion/llm/inference.rb', line 901

def effective_tier_is_external?(tier, provider)
  return external_tier?(tier.to_sym) if tier
  return false unless enterprise_privacy?

  resolved = provider || Legion::Settings[:llm][:default_provider]
  external_providers = %i[anthropic bedrock openai gemini azure]
  external_providers.include?(resolved&.to_sym)
end

.elapsed_ms_since(started_at) ⇒ Object



327
328
329
# File 'lib/legion/llm/inference.rb', line 327

def elapsed_ms_since(started_at)
  ((::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - started_at) * 1000).round
end

.emit_non_pipeline_metering(response, model:, provider:, caller: nil, messages: nil) ⇒ Object



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'lib/legion/llm/inference.rb', line 822

def emit_non_pipeline_metering(response, model:, provider:, caller: nil, messages: nil)
  return unless response

  usage = response.respond_to?(:usage) ? response.usage : nil
  input    = usage.respond_to?(:input_tokens)    ? usage.input_tokens.to_i    : 0
  output   = usage.respond_to?(:output_tokens)   ? usage.output_tokens.to_i   : 0
  thinking = usage.respond_to?(:thinking_tokens) ? usage.thinking_tokens.to_i : 0

  finish = nil
  if response.respond_to?(:stop_reason)
    finish = response.stop_reason&.to_s
  elsif response.respond_to?(:stop) && response.stop.is_a?(Hash)
    finish = response.stop[:reason]&.to_s
  end

  meta = response.respond_to?(:metadata) ? response. : {}
  meta_hash = meta.is_a?(Hash) ? meta : {}
  latency = (meta_hash[:latency_ms] || meta_hash.dig(:timing, :latency_ms) || 0).to_i
  wall_clock = (meta_hash[:wall_clock_ms] || meta_hash.dig(:timing, :wall_clock_ms) || 0).to_i

  response_content = if response.respond_to?(:text)
                       response.text
                     elsif response.respond_to?(:content)
                       response.content
                     end

  Legion::LLM::Metering.emit(
    provider:          provider,
    model_id:          model,
    request_type:      'chat',
    tier:              'direct',
    input_tokens:      input,
    output_tokens:     output,
    thinking_tokens:   thinking,
    total_tokens:      input + output + thinking,
    finish_reason:     finish,
    provider_instance: response.respond_to?(:instance) ? response.instance : nil,
    latency_ms:        latency,
    wall_clock_ms:     wall_clock,
    caller:            caller,
    event_type:        'llm_completion',
    status:            'success',
    messages:          messages,
    response_content:  response_content
  )
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.non_pipeline_metering')
end

.emit_privacy_blocked_auditObject



879
880
881
882
883
884
885
886
887
888
# File 'lib/legion/llm/inference.rb', line 879

def emit_privacy_blocked_audit
  Legion::LLM::Audit.emit_prompt(
    request_id: nil, conversation_id: nil, caller: Legion::LLM::PublisherIdentity.caller_hash,
    routing: {}, tokens: {}, status: 'privacy_blocked',
    error: { class: 'PrivacyModeError', message: 'External tiers blocked by enterprise privacy' },
    timestamp: Time.now, request_type: 'chat'
  )
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.emit_privacy_blocked_audit')
end

.enterprise_privacy?Boolean

L1: the consumer-side ENV fallback is gone — the env/setting resolution lives in the shared owner (Legion::Settings.enterprise_privacy?), consumed directly (hard dependency; no respond_to? guard). Same owner as Router.privacy_mode?.

Returns:

  • (Boolean)


875
876
877
# File 'lib/legion/llm/inference.rb', line 875

def enterprise_privacy?
  Legion::Settings.enterprise_privacy?
end

.escalation_enabled?Boolean

Returns:

  • (Boolean)


806
807
808
809
810
811
812
# File 'lib/legion/llm/inference.rb', line 806

def escalation_enabled?
  routing = Legion::Settings[:llm][:routing]
  return false unless routing.is_a?(Hash)

  esc = routing.is_a?(Hash) ? (routing[:escalation] || {}) : {}
  esc[:enabled] == true
end

.escalation_quality_thresholdObject



814
815
816
817
818
819
820
# File 'lib/legion/llm/inference.rb', line 814

def escalation_quality_threshold
  routing = Legion::Settings[:llm][:routing]
  return 50 unless routing.is_a?(Hash)

  esc = routing.is_a?(Hash) ? (routing[:escalation] || {}) : {}
  esc[:quality_threshold] || 50
end

.external_tier?(tier) ⇒ Boolean

Returns:

  • (Boolean)


912
913
914
# File 'lib/legion/llm/inference.rb', line 912

def external_tier?(tier)
  %i[cloud frontier].include?(tier)
end

.extract_error_category_from_attempt(attempt) ⇒ Object



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/legion/llm/inference.rb', line 649

def extract_error_category_from_attempt(attempt)
  return nil unless attempt.is_a?(Hash)

  failures = Array(attempt[:failures])
  return nil if failures.empty?

  first = failures.first
  if first.is_a?(Hash)
    first[:category]&.to_s || first[:error]&.to_s
  elsif first.is_a?(String)
    first
  else
    first.to_s
  end
end

.hash_response_details(result, requested_model:, requested_provider:) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/legion/llm/inference.rb', line 374

def hash_response_details(result, requested_model:, requested_provider:)
  meta = result[:meta] || result['meta'] || {}
  {
    output:        result[:response] || result['response'] || result[:content] || result['content'] || result.dig(:message, :content) || result.to_s,
    provider:      result[:provider] || result['provider'] || meta[:provider] || meta['provider'] || requested_provider,
    model:         result[:model] || result['model'] || meta[:model] || meta['model'] || requested_model,
    input_tokens:  result[:input_tokens] || result['input_tokens'] || meta[:tokens_in] || meta['tokens_in'],
    output_tokens: result[:output_tokens] || result['output_tokens'] || meta[:tokens_out] || meta['tokens_out'],
    stop_reason:   result[:stop_reason] || result['stop_reason'] || result.dig(:stop, :reason) || result.dig('stop', 'reason'),
    tool_calls:    Array(result[:tool_calls] || result['tool_calls'] || result[:tools] || result['tools']).size
  }
end

.inference_input_payload(message:, messages:) ⇒ Object



331
332
333
334
335
# File 'lib/legion/llm/inference.rb', line 331

def inference_input_payload(message:, messages:)
  return messages unless messages.nil?

  message
end

.inference_response_details(result, requested_model:, requested_provider:) ⇒ Object



353
354
355
356
357
358
# File 'lib/legion/llm/inference.rb', line 353

def inference_response_details(result, requested_model:, requested_provider:)
  return pipeline_response_details(result, requested_model: requested_model, requested_provider: requested_provider) if result.is_a?(Legion::LLM::Inference::Response)
  return hash_response_details(result, requested_model: requested_model, requested_provider: requested_provider) if result.is_a?(Hash)

  object_response_details(result, requested_model: requested_model, requested_provider: requested_provider)
end

.inference_text_length(payload) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/legion/llm/inference.rb', line 337

def inference_text_length(payload)
  case payload
  when Array
    payload.sum { |item| inference_text_length(item) }
  when Hash
    return payload[:content].to_s.length if payload.key?(:content)
    return payload['content'].to_s.length if payload.key?('content')

    payload.values.sum { |item| inference_text_length(item) }
  when nil
    0
  else
    payload.to_s.length
  end
end

.inference_token_value(tokens, key) ⇒ Object



409
410
411
412
413
414
415
416
417
# File 'lib/legion/llm/inference.rb', line 409

def inference_token_value(tokens, key)
  return nil if tokens.nil?
  return tokens[key] || tokens[key.to_s] if tokens.is_a?(Hash)

  method_name = { input: :input_tokens, output: :output_tokens, total: :total_tokens }[key]
  return tokens.public_send(method_name) if method_name && tokens.respond_to?(method_name)

  nil
end

.log_inference_error(request_type:, requested_model:, requested_provider:, error:, duration_ms:) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/legion/llm/inference.rb', line 311

def log_inference_error(request_type:, requested_model:, requested_provider:, error:, duration_ms:)
  parts = [
    '[llm][inference] response',
    "type=#{request_type}",
    'status=error',
    "duration_ms=#{duration_ms}",
    "error_class=#{error.class}",
    "error=#{error.message.inspect}"
  ]
  parts << "requested_provider=#{requested_provider}" if requested_provider
  parts << "requested_model=#{requested_model}" if requested_model
  log.error(parts.join(' '))
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.log_error')
end

.log_inference_request(request_type:, requested_model:, requested_provider:, intent:, tier:, message:, kwargs:) ⇒ Object



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

def log_inference_request(request_type:, requested_model:, requested_provider:, intent:, tier:, message:, kwargs:)
  input = inference_input_payload(message: message, messages: kwargs[:messages])
  parts = [
    '[llm][inference] request',
    "type=#{request_type}",
    "input_length=#{inference_text_length(input)}"
  ]
  # M1: the raw payload is a compliance sink — it is not logged unless an
  # operator enables llm.logging.payload_preview_chars (bounded preview).
  preview = payload_preview(input)
  parts << "input_preview=#{preview}" if preview
  parts << "requested_provider=#{requested_provider}" if requested_provider
  parts << "requested_model=#{requested_model}" if requested_model
  parts << "intent=#{intent}" if intent
  parts << "tier=#{tier}" if tier
  parts << "caller=#{caller_descriptor(kwargs[:caller])}" if kwargs[:caller]
  parts << "conversation_id=#{kwargs[:conversation_id]}" if kwargs[:conversation_id]
  parts << "request_id=#{kwargs[:request_id]}" if kwargs[:request_id]
  parts << "tools=#{Array(kwargs[:tools]).size}" if kwargs.key?(:tools)
  parts << 'stream=true' if kwargs[:stream]
  log.info(parts.join(' '))
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.log_request')
end

.log_inference_response(request_type:, requested_model:, requested_provider:, result:, duration_ms:) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/legion/llm/inference.rb', line 287

def log_inference_response(request_type:, requested_model:, requested_provider:, result:, duration_ms:)
  details = inference_response_details(result, requested_model: requested_model, requested_provider: requested_provider)
  parts = [
    '[llm][inference] response',
    "type=#{request_type}",
    'status=ok',
    "duration_ms=#{duration_ms}",
    "result_class=#{result.class}",
    "output_length=#{inference_text_length(details[:output])}"
  ]
  # M1: bounded, gated preview only — see log_inference_request.
  preview = payload_preview(details[:output])
  parts << "output_preview=#{preview}" if preview
  parts << "provider=#{details[:provider]}" if details[:provider]
  parts << "model=#{details[:model]}" if details[:model]
  parts << "input_tokens=#{details[:input_tokens]}" unless details[:input_tokens].nil?
  parts << "output_tokens=#{details[:output_tokens]}" unless details[:output_tokens].nil?
  parts << "stop_reason=#{details[:stop_reason]}" if details[:stop_reason]
  parts << "tool_calls=#{details[:tool_calls]}" unless details[:tool_calls].nil?
  log.info(parts.join(' '))
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.log_response')
end

.maybe_shadow_evaluate(response, messages, primary_model) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/legion/llm/inference.rb', line 599

def maybe_shadow_evaluate(response, messages, primary_model)
  return unless Quality::ShadowEval.enabled? && Quality::ShadowEval.should_sample?

  log.debug "[llm][inference] shadow_evaluate primary_model=#{primary_model}"
  Inference::Executor::ASYNC_THREAD_POOL.post do
    Quality::ShadowEval.evaluate(
      primary_response: { content: response.respond_to?(:content) ? response.content : response.to_s,
                          model: primary_model, usage: {} },
      messages:         messages
    )
  rescue StandardError => e
    handle_exception(e, level: :warn, operation: 'llm.inference.shadow_eval')
  end
end

.normalize_ask_direct_hash(result, fallback_model:) ⇒ Object



576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/legion/llm/inference.rb', line 576

def normalize_ask_direct_hash(result, fallback_model:)
  meta = result[:meta].is_a?(Hash) ? result[:meta] : {}
  {
    status:   result[:status] || :done,
    response: result[:response] || result[:content],
    meta:     {
      tier:       meta[:tier] || :direct,
      model:      (meta[:model] || fallback_model).to_s,
      tokens_in:  meta[:tokens_in],
      tokens_out: meta[:tokens_out]
    }
  }
end

.object_response_details(result, requested_model:, requested_provider:) ⇒ Object



387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/legion/llm/inference.rb', line 387

def object_response_details(result, requested_model:, requested_provider:)
  tool_calls = safe_inference_value(result, :tool_calls)
  {
    output:        safe_inference_value(result, :content) || result.to_s,
    provider:      requested_provider,
    model:         safe_inference_value(result, :model_id)&.to_s || requested_model,
    input_tokens:  safe_inference_value(result, :input_tokens),
    output_tokens: safe_inference_value(result, :output_tokens),
    stop_reason:   safe_inference_value(result, :stop_reason),
    tool_calls:    tool_calls.nil? ? nil : Array(tool_calls).size
  }
end

.payload_preview(payload) ⇒ Object

M1: bounded payload preview for the inference log. Returns nil when llm.logging.payload_preview_chars is unset/<= 0 (metadata-only log); otherwise the payload's inspect truncated at that many characters.



422
423
424
425
426
427
428
# File 'lib/legion/llm/inference.rb', line 422

def payload_preview(payload)
  preview_chars = Legion::Settings.dig(:llm, :logging, :payload_preview_chars).to_i
  return nil if preview_chars <= 0

  rendered = payload.inspect
  rendered.length > preview_chars ? "#{rendered[0, preview_chars]}..." : rendered
end

.pipeline_enabled?Boolean

Returns:

  • (Boolean)


485
486
487
488
489
490
# File 'lib/legion/llm/inference.rb', line 485

def pipeline_enabled?
  Legion::Settings[:llm][:pipeline_enabled] == true
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.pipeline_enabled')
  false
end

.pipeline_response_details(result, requested_model:, requested_provider:) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/legion/llm/inference.rb', line 360

def pipeline_response_details(result, requested_model:, requested_provider:)
  message = result.message
  tokens = result.tokens
  {
    output:        message.is_a?(Hash) ? (message[:content] || message['content']) : message.to_s,
    provider:      result.routing[:provider] || result.routing['provider'] || requested_provider,
    model:         result.routing[:model] || result.routing['model'] || requested_model,
    input_tokens:  inference_token_value(tokens, :input),
    output_tokens: inference_token_value(tokens, :output),
    stop_reason:   result.stop[:reason] || result.stop['reason'],
    tool_calls:    Array(result.tools).size
  }
end

.publish_escalation_event(history, final_outcome, caller: nil) ⇒ Object



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/legion/llm/inference.rb', line 614

def publish_escalation_event(history, final_outcome, caller: nil)
  return if history.size <= 1

  first_attempt = history.first
  last_attempt = history.last

  event = {
    outcome:        final_outcome,
    attempts:       history.size,
    history:        history,
    # Flat fields for consumer compatibility
    from_provider:  first_attempt&.dig(:provider),
    from_instance:  first_attempt&.dig(:instance),
    from_model:     first_attempt&.dig(:model),
    to_provider:    last_attempt&.dig(:provider),
    to_instance:    last_attempt&.dig(:instance),
    to_model:       last_attempt&.dig(:model),
    reason:         ('provider_failover' if [:failure, 'failure', :error].include?(first_attempt&.dig(:outcome))),
    error_category: extract_error_category_from_attempt(first_attempt),
    attempt_no:     history.size,
    latency_ms:     history.sum { |a| (a[:duration_ms] || 0).to_i },
    caller:         caller || Legion::LLM::PublisherIdentity.caller_hash,
    timestamp:      Time.now.utc.iso8601
  }

  Legion::Events.emit('llm.escalation', **event) if defined?(Legion::Events) && Legion::Events.respond_to?(:emit)

  log.info "[llm][inference] escalation_event outcome=#{final_outcome} attempts=#{history.size}"

  Transport::Messages::EscalationEvent.new(event).publish if Legion::Settings.dig(:transport, :connected) == true
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.publish_escalation_event', outcome: final_outcome)
  nil
end

.resolve_ask_direct_response(result, message, requested_model) ⇒ Object



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/legion/llm/inference.rb', line 560

def resolve_ask_direct_response(result, message, requested_model, &)
  if direct_chat_session?(result)
    response = block_given? ? result.ask(message, &) : result.ask(message)
    return [response, result.model.to_s]
  end

  # M2: known model identities only (the session's model_id or the
  # requested model) — nil when neither exists, not a fabricated default.
  resolved_model = if result.respond_to?(:model_id) && result.model_id
                     result.model_id.to_s
                   else
                     requested_model&.to_s
                   end
  [result, resolved_model]
end

.response_cache_shape(kwargs) ⇒ Object



794
795
796
797
798
799
800
801
802
803
804
# File 'lib/legion/llm/inference.rb', line 794

def response_cache_shape(kwargs)
  {
    system:          kwargs[:system],
    tools:           kwargs[:tools],
    tool_choice:     kwargs[:tool_choice],
    thinking:        kwargs[:thinking],
    response_format: kwargs[:response_format],
    tokens:          kwargs[:tokens],
    generation:      kwargs[:generation]
  }
end

.response_guards_enabled?Boolean

Returns:

  • (Boolean)


665
666
667
# File 'lib/legion/llm/inference.rb', line 665

def response_guards_enabled?
  Legion::Settings.dig(:llm, :response_guards, :enabled) == true
end

.safe_inference_value(object, method_name) ⇒ Object



400
401
402
403
404
405
406
407
# File 'lib/legion/llm/inference.rb', line 400

def safe_inference_value(object, method_name)
  return nil unless object.methods.include?(method_name) || object.private_methods.include?(method_name)

  object.public_send(method_name)
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.safe_value', method_name: method_name)
  nil
end

.ssot_cache_key_for(selection:, request:, snapshot:) ⇒ Object



770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/legion/llm/inference.rb', line 770

def ssot_cache_key_for(selection:, request:, snapshot:)
  lane = snapshot.lane(lane_id: selection.lane_id)
  revision_evidence = lane&.model_revision_evidence
  revision = if revision_evidence.respond_to?(:known?) && revision_evidence.known?
               revision_evidence.value.to_s
             else
               "instance:#{selection.instance_id}"
             end
  Cache.selection_key(
    provider_family:   selection.provider_family,
    model:             selection.model,
    revision:          revision,
    operation:         selection.operation,
    system:            request.system,
    messages:          request.messages,
    tools:             request.tools,
    tool_choice:       request.tool_choice,
    thinking:          request.thinking,
    response_format:   request.response_format,
    max_output_tokens: (request.tokens.is_a?(Hash) ? request.tokens[:max] : nil),
    generation:        request.generation
  )
end

.ssot_cache_request(message:, model:, provider:, tier:, temperature:, shape:) ⇒ Object



739
740
741
742
743
744
745
746
747
748
749
750
751
752
# File 'lib/legion/llm/inference.rb', line 739

def ssot_cache_request(message:, model:, provider:, tier:, temperature:, shape:)
  args = { message: message, model: model, provider: provider }
  args[:tier] = tier if tier
  args[:system] = shape[:system] if shape[:system]
  args[:tools] = shape[:tools] if shape.key?(:tools)
  args[:tool_choice] = shape[:tool_choice] if shape[:tool_choice]
  args[:thinking] = shape[:thinking] if shape[:thinking]
  args[:response_format] = shape[:response_format] if shape[:response_format]
  args[:tokens] = shape[:tokens] if shape[:tokens]
  generation = (shape[:generation] || {}).dup
  generation[:temperature] = temperature unless temperature.nil?
  args[:generation] = generation unless generation.empty?
  Inference::Request.from_chat_args(**args)
end

.ssot_cache_router(request) ⇒ Object

Mirror the executor's build_ssot_router so the probe selection uses the exact same routing derivation the dispatch will — including the raw body model source (metadata, byte-for-byte with inference/executor/routing.rb). An explicit routing pin still reaches the Router as a trusted constraint, so no fallback is needed here.



759
760
761
762
763
764
765
766
767
768
# File 'lib/legion/llm/inference.rb', line 759

def ssot_cache_router(request)
  Legion::LLM::Router.new(
    request:    request,
    operation:  RESPONSE_CACHE_OPERATION,
    body_model: request.[:client_model]
  )
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.inference.ssot_cache_router')
  nil
end

.ssot_response_cache(message:, model:, provider:, tier:, temperature:, cache_opt:, shape: {}) ⇒ Object

SSOT v3 §20.1: select the exact lane through a per-request RoutingSession, then probe the response cache keyed by that Selection — AFTER next_attempt returns an AttemptContext but BEFORE any callable acquisition. A cache hit therefore proves current policy/capability/context/availability eligibility and reports the exact Selection identity while avoiding provider dispatch. Returns:

{ hit: true,  response: <hash>, key: <str> } on hit,
{ hit: false, response: nil,   key: <str> } on miss (caller dispatches + stores),
nil when the SSOT inventory path is inactive or the request is not
cacheable (the call runs uncached — there is no pre-routing cache).


707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/legion/llm/inference.rb', line 707

def ssot_response_cache(message:, model:, provider:, tier:, temperature:, cache_opt:, shape: {})
  return nil unless cacheable?(cache_opt, temperature, message)

  snapshot = Legion::Extensions::Llm::Inventory::Registry.snapshot
  return nil unless snapshot.generation.positive?

  request = ssot_cache_request(message: message, model: model, provider: provider,
                               tier: tier, temperature: temperature, shape: shape)
  router = ssot_cache_router(request)
  return nil unless router

  attempt = router.next_attempt
  return nil if attempt.is_a?(Legion::Extensions::Llm::Routing::Rejection)

  key = ssot_cache_key_for(selection: attempt.selection, request: request, snapshot: snapshot)
  cached = Cache.get(key)
  return { hit: false, response: nil, key: key } unless cached

  response = cached.dup
  response[:meta] = (response[:meta] || {}).merge(
    cached:   true,
    provider: attempt.selection.provider_family,
    model:    attempt.selection.model,
    instance: attempt.selection.instance_id
  )
  log.debug "[llm][inference] action=ssot_response_cache cache=hit provider=#{attempt.selection.provider_family} model=#{attempt.selection.model}"
  { hit: true, response: response, key: key }
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'llm.inference.ssot_response_cache')
  nil
end

.try_defer(intent:, urgency:, model:, provider:, message:) ⇒ Object



590
591
592
593
594
595
596
597
# File 'lib/legion/llm/inference.rb', line 590

def try_defer(intent:, urgency:, model:, provider:, message:, **)
  return nil unless Scheduling.enabled? && Scheduling.should_defer?(intent: intent || :normal, urgency: urgency)
  return nil unless Legion::LLM::Scheduling::Batch.enabled?

  log.debug "[llm][inference] try_defer deferring intent=#{intent} urgency=#{urgency}"
  entry_id = Legion::LLM::Scheduling::Batch.enqueue(model: model, provider: provider, message: message, priority: urgency, **)
  { deferred: true, batch_id: entry_id, next_off_peak: Scheduling.next_off_peak.iso8601 }
end