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/metering.rb,
lib/legion/llm/inference/audit_publisher.rb,
lib/legion/llm/inference/steps/rag_guard.rb,
lib/legion/llm/inference/tool_dispatcher.rb,
lib/legion/llm/inference/steps/tool_calls.rb,
lib/legion/llm/inference/steps/rag_context.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/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/steps/knowledge_capture.rb,
lib/legion/llm/inference/steps/confidence_scoring.rb

Defined Under Namespace

Modules: AuditPublisher, Conversation, EnrichmentInjector, GaiaCaller, Profile, Prompt, Steps, Tracing Classes: 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
ToolDispatcher =
Tools::Dispatcher

Class Method Summary collapse

Class Method Details

.apply_response_guards(result, kwargs) ⇒ Object



722
723
724
725
726
727
728
729
730
731
732
733
734
735
# File 'lib/legion/llm/inference.rb', line 722

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



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
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/legion/llm/inference.rb', line 104

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 }
  )

  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



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
# File 'lib/legion/llm/inference.rb', line 447

def ask_direct(message:, model: nil, provider: nil, intent: nil, tier: nil, &)
  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]
  return normalize_ask_direct_hash(result, fallback_model: model || llm_setting(:default_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!



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

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

.attach_escalation_history(response, history, resolution, chain) ⇒ Object



680
681
682
683
684
685
686
687
# File 'lib/legion/llm/inference.rb', line 680

def attach_escalation_history(response, history, resolution, chain)
  return unless response.respond_to?(:extend)

  response.extend(EscalationHistory)
  history.each { |h| response.record_escalation_attempt(**h) }
  response.final_resolution = resolution
  response.escalation_chain = chain
end

.build_attempt(resolution, outcome, failures, duration_ms) ⇒ Object



672
673
674
675
676
677
678
# File 'lib/legion/llm/inference.rb', line 672

def build_attempt(resolution, outcome, failures, duration_ms)
  attempt = { model: resolution.model, provider: resolution.provider, tier: resolution.tier,
              outcome: outcome, failures: failures, duration_ms: duration_ms }
  attempt[:offering_id] = resolution.offering_id if resolution.offering_id
  attempt[:offering_metadata] = resolution. unless resolution..empty?
  attempt
end

.build_cache_key(model, provider, message, temperature) ⇒ Object



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

def build_cache_key(model, provider, message, temperature)
  messages_arr = message.is_a?(Array) ? message : [{ role: 'user', content: message.to_s }]
  Cache.key(
    model:       model || llm_setting(:default_model),
    provider:    provider || llm_setting(:default_provider),
    messages:    messages_arr,
    temperature: temperature
  )
end

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

Returns:

  • (Boolean)


737
738
739
# File 'lib/legion/llm/inference.rb', line 737

def cacheable?(cache_opt, temperature, message)
  cache_opt != false && temperature.to_f.zero? && message && Cache.enabled?
end

.caller_descriptor(caller_context) ⇒ Object



357
358
359
360
361
362
363
364
365
366
# File 'lib/legion/llm/inference.rb', line 357

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



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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/legion/llm/inference.rb', line 57

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
  )

  result = if defined?(Legion::Telemetry::OpenInference)
             Legion::Telemetry::OpenInference.llm_span(
               model:    (model || llm_setting(:default_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, **kwargs) ⇒ Object



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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/legion/llm/inference.rb', line 153

def chat_direct(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.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?
  cache_key = build_cache_key(model, provider, message, temperature) if cacheable?(cache_opt, temperature, message)

  if cache_key
    cached = Cache.get(cache_key)
    if cached
      log.debug '[llm][inference] chat_direct cache=hit'
      cached_response = cached.dup
      cached_response[:meta] = (cached_response[:meta] || {}).merge(cached: true)
      return cached_response
    end
  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.dispatch model=#{model} provider=#{provider} " \
    "escalate=#{escalate} message_present=#{!message.nil?}"
  )
  result = if escalate && message
             chat_with_escalation(
               model: model, provider: provider, intent: intent, tier: tier,
               max_escalations: max_escalations, quality_check: quality_check,
               message: message, temperature: temperature, **kwargs
             )
           else
             chat_single(model: model, provider: provider, intent: intent, tier: tier,
                         temperature: temperature, message: message, **kwargs, &)
           end
  log.debug("[llm][inference] chat_direct.exit result_class=#{result.class} result_nil=#{result.nil?}")

  if cache_key && result.is_a?(Hash)
    ttl = settings_value(:prompt_caching, :response_cache, :ttl_seconds) || Cache::DEFAULT_TTL
    Cache.set(cache_key, result, ttl: ttl)
  end

  result
end

.chat_single(model:, provider:, intent:, tier:, message: nil, **kwargs) ⇒ Object



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/legion/llm/inference.rb', line 506

def chat_single(model:, provider:, intent:, tier:, message: nil, **kwargs, &)
  explicit_tools = kwargs.delete(:tools)
  tools = explicit_tools
  tools = nil if tools.respond_to?(:empty?) && tools.empty?

  if (intent || tier) && Router.routing_enabled?
    resolution = Router.resolve(intent: intent, tier: tier, model: model, provider: provider)
    if resolution
      resolution = Router::GatewayInterceptor.intercept(resolution, context: kwargs.fetch(:context, {}))
      model = resolution.model
      provider = resolution.provider
      assert_external_allowed! if resolution.external?
    end
  elsif tier
    assert_external_allowed! if external_tier?(tier.to_sym)
  end

  model ||= llm_setting(:default_model)
  provider ||= (model && Router.infer_provider_for_model(model)) ||
               llm_setting(:default_provider)

  opts = {}
  opts[:model] = model if model
  opts[:provider] = provider if provider
  opts.merge!(kwargs.except(*FRAMEWORK_KEYS))
  opts.delete(:temperature) if opts[:temperature].nil?

  Call::Providers.inject_anthropic_cache_control!(opts, provider)
  opts[:tools] = tools if tools

  log.debug "[llm][inference] chat_single model=#{opts[:model]} provider=#{opts[:provider]} message_present=#{!message.nil?} tools=#{tools&.size || 0}"
  chat_single_native(model: opts[:model], provider: opts[:provider], message: message,
                     caller: kwargs[:caller], **opts.except(:model, :provider), &)
end

.chat_single_native(model:, provider:, message:, caller: nil, &block) ⇒ Object



541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/legion/llm/inference.rb', line 541

def chat_single_native(model:, provider:, message:, caller: nil, **, &block)
  raise native_provider_error('session-style chat requires message or messages') unless message
  raise native_provider_error('chat without a native provider') unless provider

  messages = message.is_a?(Array) ? message : [{ role: 'user', content: message.to_s }]
  result = if block
             Call::Dispatch.dispatch_stream(provider: provider, model: model, messages: messages, **, &block)
           else
             Call::Dispatch.dispatch_chat(provider: provider, model: model, messages: messages, **)
           end
  response = Call::NativeResponseAdapter.new(result)
  emit_non_pipeline_metering(response, model: model, provider: provider, caller: caller)
  response
end

.chat_via_pipeline(&block) ⇒ Object



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

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

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



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# File 'lib/legion/llm/inference.rb', line 586

def chat_with_escalation(model:, provider:, intent:, tier:, max_escalations:, quality_check:, message:, **kwargs)
  log.debug "[llm][inference] chat_with_escalation.enter model=#{model} provider=#{provider} max_escalations=#{max_escalations}"
  chain = Router.resolve_chain(
    intent: intent, tier: tier, model: model, provider: provider,
    max_escalations: max_escalations
  )

  threshold = escalation_quality_threshold
  history = []
  last_error = nil

  chain.each do |resolution|
    response, error = run_escalation_attempt(
      resolution, message: message, kwargs: kwargs, threshold: threshold,
      quality_check: quality_check, history: history, chain: chain
    )
    last_error = error if error
    return response if response
  end

  publish_escalation_event(history, :exhausted) if history.size > 1
  message = "All #{history.size} escalation attempts failed"
  if last_error
    providers = history.filter_map { |attempt| attempt[:provider] }.uniq.join(', ')
    message = "#{message}; no usable native provider handled the request. " \
              "providers=#{providers} last_error=#{last_error.class}: #{last_error.message}"
  end

  raise Legion::LLM::EscalationExhausted, message
end

.config_value(config, key, default = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/legion/llm/inference.rb', line 43

def config_value(config, key, default = nil)
  return default unless config.respond_to?(:key?)

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

  symbol_key = key.to_sym if key.respond_to?(:to_sym)
  return config[symbol_key] if symbol_key && config.key?(symbol_key)

  default
end

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

rubocop:disable Lint/UnusedMethodArgument



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/legion/llm/inference.rb', line 429

def daemon_ask(message:, model: nil, provider: nil, context: {}, tier: nil, identity: nil) # rubocop:disable Lint/UnusedMethodArgument
  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

Returns:

  • (Boolean)


474
475
476
# File 'lib/legion/llm/inference.rb', line 474

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



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/legion/llm/inference.rb', line 368

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 pipeline_enabled? && (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 pipeline_enabled? && (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

  if block_given? && message
    return chat_single(model: model, provider: provider, intent: intent, tier: tier,
                       message: message, **kwargs, &)
  end

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

  if defined?(Legion::LLM::Hooks)
    blocked = Legion::LLM::Hooks.run_before(messages: messages, model: resolved_model)
    return blocked[:response] if blocked
  end

  result = chat_direct(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: resolved_model)
    return blocked[:response] 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)


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

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

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

.elapsed_ms_since(started_at) ⇒ Object



263
264
265
# File 'lib/legion/llm/inference.rb', line 263

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) ⇒ Object



767
768
769
770
771
772
773
774
775
776
777
778
779
# File 'lib/legion/llm/inference.rb', line 767

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

  input  = response.respond_to?(:input_tokens)  ? response.input_tokens.to_i  : 0
  output = response.respond_to?(:output_tokens) ? response.output_tokens.to_i : 0
  Legion::LLM::Metering.emit(
    provider: provider, model_id: model, request_type: 'chat',
    tier: 'direct', input_tokens: input, output_tokens: output, total_tokens: input + output,
    caller: caller
  )
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.non_pipeline_metering')
end

.emit_privacy_blocked_auditObject



785
786
787
788
789
790
791
792
793
794
# File 'lib/legion/llm/inference.rb', line 785

def emit_privacy_blocked_audit
  Legion::LLM::Audit.emit_prompt(
    request_id: nil, conversation_id: nil, caller: nil,
    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

Returns:

  • (Boolean)


781
782
783
# File 'lib/legion/llm/inference.rb', line 781

def enterprise_privacy?
  Legion::LLM::Settings.enterprise_privacy?
end

.escalation_attempt_passed?(response, result, resolution, duration_ms, history, chain) ⇒ Boolean

Returns:

  • (Boolean)


647
648
649
650
651
652
653
654
655
656
# File 'lib/legion/llm/inference.rb', line 647

def escalation_attempt_passed?(response, result, resolution, duration_ms, history, chain)
  return false unless result.passed

  report_health(:success, resolution, duration_ms)
  history << build_attempt(resolution, :success, [], duration_ms)
  attach_escalation_history(response, history, resolution, chain)
  publish_escalation_event(history, :success) if history.size > 1
  log.debug "[llm][inference] chat_with_escalation success attempts=#{history.size}"
  true
end

.escalation_attempt_response(resolution, message, kwargs) ⇒ Object



639
640
641
642
643
644
645
# File 'lib/legion/llm/inference.rb', line 639

def escalation_attempt_response(resolution, message, kwargs)
  opts = { model: resolution.model, provider: resolution.provider }
  opts.merge!(kwargs.except(*FRAMEWORK_KEYS))
  chat_single_native(model: opts[:model], provider: opts[:provider],
                     message: message, caller: kwargs[:caller],
                     **opts.except(:model, :provider))
end

.escalation_enabled?Boolean

Returns:

  • (Boolean)


751
752
753
754
755
756
757
# File 'lib/legion/llm/inference.rb', line 751

def escalation_enabled?
  routing = llm_setting(:routing)
  return false unless routing.is_a?(Hash)

  esc = config_value(routing, :escalation, {})
  config_value(esc, :enabled) == true
end

.escalation_quality_thresholdObject



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

def escalation_quality_threshold
  routing = llm_setting(:routing)
  return 50 unless routing.is_a?(Hash)

  esc = config_value(routing, :escalation, {})
  config_value(esc, :quality_threshold, 50)
end

.external_tier?(tier) ⇒ Boolean

Returns:

  • (Boolean)


818
819
820
# File 'lib/legion/llm/inference.rb', line 818

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

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



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

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



267
268
269
270
271
# File 'lib/legion/llm/inference.rb', line 267

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

  message
end

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



289
290
291
292
293
294
295
296
# File 'lib/legion/llm/inference.rb', line 289

def inference_response_details(result, requested_model:, requested_provider:)
  if result.is_a?(Legion::LLM::Inference::Response)
    return pipeline_response_details(result, requested_model: requested_model, requested_provider: requested_provider)
  end
  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



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/legion/llm/inference.rb', line 273

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



347
348
349
350
351
352
353
354
355
# File 'lib/legion/llm/inference.rb', line 347

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

.llm_setting(key, default = nil) ⇒ Object



28
29
30
# File 'lib/legion/llm/inference.rb', line 28

def llm_setting(key, default = nil)
  config_value(llm_settings, key, default)
end

.llm_settingsObject



32
33
34
35
36
37
# File 'lib/legion/llm/inference.rb', line 32

def llm_settings
  Legion::LLM::Settings.current_settings
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.settings')
  {}
end

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



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/legion/llm/inference.rb', line 247

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



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/legion/llm/inference.rb', line 203

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)}",
    "input=#{input.inspect}"
  ]
  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



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/legion/llm/inference.rb', line 225

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])}",
    "output=#{details[:output].inspect}"
  ]
  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



571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/legion/llm/inference.rb', line 571

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}"
  Thread.new 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

.native_provider_error(operation) ⇒ Object



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

def native_provider_error(operation)
  Legion::LLM::ProviderError.new(
    "Native provider dispatch is required for #{operation}. Configure a registered lex-llm provider."
  )
end

.normalize_ask_direct_hash(result, fallback_model:) ⇒ Object



492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/legion/llm/inference.rb', line 492

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



325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/legion/llm/inference.rb', line 325

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

.pipeline_enabled?Boolean

Returns:

  • (Boolean)


416
417
418
419
420
421
# File 'lib/legion/llm/inference.rb', line 416

def pipeline_enabled?
  llm_setting(: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



298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/legion/llm/inference.rb', line 298

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) ⇒ Object



700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/legion/llm/inference.rb', line 700

def publish_escalation_event(history, final_outcome)
  payload = {
    outcome:   final_outcome,
    attempts:  history.size,
    history:   history,
    timestamp: Time.now.utc.iso8601
  }

  Legion::Events.emit('llm.escalation', **payload) 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(payload).publish if Legion::LLM::Settings.transport_connected?
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'llm.inference.publish_escalation_event', outcome: final_outcome)
  nil
end

.record_escalation_error(error, resolution, duration_ms, history) ⇒ Object



658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/legion/llm/inference.rb', line 658

def record_escalation_error(error, resolution, duration_ms, history)
  handle_exception(
    error,
    level:     :warn,
    handled:   true,
    operation: 'llm.inference.escalation_attempt',
    model:     resolution&.model,
    provider:  resolution&.provider,
    tier:      resolution&.tier
  )
  report_health(:error, resolution, duration_ms) if resolution
  history << build_attempt(resolution, :error, [error.class.name], duration_ms) if resolution
end

.report_health(signal, resolution, duration_ms, failures: nil) ⇒ Object



689
690
691
692
693
694
695
696
697
698
# File 'lib/legion/llm/inference.rb', line 689

def report_health(signal, resolution, duration_ms, failures: nil)
  return unless Router.routing_enabled?

   = { duration_ms: duration_ms }
  [:failures] = failures if failures
  Router.health_tracker.report(provider: resolution.provider, offering_id: resolution.offering_id,
                               signal: signal, value: 1, metadata: )
  Router.health_tracker.report(provider: resolution.provider, offering_id: resolution.offering_id,
                               signal: :latency, value: duration_ms, metadata: {})
end

.resolve_ask_direct_response(result, message, requested_model) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/legion/llm/inference.rb', line 478

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

  resolved_model = if result.respond_to?(:model_id) && result.model_id
                     result.model_id.to_s
                   else
                     (requested_model || llm_setting(:default_model)).to_s
                   end
  [result, resolved_model]
end

.response_guards_enabled?Boolean

Returns:

  • (Boolean)


718
719
720
# File 'lib/legion/llm/inference.rb', line 718

def response_guards_enabled?
  settings_value(:response_guards, :enabled) == true
end

.run_escalation_attempt(resolution, message:, kwargs:, threshold:, quality_check:, history:, chain:) ⇒ Object



617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/legion/llm/inference.rb', line 617

def run_escalation_attempt(resolution, message:, kwargs:, threshold:, quality_check:, history:, chain:)
  start_time = Time.now
  assert_external_allowed! if resolution.respond_to?(:external?) && resolution.external?

  response = escalation_attempt_response(resolution, message, kwargs)
  duration_ms = ((Time.now - start_time) * 1000).round
  result = Quality::Checker.check(response, quality_threshold: threshold, quality_check: quality_check)

  return [response, nil] if escalation_attempt_passed?(response, result, resolution, duration_ms, history, chain)

  report_health(:quality_failure, resolution, duration_ms, failures: result.failures)
  history << build_attempt(resolution, :quality_failure, result.failures, duration_ms)
  log.debug "[llm][inference] chat_with_escalation quality_failure attempt=#{history.size} failures=#{result.failures}"
  [nil, nil]
rescue Legion::LLM::PrivacyModeError
  raise
rescue StandardError => e
  duration_ms = ((Time.now - start_time) * 1000).round
  record_escalation_error(e, resolution, duration_ms, history)
  [nil, e]
end

.safe_inference_value(object, method_name) ⇒ Object



338
339
340
341
342
343
344
345
# File 'lib/legion/llm/inference.rb', line 338

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

.settings_value(*keys, default: nil) ⇒ Object



39
40
41
# File 'lib/legion/llm/inference.rb', line 39

def settings_value(*keys, default: nil)
  Legion::LLM::Settings.value(*keys, default: default)
end

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



562
563
564
565
566
567
568
569
# File 'lib/legion/llm/inference.rb', line 562

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