legion-llm 0.16.30 → 0.16.33
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 +4 -4
- data/CHANGELOG.md +15 -0
- data/Gemfile +5 -0
- data/README.md +4 -0
- data/lib/legion/llm/api/client_translators/openai_responses.rb +12 -1
- data/lib/legion/llm/api/namespaces/openai/responses.rb +1 -1
- data/lib/legion/llm/api/openai/responses.rb +5 -2
- data/lib/legion/llm/context/curator.rb +66 -38
- data/lib/legion/llm/inference/steps/rag_context.rb +50 -23
- data/lib/legion/llm/version.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 41a81bd0c3f5c632a5a35642c58743e5aab3ec0e282ff5eba28a0320f0db27d8
|
|
4
|
+
data.tar.gz: 16803a9c8e349325518a92bf2ca534629688bde036915efef6bf3b4cc0a959b7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 70da4042c85dadda310e92345df41fa98c4297ace0e0937c03b23f60d2c64102dcdbfef513b2b1fa909d48378047b4c35b022eb20e94ae1f37f8f55c049a2eb0
|
|
7
|
+
data.tar.gz: ce77bf942a540e8d431f86fae0f7ac4129e8a66d9aa6d76d328d1c2bca36b9ad9bd0c45ea5862851a3988e4f479b99f299318dc5d6ba0149efd6c899091af52f
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Legion LLM Changelog
|
|
2
2
|
|
|
3
|
+
## [0.16.33] - 2026-11-19
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
- Retain complete conversation history when Apollo archival fails or returns a malformed, unknown, or async-only acknowledgment. Accept confirmed local/direct persistence and existing-content deduplication; mixed facade results must contain a confirmed persisted child. Apply the same check to all archive paths and log unconfirmed outcomes without archive content. Add real SQLite failure/persistence coverage and all three client formats in synchronous and streaming execution. Fixes #192.
|
|
7
|
+
|
|
8
|
+
## [0.16.32] - 2026-11-19
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- Normalize Apollo RAG result envelopes, deduplicate general and conversation-history facts, and enforce one combined strategy limit, including smaller GAIA context limits. Preserve retrieval order and metadata; filter excluded sources before deduplication and limiting. Empty fallbacks no longer raise, failed retrievals cannot inject stale entries, and skipped history lookups do not manufacture successful retrievals. Cover actual provider-bound canonical messages across all three client formats in synchronous and streaming execution. Fixes #195.
|
|
12
|
+
|
|
13
|
+
## [0.16.31] - 2026-11-19
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
- Serialize Responses SSE payloads with lossless JSON Unicode escapes so clients can record raw HTTP byte buffers without ASCII-8BIT-to-UTF-8 errors. Preserve complete MCP arguments/results, following assistant text, and streaming errors through the current and legacy Responses renderers. Add in-process regressions for real MCP execution, buffered/unbuffered streaming, emoji, combining characters, and literal escape sequences. Refs #224.
|
|
17
|
+
|
|
3
18
|
## [0.16.30] - 2026-11-19
|
|
4
19
|
|
|
5
20
|
### Fixed
|
data/Gemfile
CHANGED
|
@@ -11,6 +11,11 @@ legion_mcp_path = File.expand_path('../legion-mcp', __dir__)
|
|
|
11
11
|
gem 'legion-mcp', path: legion_mcp_path if Dir.exist?(legion_mcp_path)
|
|
12
12
|
|
|
13
13
|
group :test do
|
|
14
|
+
# Archive regressions use the published Apollo implementation and an isolated SQLite store.
|
|
15
|
+
gem 'legion-apollo', '>= 0.5.13', require: false
|
|
16
|
+
gem 'sequel'
|
|
17
|
+
gem 'sqlite3', '>= 2.0'
|
|
18
|
+
|
|
14
19
|
# Immutable CI companions and adjacent development checkouts both consume the
|
|
15
20
|
# shared contract directly. Standalone installs use the gemspec dependency.
|
|
16
21
|
lex_llm_path = File.expand_path('.ci-dependencies/lex-llm', __dir__)
|
data/README.md
CHANGED
|
@@ -99,6 +99,8 @@ Curation runs **after** each turn (async), never inside the tool loop, so it nev
|
|
|
99
99
|
|
|
100
100
|
`drop_and_archive` is the strategy that makes curation more than a bigger trash can: instead of discarding overflow context, it sends it to the Apollo knowledge store, where it stays retrievable on future turns. Client-side compaction is lossy truncation — once it's gone, it's gone. This is archival: a fact from turn 3 can resurface at turn 300.
|
|
101
101
|
|
|
102
|
+
History is removed only after confirmed persistence, including a confirmed existing-content duplicate. Failed, malformed, unknown, or async-only acknowledgments retain the history for a later attempt. A mixed-backend response must contain a confirmed persisted result; publishing an archive request alone is insufficient.
|
|
103
|
+
|
|
102
104
|
Apollo is two stores. The local per-node store ([legion-apollo](https://github.com/LegionIO/legion-apollo)) starts knowledge at confidence 0.5, corroborates at +0.15, decays at 0.005 per pass, and archives below 0.1 ([confidence.rb](https://github.com/LegionIO/legion-apollo/blob/main/lib/legion/apollo/helpers/confidence.rb)). The shared cross-node store ([lex-apollo](https://github.com/LegionIO/lex-apollo)) corroborates at +0.3 — only when a ≥0.9-cosine match arrives from a *different* provider — and begins time decay after 168 hours. The pipeline steps here use the local store (`Legion::Apollo::Local`).
|
|
103
105
|
|
|
104
106
|
Lifecycle status in the local store moves through `pending` → `confirmed` / `disputed` → `deprecated` / `archived`. The shared store is backed by PostgreSQL+pgvector (`lib/legion/extensions/apollo.rb`).
|
|
@@ -109,6 +111,8 @@ The loop closes back up in the Inference pipeline, across three steps:
|
|
|
109
111
|
- `rag_context` (`lib/legion/llm/inference/steps/rag_context.rb`) queries Apollo — via the shared-store runner when available, falling back to `Legion::Apollo.retrieve(scope: :all)`, which merges local and shared results — and injects relevant knowledge into the request before it goes out.
|
|
110
112
|
- `gaia_advisory` (`lib/legion/llm/inference/steps/gaia_advisory.rb`) queries `Legion::Apollo::Local` — the local store only — for advisory context: tone, partner history, routing hints. GAIA advises; it doesn't inject prompts. The pipeline is what pulls context in.
|
|
111
113
|
|
|
114
|
+
RAG merges general and conversation-history results in retrieval order, removes excluded sources and duplicate facts, then applies one combined `llm.rag.full_limit` or `compact_limit`. A smaller GAIA context limit takes precedence. Duplicate identity uses a content hash when available, then a source-scoped entry ID, then content type and text. Failed retrievals contribute no entries; an explicit successful empty response remains distinct from an unavailable or skipped retrieval.
|
|
115
|
+
|
|
112
116
|
The receipts for this loop aren't a separate claim: RAG-injected tokens are a recorded column in the lex-llm-ledger aggregates already published in [docs/curation-production-metrics.md](docs/curation-production-metrics.md).
|
|
113
117
|
|
|
114
118
|
### And everything else you'd expect from a production gateway
|
|
@@ -33,6 +33,17 @@ module Legion
|
|
|
33
33
|
|
|
34
34
|
Canonical = Legion::Extensions::Llm::Canonical
|
|
35
35
|
|
|
36
|
+
# JSON Unicode escapes keep raw SSE byte buffers safe to serialize as
|
|
37
|
+
# JSON again, even when an HTTP client labels them ASCII-8BIT. Escape
|
|
38
|
+
# only at the wire boundary; canonical values and decoded strings stay
|
|
39
|
+
# intact. UTF-16 code units preserve non-BMP characters (RFC 8259 §7).
|
|
40
|
+
def self.format_sse_event(event:, payload:, **)
|
|
41
|
+
json = Legion::JSON.dump(payload).encode(Encoding::US_ASCII, fallback: lambda { |character|
|
|
42
|
+
character.encode(Encoding::UTF_16BE).unpack('n*').map { |unit| format('\\u%04x', unit) }.join
|
|
43
|
+
})
|
|
44
|
+
"event: #{event}\ndata: #{json}\n\n"
|
|
45
|
+
end
|
|
46
|
+
|
|
36
47
|
# One usage projection for synchronous responses and stream trailers.
|
|
37
48
|
module UsageRendering
|
|
38
49
|
include SharedExtractors
|
|
@@ -572,7 +583,7 @@ module Legion
|
|
|
572
583
|
private
|
|
573
584
|
|
|
574
585
|
def emit(event_name, payload)
|
|
575
|
-
@out <<
|
|
586
|
+
@out << Legion::LLM::API::ClientTranslators::OpenAIResponses.format_sse_event(event: event_name, payload: payload)
|
|
576
587
|
end
|
|
577
588
|
|
|
578
589
|
def next_seq
|
|
@@ -93,7 +93,7 @@ module Legion
|
|
|
93
93
|
rescue StandardError => e
|
|
94
94
|
handle_exception(e, level: :error, handled: false,
|
|
95
95
|
operation: 'llm.api.namespaces.openai.responses.stream', request_id: request_id)
|
|
96
|
-
out <<
|
|
96
|
+
out << Legion::LLM::API::ClientTranslators::OpenAIResponses.format_sse_event(event: 'error', payload: { type: 'server_error', message: e.message })
|
|
97
97
|
end
|
|
98
98
|
else
|
|
99
99
|
# N×N: Canonical path — responses body is already translated
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
require 'securerandom'
|
|
4
4
|
require 'legion/logging/helper'
|
|
5
5
|
require 'legion/llm/types'
|
|
6
|
+
require 'legion/llm/api/client_translators/openai_responses'
|
|
6
7
|
|
|
7
8
|
module Legion
|
|
8
9
|
module LLM
|
|
@@ -88,7 +89,9 @@ module Legion
|
|
|
88
89
|
Responses.stream_response(out, executor, request_id: request_id, model: model, upstream_body: body)
|
|
89
90
|
rescue StandardError => e
|
|
90
91
|
handle_exception(e, level: :error, handled: false, operation: 'llm.api.openai.responses.stream', request_id: request_id)
|
|
91
|
-
out <<
|
|
92
|
+
out << Legion::LLM::API::ClientTranslators::OpenAIResponses.format_sse_event(
|
|
93
|
+
event: 'error', payload: { type: 'server_error', message: e.message }
|
|
94
|
+
)
|
|
92
95
|
end
|
|
93
96
|
else
|
|
94
97
|
pipeline_response = executor.call_responses(body: body, stream: false)
|
|
@@ -369,7 +372,7 @@ module Legion
|
|
|
369
372
|
end
|
|
370
373
|
|
|
371
374
|
def self.sse_event(name, payload)
|
|
372
|
-
|
|
375
|
+
Legion::LLM::API::ClientTranslators::OpenAIResponses.format_sse_event(event: name, payload: payload)
|
|
373
376
|
end
|
|
374
377
|
|
|
375
378
|
def self.build_output_tool_calls(pipeline_response)
|
|
@@ -406,44 +406,43 @@ module Legion
|
|
|
406
406
|
payload = archived_history_payload(messages, conversation_id: conversation_id)
|
|
407
407
|
return false if payload[:content].empty?
|
|
408
408
|
|
|
409
|
-
if defined?(::Legion::Apollo::Local) && ::Legion::Apollo::Local.started?
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
log.debug("[llm][context_curator] action=drop_and_archive.skipped reason=apollo_unavailable conversation_id=#{conversation_id}")
|
|
409
|
+
result = if defined?(::Legion::Apollo::Local) && ::Legion::Apollo::Local.started?
|
|
410
|
+
::Legion::Apollo::Local.ingest(
|
|
411
|
+
content: payload[:content],
|
|
412
|
+
tags: payload[:tags],
|
|
413
|
+
source_channel: 'llm_context_curator',
|
|
414
|
+
confidence: 0.75,
|
|
415
|
+
metadata: payload[:metadata]
|
|
416
|
+
)
|
|
417
|
+
elsif defined?(::Legion::Apollo) && ::Legion::Apollo.respond_to?(:ingest)
|
|
418
|
+
::Legion::Apollo.ingest(
|
|
419
|
+
content: payload[:content],
|
|
420
|
+
content_type: 'conversation_turn',
|
|
421
|
+
tags: payload[:tags],
|
|
422
|
+
source_channel: 'llm_context_curator',
|
|
423
|
+
knowledge_domain: 'conversation_history',
|
|
424
|
+
context: payload[:metadata]
|
|
425
|
+
)
|
|
426
|
+
elsif defined?(::Legion::Extensions::Apollo::Runners::Knowledge) &&
|
|
427
|
+
::Legion::Extensions::Apollo::Runners::Knowledge.respond_to?(:handle_ingest)
|
|
428
|
+
::Legion::Extensions::Apollo::Runners::Knowledge.handle_ingest(
|
|
429
|
+
content: payload[:content],
|
|
430
|
+
content_type: 'conversation_turn',
|
|
431
|
+
tags: payload[:tags],
|
|
432
|
+
source_agent: 'legion-llm',
|
|
433
|
+
source_channel: 'llm_context_curator',
|
|
434
|
+
knowledge_domain: 'conversation_history',
|
|
435
|
+
context: payload[:metadata]
|
|
436
|
+
)
|
|
437
|
+
else
|
|
438
|
+
log.debug("[llm][context_curator] action=drop_and_archive.skipped reason=apollo_unavailable conversation_id=#{conversation_id}")
|
|
439
|
+
return false
|
|
440
|
+
end
|
|
441
|
+
|
|
442
|
+
return true if archive_persisted?(result)
|
|
443
|
+
|
|
444
|
+
log.warn("[llm][context_curator] action=archive_unconfirmed conversation_id=#{conversation_id} " \
|
|
445
|
+
"result_type=#{result.class} policy=retain_history")
|
|
447
446
|
false
|
|
448
447
|
rescue StandardError => e
|
|
449
448
|
handle_exception(e, level: :warn, operation: 'llm.context_curator.archive_conversation_history',
|
|
@@ -451,6 +450,35 @@ module Legion
|
|
|
451
450
|
false
|
|
452
451
|
end
|
|
453
452
|
|
|
453
|
+
def archive_persisted?(result)
|
|
454
|
+
return false unless result.is_a?(Hash) && result[:success] == true && result[:error].nil?
|
|
455
|
+
return persisted_archive_entry?(result) unless [:all, 'all'].include?(result[:mode])
|
|
456
|
+
|
|
457
|
+
# Facade success can mean only that an async publication succeeded.
|
|
458
|
+
# Its documented children are individual local/direct/async outcomes.
|
|
459
|
+
results = result[:results]
|
|
460
|
+
results.is_a?(Array) && results.any? { |entry| persisted_archive_entry?(entry) }
|
|
461
|
+
end
|
|
462
|
+
|
|
463
|
+
def persisted_archive_entry?(result)
|
|
464
|
+
return false unless result.is_a?(Hash) && result[:success] == true && result[:error].nil?
|
|
465
|
+
|
|
466
|
+
case result[:mode]
|
|
467
|
+
when :local, 'local'
|
|
468
|
+
archive_entry_id?(result[:id])
|
|
469
|
+
when :deduplicated, 'deduplicated'
|
|
470
|
+
true # Local dedup confirms existing persistence without returning an ID.
|
|
471
|
+
when nil
|
|
472
|
+
archive_entry_id?(result[:entry_id]) # Knowledge.handle_ingest, including facade direct ingestion.
|
|
473
|
+
else
|
|
474
|
+
false
|
|
475
|
+
end
|
|
476
|
+
end
|
|
477
|
+
|
|
478
|
+
def archive_entry_id?(id)
|
|
479
|
+
(id.is_a?(Integer) && id.positive?) || (id.is_a?(String) && !id.strip.empty?)
|
|
480
|
+
end
|
|
481
|
+
|
|
454
482
|
def archived_history_payload(messages, conversation_id:)
|
|
455
483
|
seqs = messages.filter_map { |msg| msg[:seq] }
|
|
456
484
|
{
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'legion/logging/helper'
|
|
4
|
+
require 'legion/llm/content_hash'
|
|
4
5
|
require_relative 'logging'
|
|
5
6
|
|
|
6
7
|
module Legion
|
|
@@ -195,8 +196,7 @@ module Legion
|
|
|
195
196
|
|
|
196
197
|
general = apollo_retrieve_general(query: query, limit: limit, confidence: confidence)
|
|
197
198
|
history = apollo_retrieve_conversation_history(query: query, limit: limit, confidence: confidence)
|
|
198
|
-
|
|
199
|
-
filter_excluded_source_agents(result)
|
|
199
|
+
merge_apollo_results(general, history, limit: limit)
|
|
200
200
|
end
|
|
201
201
|
|
|
202
202
|
def filter_excluded_source_agents(result)
|
|
@@ -204,7 +204,7 @@ module Legion
|
|
|
204
204
|
return result if excluded.empty?
|
|
205
205
|
|
|
206
206
|
entries = Array(result[:entries])
|
|
207
|
-
filtered = entries.reject { |e| excluded.include?(e[:source_agent].to_s) }
|
|
207
|
+
filtered = entries.reject { |e| excluded.include?((e[:source_agent] || e['source_agent']).to_s) }
|
|
208
208
|
if filtered.size < entries.size
|
|
209
209
|
log.debug(
|
|
210
210
|
"[llm][steps][rag_context] action=source_agent_filter excluded=#{entries.size - filtered.size} " \
|
|
@@ -237,10 +237,10 @@ module Legion
|
|
|
237
237
|
end
|
|
238
238
|
|
|
239
239
|
def apollo_retrieve_conversation_history(query:, limit:, confidence:)
|
|
240
|
-
return
|
|
240
|
+
return nil unless conversation_history_retrieval_enabled?
|
|
241
241
|
|
|
242
242
|
conversation_id = @request.conversation_id
|
|
243
|
-
return
|
|
243
|
+
return nil if conversation_id.to_s.empty?
|
|
244
244
|
|
|
245
245
|
tags = ['llm_conversation_history', "conversation:#{conversation_id}"]
|
|
246
246
|
log_step_debug(:rag_context, :apollo_history_query, limit: limit, tag_count: tags.size)
|
|
@@ -260,40 +260,67 @@ module Legion
|
|
|
260
260
|
tags: tags,
|
|
261
261
|
domain: 'conversation_history'
|
|
262
262
|
)
|
|
263
|
-
else
|
|
264
|
-
empty_apollo_result
|
|
265
263
|
end
|
|
266
264
|
rescue StandardError => e
|
|
267
265
|
handle_exception(e, level: :warn, operation: 'llm.pipeline.steps.rag_context.apollo_history_retrieve',
|
|
268
266
|
conversation_id: conversation_id)
|
|
269
|
-
|
|
267
|
+
nil
|
|
270
268
|
end
|
|
271
269
|
|
|
272
270
|
def conversation_history_retrieval_enabled?
|
|
273
271
|
Legion::Settings[:llm][:rag][:conversation_history_enabled] == true
|
|
274
272
|
end
|
|
275
273
|
|
|
276
|
-
def merge_apollo_results(*results)
|
|
277
|
-
|
|
278
|
-
{
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
274
|
+
def merge_apollo_results(*results, limit:)
|
|
275
|
+
normalized = results.map { |result| normalize_apollo_result(result) }
|
|
276
|
+
entries = normalized.flat_map { |result| result[:entries] }
|
|
277
|
+
result = filter_excluded_source_agents({
|
|
278
|
+
success: normalized.any? { |retrieval| retrieval[:success] },
|
|
279
|
+
entries: entries,
|
|
280
|
+
count: entries.size
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
# Preserve retrieval order. Excluded sources cannot consume the
|
|
284
|
+
# shared budget or hide an allowed copy of the same fact.
|
|
285
|
+
seen = Set.new
|
|
286
|
+
entries = result[:entries].reject do |entry|
|
|
287
|
+
identity = apollo_entry_identity(entry)
|
|
288
|
+
identity && !seen.add?(identity)
|
|
289
|
+
end.first(limit)
|
|
290
|
+
result.merge(entries: entries, count: entries.size)
|
|
283
291
|
end
|
|
284
292
|
|
|
285
|
-
def
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
293
|
+
def normalize_apollo_result(result)
|
|
294
|
+
case result
|
|
295
|
+
when Hash
|
|
296
|
+
entries = result[:success] == false ? [] : (result[:entries] || [])
|
|
297
|
+
success = result[:success] == true
|
|
298
|
+
when Array
|
|
299
|
+
entries = result
|
|
300
|
+
success = false
|
|
301
|
+
when nil
|
|
302
|
+
entries = []
|
|
303
|
+
success = false
|
|
290
304
|
else
|
|
291
|
-
Array
|
|
305
|
+
raise ArgumentError, 'Apollo retrieval must return a Hash, Array or nil'
|
|
292
306
|
end
|
|
307
|
+
raise ArgumentError, 'Apollo retrieval entries must be an Array of Hashes' unless entries.is_a?(Array) && entries.all?(Hash)
|
|
308
|
+
|
|
309
|
+
# Empty arrays/nil are fallback results, not evidence of a successful
|
|
310
|
+
# retrieval. An explicit success envelope can represent zero hits.
|
|
311
|
+
{ success: success || entries.any?, entries: entries }
|
|
293
312
|
end
|
|
294
313
|
|
|
295
|
-
def
|
|
296
|
-
|
|
314
|
+
def apollo_entry_identity(entry)
|
|
315
|
+
fields = entry.transform_keys(&:to_sym)
|
|
316
|
+
content_hash = fields[:content_hash]
|
|
317
|
+
return [:content_hash, content_hash] unless content_hash.to_s.empty?
|
|
318
|
+
|
|
319
|
+
id = fields[:id]
|
|
320
|
+
return [:source_id, fields[:source].to_s, id] unless id.to_s.empty?
|
|
321
|
+
|
|
322
|
+
digest = Legion::LLM::ContentHash.call(fields[:content])
|
|
323
|
+
[:content, fields[:content_type].to_s, digest] if digest
|
|
297
324
|
end
|
|
298
325
|
|
|
299
326
|
# G3: pipeline messages are Canonical::Message — the query is the
|
data/lib/legion/llm/version.rb
CHANGED