legion-llm 0.5.4 → 0.5.7

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: 3c8ab6d42537aec5471648490e91968d41395206396b69f4cf48d73ac48cf217
4
+ data.tar.gz: 49ac7e085f62e08b3391e5926e774b920539a1bef03f64b9c7531bc697646ca4
5
5
  SHA512:
6
- metadata.gz: ee78d1dad4322e967231c1c90dca5082f0e9bfd56e474a0906281cf4507649076b0a75b0eb9cfba9ddb94a7beb54693a2d3dbd3ec1185bc6b15899f2b6f50c66
7
- data.tar.gz: e7cab9bfdcb2e602c1d7a1565faf78fca52bbfe18ac8763d82e58949f9f577c14ce3c3e9719035a9739145cab2428e800d2b9df29883da509c4055f7234ae199
6
+ metadata.gz: eb1f7f99f9edf09cc108a1d3643c9372ca9e07669dc4f89ff3d2c9d1c5305d1a0e26a8d02316f7edebcb5a9bfe3112a4c8a061f19d2af7bce2ba5649d0e7dccc
7
+ data.tar.gz: 22983edc5b03faa7692d9c71d5a73ca8d3eccadbf6730b1fd0e7ff9edfb5f2e0b1ea8c926045d3ad0bd6cc4d5fa96900c021964472076b0fce71a5a8fb128be8
@@ -3,14 +3,32 @@ on:
3
3
  push:
4
4
  branches: [main]
5
5
  pull_request:
6
+ schedule:
7
+ - cron: '0 9 * * 1'
6
8
 
7
9
  jobs:
8
10
  ci:
9
11
  uses: LegionIO/.github/.github/workflows/ci.yml@main
10
12
 
13
+ lint:
14
+ uses: LegionIO/.github/.github/workflows/lint-patterns.yml@main
15
+
16
+ security:
17
+ uses: LegionIO/.github/.github/workflows/security-scan.yml@main
18
+
19
+ version-changelog:
20
+ uses: LegionIO/.github/.github/workflows/version-changelog.yml@main
21
+
22
+ dependency-review:
23
+ uses: LegionIO/.github/.github/workflows/dependency-review.yml@main
24
+
25
+ stale:
26
+ if: github.event_name == 'schedule'
27
+ uses: LegionIO/.github/.github/workflows/stale.yml@main
28
+
11
29
  release:
12
- needs: ci
30
+ needs: [ci, lint]
13
31
  if: github.event_name == 'push' && github.ref == 'refs/heads/main'
14
32
  uses: LegionIO/.github/.github/workflows/release.yml@main
15
33
  secrets:
16
- rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
34
+ rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Legion LLM Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ### Fixed
6
+ - Fix namespace collision: use `::Data.define` instead of `Data.define` in Pipeline Request and Response to prevent resolution to `Legion::Data`
7
+
8
+ ## [0.5.6] - 2026-03-24
9
+
10
+ ### Fixed
11
+ - `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)
12
+ - Added `Transport::Exchanges::Audit` exchange class for the `llm.audit` topic exchange
13
+ - Added `Transport::Messages::AuditEvent` message class with `routing_key 'llm.audit.complete'`
14
+
15
+ ## [0.5.5] - 2026-03-24
16
+
17
+ ### Changed
18
+ - RAG context step now fires on almost all queries, not just long conversations
19
+ - RAG only skips trivial queries (greetings, pings) when strategy is auto
20
+ - 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`
21
+ - Strategy logic inverted: low utilization gets full RAG (room for context), high utilization gets compact, very high skips
22
+
3
23
  ## [0.5.4] - 2026-03-24
4
24
 
5
25
  ### 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/LICENSE CHANGED
@@ -1,11 +1,192 @@
1
-
2
1
  Apache License
3
2
  Version 2.0, January 2004
4
3
  http://www.apache.org/licenses/
5
4
 
6
5
  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
6
 
8
- Copyright 2026 Esity / Matthew Iverson
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 Esity
9
190
 
10
191
  Licensed under the Apache License, Version 2.0 (the "License");
11
192
  you may not use this file except in compliance with the License.
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
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module LLM
5
5
  module Pipeline
6
- Request = Data.define(
6
+ Request = ::Data.define(
7
7
  :id, :conversation_id, :idempotency_key, :schema_version,
8
8
  :system, :messages, :tools, :tool_choice,
9
9
  :routing, :tokens, :stop, :generation, :thinking,
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module LLM
5
5
  module Pipeline
6
- Response = Data.define(
6
+ Response = ::Data.define(
7
7
  :id, :request_id, :conversation_id, :schema_version,
8
8
  :message, :routing, :tokens, :thinking, :stop, :tools,
9
9
  :stream, :cache, :retry, :timestamps, :cost, :quality,
@@ -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.7'
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.7
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