lex-apollo 0.4.44 → 0.4.45
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 +33 -0
- data/README.md +72 -14
- data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -41
- data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
- data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
- data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
- data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
- data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +4 -16
- data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
- data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
- data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
- data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
- data/lib/legion/extensions/apollo/api.rb +96 -41
- data/lib/legion/extensions/apollo/client.rb +20 -9
- data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
- data/lib/legion/extensions/apollo/helpers/capability.rb +10 -51
- data/lib/legion/extensions/apollo/helpers/confidence.rb +8 -52
- data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
- data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
- data/lib/legion/extensions/apollo/helpers/graph_query.rb +99 -43
- data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
- data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
- data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
- data/lib/legion/extensions/apollo/helpers/writeback.rb +64 -102
- data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
- data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
- data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
- data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +110 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +87 -136
- data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
- data/lib/legion/extensions/apollo/runners/maintenance.rb +151 -64
- data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
- data/lib/legion/extensions/apollo/runners/request.rb +51 -46
- data/lib/legion/extensions/apollo/runners/search.rb +88 -0
- data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
- data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
- data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
- data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
- data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +26 -24
- data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
- data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
- data/spec/legion/extensions/apollo/api_spec.rb +240 -8
- data/spec/legion/extensions/apollo/contradiction_spec.rb +28 -50
- data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
- data/spec/legion/extensions/apollo/helpers/capability_spec.rb +24 -27
- data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
- data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
- data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +108 -0
- data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
- data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
- data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
- data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +73 -74
- data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +32 -3
- data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
- data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
- data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
- data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +124 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +23 -7
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -77
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +138 -6
- data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
- data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +314 -655
- data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +11 -2
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +33 -65
- data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
- data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
- data/spec/legion/extensions/apollo/runners/request_spec.rb +120 -98
- data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
- data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
- data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
- data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
- data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
- data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
- data/spec/spec_helper.rb +13 -15
- metadata +40 -14
- data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
- data/spec/legion/extensions/apollo/actors/contradiction_scanner_spec.rb +0 -38
- data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
- data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
- data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
- data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +0 -39
- data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
- data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
- data/spec/legion/extensions/apollo/helpers/entity_watchdog_spec.rb +0 -64
|
@@ -1,41 +1,72 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
require 'legion/logging/helper'
|
|
4
|
+
require 'legion/settings/helper'
|
|
5
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
6
|
+
require 'legion/extensions/apollo/helpers/storage'
|
|
4
7
|
|
|
5
8
|
module Legion
|
|
6
9
|
module Extensions
|
|
7
10
|
module Apollo
|
|
8
11
|
module Runners
|
|
9
12
|
module Expertise
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
include Legion::Logging::Helper
|
|
14
|
+
include Legion::Settings::Helper
|
|
15
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
16
|
+
extend Legion::Extensions::Apollo::Helpers::Storage
|
|
17
|
+
extend self
|
|
18
|
+
|
|
19
|
+
def get_expertise(domain:, min_proficiency: settings[:expertise][:initial_proficiency], **)
|
|
20
|
+
model = data_model_expertise
|
|
21
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
22
|
+
|
|
23
|
+
entries = model.where(domain: domain).where { proficiency >= min_proficiency }.order(Sequel.desc(:proficiency)).all
|
|
24
|
+
formatted = entries.map(&:values)
|
|
25
|
+
{ success: true, domain: domain, min_proficiency: min_proficiency, entries: formatted, count: formatted.size }
|
|
26
|
+
rescue Sequel::Error => e
|
|
27
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.get_expertise', domain: domain)
|
|
28
|
+
{ success: false, error: e.message, entries: [], count: 0 }
|
|
12
29
|
end
|
|
13
30
|
|
|
14
|
-
def domains_at_risk(min_agents:
|
|
15
|
-
|
|
31
|
+
def domains_at_risk(min_agents: settings[:expertise][:min_agents_at_risk], **)
|
|
32
|
+
model = data_model_expertise
|
|
33
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
34
|
+
|
|
35
|
+
agent_count = Sequel.function(:count, :agent_id).distinct
|
|
36
|
+
domains = model.select_group(:domain).select_append(agent_count.as(:agent_count))
|
|
37
|
+
.having(agent_count < min_agents).order(:domain).naked.all
|
|
38
|
+
{ success: true, min_agents: min_agents, domains: domains, count: domains.size }
|
|
39
|
+
rescue Sequel::Error => e
|
|
40
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.domains_at_risk')
|
|
41
|
+
{ success: false, error: e.message, domains: [], count: 0 }
|
|
16
42
|
end
|
|
17
43
|
|
|
18
44
|
def agent_profile(agent_id:, **)
|
|
19
|
-
|
|
45
|
+
model = data_model_expertise
|
|
46
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
47
|
+
|
|
48
|
+
entries = model.where(agent_id: agent_id).order(:domain).all.map(&:values)
|
|
49
|
+
{ success: true, agent_id: agent_id, entries: entries, count: entries.size }
|
|
50
|
+
rescue Sequel::Error => e
|
|
51
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.agent_profile', agent_id: agent_id)
|
|
52
|
+
{ success: false, error: e.message, agent_id: agent_id, entries: [], count: 0 }
|
|
20
53
|
end
|
|
21
54
|
|
|
22
55
|
def aggregate(**)
|
|
23
|
-
|
|
56
|
+
model = data_model_entry
|
|
57
|
+
expertise_model = data_model_expertise
|
|
58
|
+
unless model && expertise_model
|
|
24
59
|
log.warn('Apollo Expertise.aggregate skipped: apollo_data_not_available')
|
|
25
60
|
return { success: false, error: 'apollo_data_not_available' }
|
|
26
61
|
end
|
|
27
62
|
|
|
28
|
-
entries =
|
|
29
|
-
.select(:source_agent, :tags, :confidence)
|
|
30
|
-
.exclude(source_agent: nil)
|
|
31
|
-
.all
|
|
63
|
+
entries = model.select(:source_agent, :knowledge_domain, :tags, :confidence).exclude(source_agent: nil).all
|
|
32
64
|
log.debug("Apollo Expertise.aggregate entries=#{entries.size}")
|
|
33
65
|
|
|
34
66
|
agent_set = Set.new
|
|
35
67
|
domain_set = Set.new
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
upsert_expertise_group(group)
|
|
68
|
+
expertise_groups(entries: entries).each_value do |group|
|
|
69
|
+
expertise_upsert_group(model: expertise_model, group: group)
|
|
39
70
|
agent_set << group[:agent_id]
|
|
40
71
|
domain_set << group[:domain]
|
|
41
72
|
end
|
|
@@ -47,39 +78,37 @@ module Legion
|
|
|
47
78
|
{ success: false, error: e.message }
|
|
48
79
|
end
|
|
49
80
|
|
|
50
|
-
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
def expertise_groups(entries:, **)
|
|
51
84
|
entries.each_with_object({}) do |entry, groups|
|
|
52
85
|
agent = entry.source_agent
|
|
53
|
-
domain = entry.
|
|
54
|
-
|
|
86
|
+
domain = entry.knowledge_domain ||
|
|
87
|
+
storage_deserialize_tags(tags: entry.tags).first || 'general'
|
|
88
|
+
key = [agent, domain]
|
|
55
89
|
groups[key] ||= { agent_id: agent, domain: domain, confidences: [] }
|
|
56
90
|
groups[key][:confidences] << entry.confidence.to_f
|
|
57
91
|
end
|
|
58
92
|
end
|
|
59
93
|
|
|
60
|
-
def
|
|
94
|
+
def expertise_upsert_group(model:, group:, **)
|
|
61
95
|
count = group[:confidences].size
|
|
62
|
-
proficiency = expertise_proficiency(group[:confidences])
|
|
63
|
-
existing =
|
|
64
|
-
.where(agent_id: group[:agent_id], domain: group[:domain]).first
|
|
96
|
+
proficiency = expertise_proficiency(confidences: group[:confidences])
|
|
97
|
+
existing = model.first(agent_id: group[:agent_id], domain: group[:domain])
|
|
65
98
|
|
|
66
99
|
if existing
|
|
67
100
|
existing.update(proficiency: proficiency, entry_count: count, last_active_at: Time.now)
|
|
68
101
|
else
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
proficiency: proficiency, entry_count: count, last_active_at: Time.now
|
|
72
|
-
)
|
|
102
|
+
model.create(agent_id: group[:agent_id], domain: group[:domain], proficiency: proficiency,
|
|
103
|
+
entry_count: count, last_active_at: Time.now)
|
|
73
104
|
end
|
|
74
105
|
end
|
|
75
106
|
|
|
76
|
-
def expertise_proficiency(confidences)
|
|
107
|
+
def expertise_proficiency(confidences:, **)
|
|
77
108
|
avg = confidences.sum / confidences.size
|
|
78
|
-
cap =
|
|
109
|
+
cap = settings[:expertise][:proficiency_cap]
|
|
79
110
|
[avg * Math.log2(confidences.size + 1), cap].min
|
|
80
111
|
end
|
|
81
|
-
|
|
82
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
83
112
|
end
|
|
84
113
|
end
|
|
85
114
|
end
|
|
@@ -1,54 +1,47 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require 'legion/llm/inference'
|
|
4
|
+
require 'legion/logging/helper'
|
|
5
|
+
require 'legion/settings/helper'
|
|
6
|
+
require 'legion/json'
|
|
7
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
8
|
+
require 'legion/extensions/apollo/runners/entity_extractor'
|
|
9
|
+
require 'legion/extensions/apollo/runners/knowledge'
|
|
10
|
+
|
|
3
11
|
module Legion
|
|
4
12
|
module Extensions
|
|
5
13
|
module Apollo
|
|
6
14
|
module Runners
|
|
7
15
|
module Gas
|
|
8
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
9
16
|
include Legion::Logging::Helper
|
|
10
17
|
include Legion::JSON::Helper
|
|
11
|
-
|
|
12
|
-
extend Legion::
|
|
13
|
-
extend Legion::JSON::Helper
|
|
18
|
+
include Legion::Settings::Helper
|
|
19
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
14
20
|
|
|
15
21
|
RELATION_TYPES = %w[
|
|
16
22
|
similar_to contradicts depends_on causes
|
|
17
23
|
part_of supersedes supports_by extends
|
|
18
24
|
].freeze
|
|
19
25
|
|
|
20
|
-
|
|
21
|
-
SYNTHESIS_CONFIDENCE_CAP = 0.7
|
|
22
|
-
MAX_ANTICIPATIONS = 3
|
|
23
|
-
|
|
24
|
-
module_function
|
|
25
|
-
|
|
26
|
-
def json_load(str)
|
|
27
|
-
json_parse(str)
|
|
28
|
-
end
|
|
26
|
+
extend self
|
|
29
27
|
|
|
30
|
-
def
|
|
31
|
-
|
|
32
|
-
def max_anticipations = Legion::Extensions::Apollo.settings[:gas][:max_anticipations]
|
|
33
|
-
def similar_entries_limit = Legion::Extensions::Apollo.settings[:gas][:similar_entries_limit]
|
|
34
|
-
def fallback_confidence = Legion::Extensions::Apollo.settings[:gas][:fallback_confidence]
|
|
35
|
-
|
|
36
|
-
def process(audit_event)
|
|
37
|
-
unless processable?(audit_event)
|
|
28
|
+
def process(**audit_event)
|
|
29
|
+
unless gas_processable?(audit_event)
|
|
38
30
|
log.debug('GAS process skipped reason=no_content')
|
|
39
|
-
return { phases_completed: 0, reason: 'no content' }
|
|
31
|
+
return { success: true, phases_completed: 0, reason: 'no content' }
|
|
40
32
|
end
|
|
41
33
|
|
|
42
34
|
log.debug("GAS process start request_id=#{audit_event[:request_id] || 'nil'} messages=#{Array(audit_event[:messages]).size} response_length=#{audit_event[:response_content].to_s.length}") # rubocop:disable Layout/LineLength
|
|
43
35
|
|
|
44
|
-
facts =
|
|
45
|
-
entities =
|
|
46
|
-
relations =
|
|
47
|
-
synthesis =
|
|
48
|
-
deposit_result =
|
|
49
|
-
anticipations =
|
|
36
|
+
facts = gas_phase_comprehend(audit_event)
|
|
37
|
+
entities = gas_phase_extract(audit_event, facts)
|
|
38
|
+
relations = gas_phase_relate(facts: facts)
|
|
39
|
+
synthesis = gas_phase_synthesize(facts, relations)
|
|
40
|
+
deposit_result = gas_phase_deposit(facts: facts, relations: relations, synthesis: synthesis, audit_event: audit_event)
|
|
41
|
+
anticipations = gas_phase_anticipate(facts, synthesis)
|
|
50
42
|
|
|
51
43
|
result = {
|
|
44
|
+
success: deposit_result[:failed].zero? && deposit_result[:relations_failed].zero?,
|
|
52
45
|
phases_completed: 6,
|
|
53
46
|
facts: facts.length,
|
|
54
47
|
entities: entities.length,
|
|
@@ -61,49 +54,40 @@ module Legion
|
|
|
61
54
|
result
|
|
62
55
|
rescue StandardError => e
|
|
63
56
|
handle_exception(e, level: :error, operation: 'apollo.gas.process')
|
|
64
|
-
{ phases_completed: 0, error: e.message }
|
|
57
|
+
{ success: false, phases_completed: 0, error: e.message }
|
|
65
58
|
end
|
|
66
59
|
|
|
67
|
-
|
|
60
|
+
private
|
|
61
|
+
|
|
62
|
+
def gas_processable?(event)
|
|
68
63
|
event[:messages]&.any? == true && !event[:response_content].nil?
|
|
69
64
|
end
|
|
70
65
|
|
|
71
66
|
# Phase 1: Comprehend - extract typed facts from the exchange
|
|
72
|
-
def
|
|
67
|
+
def gas_phase_comprehend(audit_event)
|
|
73
68
|
messages = audit_event[:messages]
|
|
74
69
|
response = audit_event[:response_content]
|
|
75
70
|
|
|
76
|
-
mode =
|
|
71
|
+
mode = Legion::LLM.started? ? :llm : :mechanical
|
|
77
72
|
log.debug("GAS phase_comprehend mode=#{mode} messages=#{Array(messages).size} response_length=#{response.to_s.length}")
|
|
78
|
-
facts = mode == :llm ?
|
|
73
|
+
facts = mode == :llm ? gas_llm_comprehend(messages, response) : gas_mechanical_comprehend(messages, response)
|
|
79
74
|
log.debug("GAS phase_comprehend facts=#{facts.size}")
|
|
80
75
|
facts
|
|
81
76
|
end
|
|
82
77
|
|
|
83
78
|
# Phase 2: Extract - entity extraction (delegates to existing EntityExtractor)
|
|
84
|
-
def
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return []
|
|
88
|
-
end
|
|
79
|
+
def gas_phase_extract(audit_event, _facts)
|
|
80
|
+
result = Legion::Extensions::Apollo::Runners::EntityExtractor.extract_entities(text: audit_event[:response_content])
|
|
81
|
+
raise IOError, "Apollo entity extraction failed: #{result[:error]}" unless result[:success]
|
|
89
82
|
|
|
90
|
-
|
|
91
|
-
entities = result[:success] ? (result[:entities] || []) : []
|
|
83
|
+
entities = result[:entities]
|
|
92
84
|
log.debug("GAS phase_extract success=#{result[:success]} entities=#{entities.size}")
|
|
93
85
|
entities
|
|
94
|
-
rescue StandardError => e
|
|
95
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_extract')
|
|
96
|
-
[]
|
|
97
86
|
end
|
|
98
87
|
|
|
99
88
|
# Phase 3: Relate - classify relationships between new and existing entries
|
|
100
|
-
def
|
|
101
|
-
|
|
102
|
-
log.debug('GAS phase_relate skipped reason=knowledge_runner_unavailable')
|
|
103
|
-
return []
|
|
104
|
-
end
|
|
105
|
-
|
|
106
|
-
existing = fetch_similar_entries(facts)
|
|
89
|
+
def gas_phase_relate(facts:, **)
|
|
90
|
+
existing = gas_fetch_similar_entries(facts: facts)
|
|
107
91
|
if existing.empty?
|
|
108
92
|
log.debug("GAS phase_relate skipped reason=no_existing_entries facts=#{facts.size}")
|
|
109
93
|
return []
|
|
@@ -112,7 +96,7 @@ module Legion
|
|
|
112
96
|
relations = []
|
|
113
97
|
facts.each do |fact|
|
|
114
98
|
existing.each do |entry|
|
|
115
|
-
relation =
|
|
99
|
+
relation = gas_classify_relation(fact, entry)
|
|
116
100
|
relations << relation if relation
|
|
117
101
|
end
|
|
118
102
|
end
|
|
@@ -121,32 +105,24 @@ module Legion
|
|
|
121
105
|
end
|
|
122
106
|
|
|
123
107
|
# Phase 4: Synthesize - generate derivative knowledge
|
|
124
|
-
def
|
|
108
|
+
def gas_phase_synthesize(facts, _relations)
|
|
125
109
|
if facts.length < 2
|
|
126
110
|
log.debug("GAS phase_synthesize skipped reason=insufficient_facts facts=#{facts.length}")
|
|
127
111
|
return []
|
|
128
112
|
end
|
|
129
|
-
unless
|
|
113
|
+
unless Legion::LLM.started?
|
|
130
114
|
log.debug('GAS phase_synthesize skipped reason=llm_unavailable')
|
|
131
115
|
return []
|
|
132
116
|
end
|
|
133
117
|
|
|
134
|
-
synthesis =
|
|
118
|
+
synthesis = gas_llm_synthesize(facts)
|
|
135
119
|
log.debug("GAS phase_synthesize synthesis=#{synthesis.size}")
|
|
136
120
|
synthesis
|
|
137
|
-
rescue StandardError => e
|
|
138
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_synthesize')
|
|
139
|
-
[]
|
|
140
121
|
end
|
|
141
122
|
|
|
142
123
|
# Phase 5: Deposit entries, then link successfully stored facts.
|
|
143
|
-
def
|
|
124
|
+
def gas_phase_deposit(facts:, relations:, synthesis:, audit_event:, **)
|
|
144
125
|
counts = { deposited: 0, failed: 0, facts: 0, synthesis: 0 }
|
|
145
|
-
unless defined?(Legion::Extensions::Apollo::Runners::Knowledge)
|
|
146
|
-
return counts.merge(failed: facts.size + synthesis.size, relations: 0,
|
|
147
|
-
relations_failed: relations.size, relations_skipped: 0)
|
|
148
|
-
end
|
|
149
|
-
|
|
150
126
|
fact_ids = Array.new(facts.size)
|
|
151
127
|
source_ids = {}
|
|
152
128
|
{ facts: facts, synthesis: synthesis }.each do |kind, entries|
|
|
@@ -189,13 +165,13 @@ module Legion
|
|
|
189
165
|
def gas_deposit_relations(relations:, source_ids:)
|
|
190
166
|
counts = { relations: 0, relations_failed: 0, relations_skipped: 0 }
|
|
191
167
|
return counts if relations.empty?
|
|
192
|
-
unless
|
|
193
|
-
|
|
168
|
+
unless !data_model_entry.nil? &&
|
|
169
|
+
!data_model_relation.nil?
|
|
194
170
|
return counts.merge(relations_failed: relations.size)
|
|
195
171
|
end
|
|
196
172
|
|
|
197
|
-
entry_model =
|
|
198
|
-
relation_model =
|
|
173
|
+
entry_model = data_model_entry
|
|
174
|
+
relation_model = data_model_relation
|
|
199
175
|
seen = {}
|
|
200
176
|
relations.each do |relation|
|
|
201
177
|
type = relation[:relation_type].to_s
|
|
@@ -231,58 +207,52 @@ module Legion
|
|
|
231
207
|
def gas_relation_accepted?(type:, confidence:)
|
|
232
208
|
Legion::Extensions::Apollo::Helpers::Confidence::RELATION_TYPES.include?(type) &&
|
|
233
209
|
confidence.is_a?(Numeric) && confidence.real? && confidence.finite? &&
|
|
234
|
-
confidence.between?(relate_confidence_gate, 1.0)
|
|
210
|
+
confidence.between?(settings[:gas][:relate_confidence_gate], 1.0)
|
|
235
211
|
end
|
|
236
|
-
private_class_method :gas_deposit_relations, :gas_relation_accepted?
|
|
237
212
|
|
|
238
213
|
# Phase 6: Anticipate - pre-cache likely follow-up questions
|
|
239
|
-
def
|
|
214
|
+
def gas_phase_anticipate(facts, _synthesis)
|
|
240
215
|
if facts.empty?
|
|
241
216
|
log.debug('GAS phase_anticipate skipped reason=no_facts')
|
|
242
217
|
return []
|
|
243
218
|
end
|
|
244
|
-
unless
|
|
219
|
+
unless Legion::LLM.started?
|
|
245
220
|
log.debug('GAS phase_anticipate skipped reason=llm_unavailable')
|
|
246
221
|
return []
|
|
247
222
|
end
|
|
248
223
|
|
|
249
|
-
anticipations =
|
|
224
|
+
anticipations = gas_llm_anticipate(facts)
|
|
250
225
|
log.debug("GAS phase_anticipate anticipations=#{anticipations.size}")
|
|
251
226
|
anticipations
|
|
252
|
-
rescue StandardError => e
|
|
253
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_anticipate')
|
|
254
|
-
[]
|
|
255
227
|
end
|
|
256
228
|
|
|
257
|
-
def
|
|
258
|
-
lim = similar_entries_limit
|
|
259
|
-
min_conf =
|
|
229
|
+
def gas_fetch_similar_entries(facts:, **)
|
|
230
|
+
lim = settings[:gas][:similar_entries_limit]
|
|
231
|
+
min_conf = settings[:query][:default_min_confidence]
|
|
260
232
|
entries = []
|
|
261
233
|
facts.each do |fact|
|
|
262
|
-
result = Runners::Knowledge.retrieve_relevant(
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
234
|
+
result = Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(
|
|
235
|
+
query: fact[:content], limit: lim, min_confidence: min_conf
|
|
236
|
+
)
|
|
237
|
+
raise IOError, "Apollo semantic retrieval failed: #{result[:error]}" unless result[:success]
|
|
238
|
+
|
|
239
|
+
entries.concat(result[:entries])
|
|
267
240
|
end
|
|
268
241
|
unique = entries.uniq { |e| e[:id] }
|
|
269
242
|
log.debug("GAS fetch_similar_entries facts=#{facts.size} entries=#{unique.size}")
|
|
270
243
|
unique
|
|
271
244
|
end
|
|
272
245
|
|
|
273
|
-
def
|
|
274
|
-
fb_conf = fallback_confidence
|
|
275
|
-
if
|
|
276
|
-
|
|
246
|
+
def gas_classify_relation(fact, entry)
|
|
247
|
+
fb_conf = settings[:gas][:fallback_confidence]
|
|
248
|
+
if Legion::LLM.started?
|
|
249
|
+
gas_llm_classify_relation(fact, entry)
|
|
277
250
|
else
|
|
278
251
|
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fb_conf }
|
|
279
252
|
end
|
|
280
|
-
rescue StandardError => e
|
|
281
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.classify_relation')
|
|
282
|
-
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fallback_confidence }
|
|
283
253
|
end
|
|
284
254
|
|
|
285
|
-
def
|
|
255
|
+
def gas_llm_classify_relation(fact, entry) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
|
|
286
256
|
prompt = <<~PROMPT
|
|
287
257
|
Classify the relationship between these two knowledge entries.
|
|
288
258
|
Valid types: #{RELATION_TYPES.join(', ')}
|
|
@@ -293,7 +263,7 @@ module Legion
|
|
|
293
263
|
Return JSON with relation_type and confidence (0.0-1.0).
|
|
294
264
|
PROMPT
|
|
295
265
|
|
|
296
|
-
result = Legion::LLM::
|
|
266
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
297
267
|
message: prompt.strip,
|
|
298
268
|
schema: {
|
|
299
269
|
type: :object,
|
|
@@ -319,28 +289,25 @@ module Legion
|
|
|
319
289
|
result[:data][:relations] || result.dig(:data, 'relations') || []
|
|
320
290
|
else
|
|
321
291
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
322
|
-
parsed =
|
|
292
|
+
parsed = json_parse(content)
|
|
323
293
|
parsed.is_a?(Hash) ? (parsed[:relations] || parsed['relations'] || []) : []
|
|
324
294
|
end
|
|
325
295
|
best = rels.max_by { |r| r[:confidence] || r['confidence'] || 0 }
|
|
326
296
|
|
|
327
|
-
return
|
|
297
|
+
return gas_fallback_relation(fact, entry) unless best
|
|
328
298
|
|
|
329
299
|
conf = best[:confidence] || best['confidence'] || 0
|
|
330
300
|
rtype = best[:relation_type] || best['relation_type']
|
|
331
|
-
return
|
|
301
|
+
return gas_fallback_relation(fact, entry) if conf < settings[:gas][:relate_confidence_gate] || !RELATION_TYPES.include?(rtype)
|
|
332
302
|
|
|
333
303
|
{ from_content: fact[:content], to_id: entry[:id], relation_type: rtype, confidence: conf }
|
|
334
|
-
rescue StandardError => e
|
|
335
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_classify_relation')
|
|
336
|
-
fallback_relation(fact, entry)
|
|
337
304
|
end
|
|
338
305
|
|
|
339
|
-
def
|
|
340
|
-
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fallback_confidence }
|
|
306
|
+
def gas_fallback_relation(fact, entry)
|
|
307
|
+
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: settings[:gas][:fallback_confidence] }
|
|
341
308
|
end
|
|
342
309
|
|
|
343
|
-
def
|
|
310
|
+
def gas_llm_synthesize(facts)
|
|
344
311
|
facts_text = facts.each_with_index.map { |f, i| "[#{i}] (#{f[:content_type]}) #{f[:content]}" }.join("\n")
|
|
345
312
|
|
|
346
313
|
prompt = <<~PROMPT
|
|
@@ -353,7 +320,7 @@ module Legion
|
|
|
353
320
|
Return JSON with a "synthesis" array where each item has: content (string), content_type (inference/implication/connection), source_indices (array of entry indices used).
|
|
354
321
|
PROMPT
|
|
355
322
|
|
|
356
|
-
result = Legion::LLM::
|
|
323
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
357
324
|
message: prompt.strip,
|
|
358
325
|
schema: {
|
|
359
326
|
type: :object,
|
|
@@ -380,39 +347,36 @@ module Legion
|
|
|
380
347
|
result[:data][:synthesis] || result.dig(:data, 'synthesis') || []
|
|
381
348
|
else
|
|
382
349
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
383
|
-
parsed =
|
|
350
|
+
parsed = json_parse(content)
|
|
384
351
|
parsed.is_a?(Hash) ? (parsed[:synthesis] || parsed['synthesis'] || []) : []
|
|
385
352
|
end
|
|
386
353
|
|
|
387
|
-
items.map { |item|
|
|
388
|
-
rescue StandardError => e
|
|
389
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_synthesize')
|
|
390
|
-
[]
|
|
354
|
+
items.map { |item| gas_build_synthesis_entry(item, facts) }
|
|
391
355
|
end
|
|
392
356
|
|
|
393
|
-
def
|
|
357
|
+
def gas_build_synthesis_entry(item, facts)
|
|
394
358
|
source_indices = item[:source_indices] || item['source_indices'] || []
|
|
395
359
|
source_confs = source_indices.filter_map { |i| facts[i]&.dig(:confidence) }
|
|
396
|
-
fb = fallback_confidence
|
|
397
|
-
geo_mean = source_confs.empty? ? fb :
|
|
360
|
+
fb = settings[:gas][:fallback_confidence]
|
|
361
|
+
geo_mean = source_confs.empty? ? fb : gas_geometric_mean(source_confs)
|
|
398
362
|
|
|
399
363
|
{
|
|
400
364
|
content: item[:content] || item['content'],
|
|
401
365
|
content_type: (item[:content_type] || item['content_type'] || 'inference').to_sym,
|
|
402
366
|
status: :candidate,
|
|
403
|
-
confidence: [geo_mean, synthesis_confidence_cap].min,
|
|
367
|
+
confidence: [geo_mean, settings[:gas][:synthesis_confidence_cap]].min,
|
|
404
368
|
source_indices: source_indices
|
|
405
369
|
}
|
|
406
370
|
end
|
|
407
371
|
|
|
408
|
-
def
|
|
372
|
+
def gas_geometric_mean(values)
|
|
409
373
|
return 0.0 if values.empty?
|
|
410
374
|
|
|
411
375
|
product = values.reduce(1.0) { |acc, v| acc * v }
|
|
412
376
|
product**(1.0 / values.length)
|
|
413
377
|
end
|
|
414
378
|
|
|
415
|
-
def
|
|
379
|
+
def gas_llm_anticipate(facts)
|
|
416
380
|
facts_text = facts.map { |f| "(#{f[:content_type]}) #{f[:content]}" }.join("\n")
|
|
417
381
|
|
|
418
382
|
prompt = <<~PROMPT
|
|
@@ -424,7 +388,7 @@ module Legion
|
|
|
424
388
|
Return JSON with a "questions" array of question strings.
|
|
425
389
|
PROMPT
|
|
426
390
|
|
|
427
|
-
result = Legion::LLM::
|
|
391
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
428
392
|
message: prompt.strip,
|
|
429
393
|
schema: {
|
|
430
394
|
type: :object,
|
|
@@ -440,45 +404,35 @@ module Legion
|
|
|
440
404
|
result[:data][:questions] || result.dig(:data, 'questions') || []
|
|
441
405
|
else
|
|
442
406
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
443
|
-
parsed =
|
|
407
|
+
parsed = json_parse(content)
|
|
444
408
|
parsed.is_a?(Hash) ? (parsed[:questions] || parsed['questions'] || []) : []
|
|
445
409
|
end
|
|
446
|
-
questions = questions.first(max_anticipations)
|
|
410
|
+
questions = questions.first(settings[:gas][:max_anticipations])
|
|
447
411
|
|
|
448
412
|
questions.map do |q|
|
|
449
|
-
|
|
413
|
+
gas_promote_to_pattern_store(question: q, facts: facts)
|
|
450
414
|
{ question: q }
|
|
451
415
|
end
|
|
452
|
-
rescue StandardError => e
|
|
453
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_anticipate')
|
|
454
|
-
[]
|
|
455
416
|
end
|
|
456
417
|
|
|
457
|
-
def
|
|
418
|
+
def gas_promote_to_pattern_store(question:, facts:)
|
|
458
419
|
return unless defined?(Legion::Extensions::Agentic::TBI::PatternStore)
|
|
459
420
|
|
|
460
421
|
Legion::Extensions::Agentic::TBI::PatternStore.promote_candidate(
|
|
461
422
|
intent: question,
|
|
462
423
|
resolution: { source: 'gas_anticipate', facts: facts.map { |f| f[:content] } },
|
|
463
|
-
confidence: fallback_confidence
|
|
424
|
+
confidence: settings[:gas][:fallback_confidence]
|
|
464
425
|
)
|
|
465
426
|
rescue StandardError => e
|
|
466
427
|
handle_exception(e, level: :warn, operation: 'apollo.gas.promote_to_pattern_store')
|
|
467
428
|
nil
|
|
468
429
|
end
|
|
469
430
|
|
|
470
|
-
def
|
|
471
|
-
defined?(Legion::LLM::Pipeline::GaiaCaller)
|
|
472
|
-
rescue StandardError => e
|
|
473
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_available')
|
|
474
|
-
false
|
|
475
|
-
end
|
|
476
|
-
|
|
477
|
-
def mechanical_comprehend(_messages, response)
|
|
431
|
+
def gas_mechanical_comprehend(_messages, response)
|
|
478
432
|
[{ content: response, content_type: :observation }]
|
|
479
433
|
end
|
|
480
434
|
|
|
481
|
-
def
|
|
435
|
+
def gas_llm_comprehend(messages, response)
|
|
482
436
|
prompt = <<~PROMPT
|
|
483
437
|
Extract distinct facts from this exchange. Return JSON array of {content:, content_type:} where content_type is one of: fact, concept, procedure, association.
|
|
484
438
|
|
|
@@ -486,7 +440,7 @@ module Legion
|
|
|
486
440
|
Assistant: #{response}
|
|
487
441
|
PROMPT
|
|
488
442
|
|
|
489
|
-
result = Legion::LLM::
|
|
443
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
490
444
|
message: prompt.strip,
|
|
491
445
|
schema: {
|
|
492
446
|
type: :object,
|
|
@@ -512,7 +466,7 @@ module Legion
|
|
|
512
466
|
result[:data][:facts] || result.dig(:data, 'facts') || []
|
|
513
467
|
else
|
|
514
468
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
515
|
-
parsed =
|
|
469
|
+
parsed = json_parse(content)
|
|
516
470
|
parsed.is_a?(Hash) ? (parsed[:facts] || parsed['facts'] || []) : Array(parsed)
|
|
517
471
|
end
|
|
518
472
|
facts_array.map do |f|
|
|
@@ -521,9 +475,6 @@ module Legion
|
|
|
521
475
|
content_type: (f[:content_type] || f['content_type'] || 'fact').to_sym
|
|
522
476
|
}
|
|
523
477
|
end
|
|
524
|
-
rescue StandardError => e
|
|
525
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_comprehend')
|
|
526
|
-
mechanical_comprehend(messages, response)
|
|
527
478
|
end
|
|
528
479
|
end
|
|
529
480
|
end
|