legion-llm 0.5.4 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 888d6f2f71dee1e592ffdf92bc132355fcfd7900752e4c8df4151edebc32b8bb
4
- data.tar.gz: 1596d8e3819ee82e812aa434ffe6fdb39c5b4418b48bd034ed9da54b3f76e1a8
3
+ metadata.gz: 734e9ae7b47f1cef605a851314bf37e6bbf1a05db5dd61fc9aa0a29562a48ec6
4
+ data.tar.gz: 9a4e5519dd6ca8e00903c23cbb26e14ee2b2a24241c342af72c1702ecbb5864b
5
5
  SHA512:
6
- metadata.gz: ee78d1dad4322e967231c1c90dca5082f0e9bfd56e474a0906281cf4507649076b0a75b0eb9cfba9ddb94a7beb54693a2d3dbd3ec1185bc6b15899f2b6f50c66
7
- data.tar.gz: e7cab9bfdcb2e602c1d7a1565faf78fca52bbfe18ac8763d82e58949f9f577c14ce3c3e9719035a9739145cab2428e800d2b9df29883da509c4055f7234ae199
6
+ metadata.gz: 5a678f5944f951a7c55892bc530bffb006f34b478b2958d07ff3b290705b0ed114e224bfce6cdf998a5a70e0e1864da52d71c7d2aedc38eb879dce9e190987d6
7
+ data.tar.gz: '093d34861b714964b85bd8b3275f1872b3c0461037f621765f5e2b3178f9ddbe8e2a28a919e85c2ef09455c978e9a25383e35900cbe02dcaf3cc6478806a30d0'
data/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Legion LLM Changelog
2
2
 
3
+ ## [0.5.6] - 2026-03-24
4
+
5
+ ### Fixed
6
+ - `AuditPublisher` now uses dedicated `Transport::Messages::AuditEvent` message class instead of `Messages::Dynamic` (Dynamic ignores `exchange:`/`routing_key:` kwargs and requires a `function_id` DB lookup — audit events were never reaching RabbitMQ)
7
+ - Added `Transport::Exchanges::Audit` exchange class for the `llm.audit` topic exchange
8
+ - Added `Transport::Messages::AuditEvent` message class with `routing_key 'llm.audit.complete'`
9
+
10
+ ## [0.5.5] - 2026-03-24
11
+
12
+ ### Changed
13
+ - RAG context step now fires on almost all queries, not just long conversations
14
+ - RAG only skips trivial queries (greetings, pings) when strategy is auto
15
+ - All RAG thresholds configurable via `Legion::Settings[:llm][:rag]`: `full_limit`, `compact_limit`, `min_confidence`, `utilization_compact_threshold`, `utilization_skip_threshold`, `trivial_max_chars`, `trivial_patterns`
16
+ - Strategy logic inverted: low utilization gets full RAG (room for context), high utilization gets compact, very high skips
17
+
3
18
  ## [0.5.4] - 2026-03-24
4
19
 
5
20
  ### Added
data/CLAUDE.md CHANGED
@@ -8,7 +8,7 @@
8
8
  Core LegionIO gem providing LLM capabilities to all extensions. Wraps ruby_llm to provide a consistent interface for chat, embeddings, tool use, and agents across multiple providers (Bedrock, Anthropic, OpenAI, Gemini, Ollama). Includes a dynamic weighted routing engine that dispatches requests across local, fleet, and cloud tiers based on caller intent, priority rules, time schedules, cost multipliers, and real-time provider health.
9
9
 
10
10
  **GitHub**: https://github.com/LegionIO/legion-llm
11
- **Version**: 0.4.1
11
+ **Version**: 0.5.3
12
12
  **License**: Apache-2.0
13
13
 
14
14
  ## Architecture
@@ -110,7 +110,7 @@ Three-tier dispatch model. Local-first avoids unnecessary network hops; fleet of
110
110
 
111
111
  ### Gateway Integration (lex-llm-gateway)
112
112
 
113
- Gateway delegation removed in v0.4.1. `chat`, `embed`, and `structured` route directly — no `begin/rescue LoadError` block, no `gateway_loaded?` check. The pipeline (when `pipeline_enabled: true`) handles metering and fleet dispatch natively. The `_direct` variants still exist as the canonical non-pipeline path for `chat_direct`, `embed_direct`, `structured_direct`.
113
+ Gateway delegation removed in v0.4.1. `chat`, `embed`, and `structured` route directly — no `begin/rescue LoadError` block, no `gateway_loaded?` check. The pipeline (enabled by default since v0.4.8) handles metering and fleet dispatch natively. The `_direct` variants still exist as the canonical non-pipeline path for `chat_direct`, `embed_direct`, `structured_direct`.
114
114
 
115
115
  ### Integration with LegionIO
116
116
 
@@ -187,7 +187,7 @@ Settings read from `Legion::Settings[:llm]`:
187
187
  |-----|------|---------|-------------|
188
188
  | `enabled` | Boolean | `true` | Enable LLM support |
189
189
  | `connected` | Boolean | `false` | Set to true after successful start |
190
- | `pipeline_enabled` | Boolean | `false` | Enable 18-step pipeline for chat() dispatch |
190
+ | `pipeline_enabled` | Boolean | `true` | Enable 18-step pipeline for chat() dispatch (enabled by default since v0.4.8) |
191
191
  | `default_model` | String | `nil` | Default model ID (auto-detected if nil) |
192
192
  | `default_provider` | Symbol | `nil` | Default provider (auto-detected if nil) |
193
193
  | `providers` | Hash | See below | Per-provider configuration |
@@ -325,7 +325,7 @@ In-memory signal consumer with pluggable handlers. Adjusts effective priorities
325
325
  | `lib/legion/llm/structured_output.rb` | JSON schema enforcement with native response_format and prompt fallback |
326
326
  | `lib/legion/llm/errors.rb` | Typed error hierarchy: LLMError base + AuthError, RateLimitError, ContextOverflow, ProviderError, ProviderDown, UnsupportedCapability, PipelineError |
327
327
  | `lib/legion/llm/conversation_store.rb` | ConversationStore: in-memory LRU (256 slots) + optional Sequel DB persistence + spool fallback |
328
- | `lib/legion/llm/version.rb` | Version constant (0.4.2) |
328
+ | `lib/legion/llm/version.rb` | Version constant (0.5.3) |
329
329
  | `lib/legion/llm/quality_checker.rb` | QualityChecker module with QualityResult struct |
330
330
  | `lib/legion/llm/escalation_history.rb` | EscalationHistory mixin: `escalation_history`, `escalated?`, `final_resolution`, `escalation_chain` |
331
331
  | `lib/legion/llm/router/escalation_chain.rb` | EscalationChain value object |
@@ -451,8 +451,8 @@ The legacy `vault_path` per-provider setting was removed in v0.3.1.
451
451
  Tests run without the full LegionIO stack. `spec/spec_helper.rb` stubs `Legion::Logging` and `Legion::Settings` with in-memory implementations. Each test resets settings to defaults via `before(:each)`.
452
452
 
453
453
  ```bash
454
- bundle exec rspec # 794 examples, 0 failures
455
- bundle exec rubocop # 142 files, 0 offenses
454
+ bundle exec rspec # 882 examples, 0 failures
455
+ bundle exec rubocop # 0 offenses
456
456
  ```
457
457
 
458
458
  ## Design Documents
data/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  LLM integration for the [LegionIO](https://github.com/LegionIO/LegionIO) framework. Wraps [ruby_llm](https://github.com/crmne/ruby_llm) to provide chat, embeddings, tool use, and agent capabilities to any Legion extension.
4
4
 
5
- **Version**: 0.3.15
5
+ **Version**: 0.5.3
6
6
 
7
7
  ## Installation
8
8
 
@@ -280,9 +280,32 @@ session.with_tools(CodeAnalyzer, SecurityScanner)
280
280
  response = session.ask("Review this PR: #{diff}")
281
281
  ```
282
282
 
283
+ ### Unified Pipeline
284
+
285
+ All `chat()` calls flow through an 18-step request/response pipeline (enabled by default since v0.4.8). The pipeline handles RBAC, classification, RAG context retrieval, MCP tool discovery, metering, billing, audit, and GAIA advisory in a consistent sequence. Steps are skipped based on the caller profile (`:external`, `:gaia`, `:system`).
286
+
287
+ ```ruby
288
+ # Pipeline is enabled by default — no configuration needed
289
+ result = Legion::LLM.chat(message: "hello")
290
+
291
+ # Disable pipeline for a specific call (not recommended — use caller: profile instead)
292
+ # Set pipeline_enabled: false in settings to disable globally
293
+ ```
294
+
295
+ The pipeline accepts a `caller:` hash describing the request origin:
296
+
297
+ ```ruby
298
+ Legion::LLM.chat(
299
+ message: "hello",
300
+ caller: { requested_by: { identity: "user@example.com", type: :human, credential: :jwt } }
301
+ )
302
+ ```
303
+
304
+ System callers (type: `:system`) derive the `:system` profile, which skips governance steps to prevent recursion.
305
+
283
306
  ### Routing
284
307
 
285
- legion-llm includes a dynamic weighted routing engine that dispatches requests across local, fleet, and cloud tiers based on caller intent, priority rules, time schedules, cost multipliers, and real-time provider health. Routing is **disabled by default** — opt in via settings.
308
+ legion-llm includes a dynamic weighted routing engine that dispatches requests across local, fleet, and cloud tiers based on caller intent, priority rules, time schedules, cost multipliers, and real-time provider health. Routing is **disabled by default** — opt in by setting `routing.enabled: true` in settings.
286
309
 
287
310
  #### Three Tiers
288
311
 
@@ -629,7 +652,7 @@ bundle exec rspec
629
652
  Tests use stubbed `Legion::Logging` and `Legion::Settings` modules (no need for the full LegionIO stack):
630
653
 
631
654
  ```bash
632
- bundle exec rspec # Run all 304 tests
655
+ bundle exec rspec # Run all 882 tests
633
656
  bundle exec rubocop # Lint (0 offenses)
634
657
  bundle exec rspec spec/legion/llm_spec.rb # Run specific test file
635
658
  bundle exec rspec spec/legion/llm/router_spec.rb # Router tests only
@@ -34,14 +34,10 @@ module Legion
34
34
  event = build_event(request: request, response: response)
35
35
 
36
36
  begin
37
- if defined?(Legion::Transport) &&
38
- defined?(Legion::Transport::Messages::Dynamic)
39
- Legion::Transport::Messages::Dynamic.new(
40
- function: 'llm_audit',
41
- opts: event,
42
- exchange: EXCHANGE,
43
- routing_key: ROUTING_KEY
44
- ).publish
37
+ if defined?(Legion::Transport)
38
+ require 'legion/llm/transport/exchanges/audit'
39
+ require 'legion/llm/transport/messages/audit_event'
40
+ Legion::LLM::Transport::Messages::AuditEvent.new(**event).publish
45
41
  elsif defined?(Legion::Logging)
46
42
  Legion::Logging.debug('audit publish skipped: transport unavailable')
47
43
  end
@@ -6,32 +6,64 @@ module Legion
6
6
  module Steps
7
7
  module RagContext
8
8
  def step_rag_context
9
- strategy = select_context_strategy(utilization: estimate_utilization)
10
- return if %i[none full].include?(strategy)
9
+ return unless rag_enabled?
10
+ return unless substantive_query?
11
+ return unless apollo_available_or_warn?
11
12
 
12
- unless apollo_available?
13
- @warnings << 'Apollo unavailable for RAG context retrieval'
14
- return
15
- end
13
+ strategy = select_context_strategy(utilization: estimate_utilization)
14
+ return if strategy == :none
16
15
 
17
16
  query = extract_query
18
- return if query.nil? || query.empty?
19
-
20
17
  start_time = Time.now
21
18
  result = apollo_retrieve(query: query, strategy: strategy)
19
+ record_rag_enrichment(result, strategy)
20
+ record_rag_timeline(result, strategy, start_time)
21
+ rescue StandardError => e
22
+ @warnings << "RAG context error: #{e.message}"
23
+ end
22
24
 
23
- if result && result[:success] && result[:entries]&.any?
24
- @enrichments['rag:context_retrieval'] = {
25
- content: "#{result[:count]} entries retrieved via #{strategy}",
26
- data: {
27
- entries: result[:entries],
28
- strategy: strategy,
29
- count: result[:count]
30
- },
31
- timestamp: Time.now
32
- }
33
- end
25
+ private
26
+
27
+ def rag_settings
28
+ @rag_settings ||= if defined?(Legion::Settings) && !Legion::Settings[:llm].nil?
29
+ Legion::Settings[:llm][:rag] || {}
30
+ else
31
+ {}
32
+ end
33
+ end
34
+
35
+ def rag_enabled?
36
+ rag_settings.fetch(:enabled, true)
37
+ end
38
+
39
+ def substantive_query?
40
+ query = extract_query
41
+ return false if query.nil? || query.empty?
42
+
43
+ auto_strategy = @request.context_strategy.nil? || @request.context_strategy == :auto
44
+ return true unless auto_strategy
45
+
46
+ !trivial_query?(query)
47
+ end
48
+
49
+ def apollo_available_or_warn?
50
+ return true if apollo_available?
51
+
52
+ @warnings << 'Apollo unavailable for RAG context retrieval'
53
+ false
54
+ end
55
+
56
+ def record_rag_enrichment(result, strategy)
57
+ return unless result && result[:success] && result[:entries]&.any?
34
58
 
59
+ @enrichments['rag:context_retrieval'] = {
60
+ content: "#{result[:count]} entries retrieved via #{strategy}",
61
+ data: { entries: result[:entries], strategy: strategy, count: result[:count] },
62
+ timestamp: Time.now
63
+ }
64
+ end
65
+
66
+ def record_rag_timeline(result, strategy, start_time)
35
67
  @timeline.record(
36
68
  category: :enrichment, key: 'rag:context_retrieval',
37
69
  direction: :inbound,
@@ -39,20 +71,21 @@ module Legion
39
71
  from: 'apollo', to: 'pipeline',
40
72
  duration_ms: ((Time.now - start_time) * 1000).to_i
41
73
  )
42
- rescue StandardError => e
43
- @warnings << "RAG context error: #{e.message}"
44
74
  end
45
75
 
46
- private
47
-
48
76
  def select_context_strategy(utilization:)
49
77
  explicit = @request.context_strategy
50
78
  return explicit if explicit && explicit != :auto
51
79
 
52
- case utilization
53
- when 0...0.3 then :full
54
- when 0.3...0.8 then :rag_hybrid
55
- else :rag
80
+ skip_threshold = rag_settings.fetch(:utilization_skip_threshold, 0.9)
81
+ compact_threshold = rag_settings.fetch(:utilization_compact_threshold, 0.7)
82
+
83
+ if utilization >= skip_threshold
84
+ :none
85
+ elsif utilization >= compact_threshold
86
+ :rag_compact
87
+ else
88
+ :rag
56
89
  end
57
90
  end
58
91
 
@@ -63,15 +96,29 @@ module Legion
63
96
  message_tokens.to_f / @request.tokens[:max]
64
97
  end
65
98
 
99
+ def trivial_query?(query)
100
+ max_chars = rag_settings.fetch(:trivial_max_chars, 20)
101
+ patterns = rag_settings.fetch(:trivial_patterns, [])
102
+
103
+ return false if query.length > max_chars
104
+
105
+ normalized = query.strip.downcase.gsub(/[^a-z0-9\s]/, '')
106
+ patterns.any? { |p| normalized == p }
107
+ end
108
+
66
109
  def apollo_available?
67
110
  defined?(::Legion::Extensions::Apollo::Runners::Knowledge)
68
111
  end
69
112
 
70
113
  def apollo_retrieve(query:, strategy:)
71
- opts = { query: query, limit: 10, min_confidence: 0.5 }
72
- opts[:limit] = 5 if strategy == :rag_hybrid
114
+ full_limit = rag_settings.fetch(:full_limit, 10)
115
+ compact_limit = rag_settings.fetch(:compact_limit, 5)
116
+ confidence = rag_settings.fetch(:min_confidence, 0.5)
73
117
 
74
- ::Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(**opts)
118
+ limit = strategy == :rag_compact ? compact_limit : full_limit
119
+ ::Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(
120
+ query: query, limit: limit, min_confidence: confidence
121
+ )
75
122
  end
76
123
 
77
124
  def extract_query
@@ -19,7 +19,8 @@ module Legion
19
19
  prompt_caching: prompt_caching_defaults,
20
20
  arbitrage: arbitrage_defaults,
21
21
  batch: batch_defaults,
22
- scheduling: scheduling_defaults
22
+ scheduling: scheduling_defaults,
23
+ rag: rag_defaults
23
24
  }
24
25
  end
25
26
 
@@ -113,6 +114,19 @@ module Legion
113
114
  }
114
115
  end
115
116
 
117
+ def self.rag_defaults
118
+ {
119
+ enabled: true,
120
+ full_limit: 10,
121
+ compact_limit: 5,
122
+ min_confidence: 0.5,
123
+ utilization_compact_threshold: 0.7,
124
+ utilization_skip_threshold: 0.9,
125
+ trivial_max_chars: 20,
126
+ trivial_patterns: %w[hello hi hey ping pong test ok okay yes no thanks thank]
127
+ }
128
+ end
129
+
116
130
  def self.providers
117
131
  {
118
132
  bedrock: {
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module LLM
5
+ module Transport
6
+ module Exchanges
7
+ class Audit < ::Legion::Transport::Exchange
8
+ def exchange_name
9
+ 'llm.audit'
10
+ end
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module LLM
5
+ module Transport
6
+ module Messages
7
+ class AuditEvent < ::Legion::Transport::Message
8
+ def exchange
9
+ Legion::LLM::Transport::Exchanges::Audit
10
+ end
11
+
12
+ def routing_key
13
+ 'llm.audit.complete'
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Legion
4
4
  module LLM
5
- VERSION = '0.5.4'
5
+ VERSION = '0.5.6'
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: legion-llm
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.4
4
+ version: 0.5.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Esity
@@ -255,7 +255,9 @@ files:
255
255
  - lib/legion/llm/shadow_eval.rb
256
256
  - lib/legion/llm/structured_output.rb
257
257
  - lib/legion/llm/tool_registry.rb
258
+ - lib/legion/llm/transport/exchanges/audit.rb
258
259
  - lib/legion/llm/transport/exchanges/escalation.rb
260
+ - lib/legion/llm/transport/messages/audit_event.rb
259
261
  - lib/legion/llm/transport/messages/escalation_event.rb
260
262
  - lib/legion/llm/version.rb
261
263
  homepage: https://github.com/LegionIO/legion-llm