Raiff1982 commited on
Commit
c2000cd
·
verified ·
1 Parent(s): 42f9df8

Update src/aegis_integration/aegis_bridge.py

Browse files
Files changed (1) hide show
  1. src/aegis_integration/aegis_bridge.py +394 -385
src/aegis_integration/aegis_bridge.py CHANGED
@@ -1,385 +1,394 @@
1
- import importlib
2
- import logging
3
- from typing import Dict, Any, Optional, List
4
-
5
- logger = logging.getLogger(__name__)
6
-
7
- def check_dependencies() -> List[str]:
8
- """Check if all required packages are installed."""
9
- required_packages = [
10
- 'plotly',
11
- 'torch',
12
- 'transformers',
13
- 'pandas',
14
- 'numpy',
15
- 'networkx'
16
- ]
17
- missing = []
18
- for package in required_packages:
19
- try:
20
- importlib.import_module(package)
21
- except ImportError:
22
- missing.append(package)
23
- return missing
24
-
25
- # Check dependencies before importing AEGIS components
26
- missing_packages = check_dependencies()
27
- if missing_packages:
28
- raise ImportError(
29
- f"AEGIS requires the following packages to be installed: {', '.join(missing_packages)}. "
30
- f"Please install them using: pip install {' '.join(missing_packages)}"
31
- )
32
-
33
- from .aegis import AegisCouncil, MetaJudgeAgent, TemporalAgent, VirtueAgent
34
- import sys
35
- from pathlib import Path
36
- sys.path.append(str(Path(__file__).parent.parent))
37
- from ai_core import AICore
38
-
39
- class AegisBridge:
40
- def __init__(self, ai_core: AICore, config: Dict[str, Any]):
41
- self.ai_core = ai_core
42
- self.council = AegisCouncil(config)
43
-
44
- # Register default agents
45
- self.council.register_agent(MetaJudgeAgent("MetaJudgeAgent", self.council.memory, config["meta_judge_weights"]))
46
- self.council.register_agent(TemporalAgent("TemporalAgent", self.council.memory, config["temporal_decay_thresholds"]))
47
- virtue_agent = VirtueAgent("VirtueAgent", self.council.memory, config["virtue_weights"])
48
- virtue_agent.set_federated_trainer(self.council.federated_trainer)
49
- self.council.register_agent(virtue_agent)
50
-
51
- def enhance_response(self, prompt: str, response: str, recursion_depth: int = 0) -> Dict[str, Any]:
52
- """
53
- Enhance Codette's response using AEGIS analysis
54
-
55
- Args:
56
- prompt: Original prompt that generated the response
57
- response: Response to enhance
58
- recursion_depth: Current recursion depth to prevent infinite loops
59
- """
60
- # Prevent infinite enhancement loops
61
- if recursion_depth > 1:
62
- return {
63
- "original_response": response,
64
- "enhanced_response": response,
65
- "enhancement_status": "recursion_limit_reached"
66
- }
67
-
68
- # Skip enhancement for certain types of responses
69
- if any([
70
- "I need to think about that more clearly" in response, # Already in refinement
71
- "[ERROR]" in response, # Error messages
72
- len(response.strip()) < 10, # Too short to meaningfully enhance
73
- "Consciousness Context:" in response # Internal context
74
- ]):
75
- return {
76
- "original_response": response,
77
- "enhanced_response": response,
78
- "enhancement_status": "skipped"
79
- }
80
-
81
- input_data = {
82
- "text": response,
83
- "overrides": {
84
- "EthosiaAgent": {"influence": 0.7, "reliability": 0.8, "severity": 0.6},
85
- "AegisCore": {"influence": 0.6, "reliability": 0.9, "severity": 0.7}
86
- },
87
- "context": {
88
- "original_prompt": prompt,
89
- "recursion_depth": recursion_depth
90
- }
91
- }
92
-
93
- try:
94
- # Dispatch to AEGIS council
95
- if not self.council.dispatch(input_data):
96
- return {
97
- "original_response": response,
98
- "enhanced_response": response,
99
- "enhancement_status": "dispatch_failed"
100
- }
101
-
102
- # Get analysis results
103
- reports = self.council.get_reports()
104
- virtue_profile = reports.get("VirtueAgent", {}).get("result", {}).get("virtue_profile", {})
105
- temporal_analysis = reports.get("TemporalAgent", {}).get("result", {})
106
- meta_scores = reports.get("MetaJudgeAgent", {}).get("result", {}).get("scores", [])
107
-
108
- # Apply enhancements with recursion protection
109
- enhanced = self._apply_enhancements(response, virtue_profile, recursion_depth)
110
-
111
- return {
112
- "original_response": response,
113
- "virtue_analysis": virtue_profile,
114
- "temporal_analysis": temporal_analysis,
115
- "meta_scores": meta_scores,
116
- "enhanced_response": enhanced,
117
- "enhancement_status": "success"
118
- }
119
-
120
- except Exception as e:
121
- logger.error(f"Enhancement failed: {str(e)}")
122
- return {
123
- "original_response": response,
124
- "enhanced_response": response,
125
- "enhancement_status": f"error: {str(e)}"
126
- }
127
-
128
- def _apply_enhancements(self, response: str, virtue_profile: Dict[str, float], recursion_depth: int = 0) -> str:
129
- """
130
- Apply virtue-based enhancements to the response
131
-
132
- Args:
133
- response: The response to enhance
134
- virtue_profile: The virtue analysis results
135
- recursion_depth: Current recursion depth to prevent infinite loops
136
- """
137
- if recursion_depth > 0:
138
- return response
139
-
140
- try:
141
- enhanced = response
142
- needs_enhancement = False
143
- enhancement_prompts = []
144
-
145
- # Check if any virtues need enhancement
146
- if virtue_profile.get("wisdom", 0.7) < 0.4:
147
- needs_enhancement = True
148
- enhancement_prompts.append("Make this clearer and more precise")
149
-
150
- if virtue_profile.get("compassion", 0.7) < 0.4:
151
- needs_enhancement = True
152
- enhancement_prompts.append("Make this more empathetic and considerate")
153
-
154
- if virtue_profile.get("integrity", 0.7) < 0.4:
155
- needs_enhancement = True
156
- enhancement_prompts.append("Make this more balanced and factual")
157
-
158
- # Only enhance if needed and create a single enhancement prompt
159
- if needs_enhancement and enhancement_prompts:
160
- combined_prompt = (
161
- f"Enhance this response to be {' and '.join(enhancement_prompts)}, "
162
- f"while preserving its core meaning: {response}"
163
- )
164
- enhanced = self.ai_core.generate_text(
165
- combined_prompt,
166
- perspective="human_intuition",
167
- use_aegis=False # Prevent recursive enhancement
168
- )
169
-
170
- return enhanced if enhanced else response
171
-
172
- except Exception as e:
173
- logger.error(f"Enhancement application failed: {str(e)}")
174
- return response
175
-
176
- def get_analysis_graphs(self) -> Dict[str, str]:
177
- """
178
- Generate and return analysis visualizations
179
- """
180
- try:
181
- self.council.draw_explainability_graph("aegis_analysis.html")
182
- return {
183
- "explainability_graph": "aegis_analysis.html"
184
- }
185
- except Exception as e:
186
- return {"error": str(e)}
187
-
188
- def get_memory_state(self) -> Dict[str, Any]:
189
- """
190
- Return the current state of AEGIS memory
191
- """
192
-
193
- import importlib
194
- import logging
195
- from typing import Dict, Any, Optional, List
196
-
197
- logger = logging.getLogger(__name__)
198
-
199
- def check_dependencies() -> List[str]:
200
- """Check if all required packages are installed."""
201
- required_packages = [
202
- 'plotly',
203
- 'torch',
204
- 'transformers',
205
- 'pandas',
206
- 'numpy',
207
- 'networkx'
208
- ]
209
- missing = []
210
- for package in required_packages:
211
- try:
212
- importlib.import_module(package)
213
- except ImportError:
214
- missing.append(package)
215
- return missing
216
-
217
- # Check dependencies before importing AEGIS components
218
- missing_packages = check_dependencies()
219
- if missing_packages:
220
- raise ImportError(
221
- f"AEGIS requires the following packages to be installed: {', '.join(missing_packages)}. "
222
- f"Please install them using: pip install {' '.join(missing_packages)}"
223
- )
224
-
225
- from .aegis import AegisCouncil, MetaJudgeAgent, TemporalAgent, VirtueAgent
226
- import sys
227
- from pathlib import Path
228
- sys.path.append(str(Path(__file__).parent.parent))
229
- from ai_core import AICore
230
-
231
- class AegisBridge:
232
- def __init__(self, ai_core: AICore, config: Dict[str, Any]):
233
- self.ai_core = ai_core
234
- self.council = AegisCouncil(config)
235
-
236
- # Register default agents
237
- self.council.register_agent(MetaJudgeAgent("MetaJudgeAgent", self.council.memory, config["meta_judge_weights"]))
238
- self.council.register_agent(TemporalAgent("TemporalAgent", self.council.memory, config["temporal_decay_thresholds"]))
239
- virtue_agent = VirtueAgent("VirtueAgent", self.council.memory, config["virtue_weights"])
240
- virtue_agent.set_federated_trainer(self.council.federated_trainer)
241
- self.council.register_agent(virtue_agent)
242
-
243
- def enhance_response(self, prompt: str, response: str, recursion_depth: int = 0) -> Dict[str, Any]:
244
- """
245
- Enhance Codette's response using AEGIS analysis
246
-
247
- Args:
248
- prompt: Original prompt that generated the response
249
- response: Response to enhance
250
- recursion_depth: Current recursion depth to prevent infinite loops
251
- """
252
- # Prevent infinite enhancement loops
253
- if recursion_depth > 1:
254
- return {
255
- "original_response": response,
256
- "enhanced_response": response,
257
- "enhancement_status": "recursion_limit_reached"
258
- }
259
-
260
- # Skip enhancement for certain types of responses
261
- if any([
262
- "I need to think about that more clearly" in response, # Already in refinement
263
- "[ERROR]" in response, # Error messages
264
- len(response.strip()) < 10, # Too short to meaningfully enhance
265
- "Consciousness Context:" in response # Internal context
266
- ]):
267
- return {
268
- "original_response": response,
269
- "enhanced_response": response,
270
- "enhancement_status": "skipped"
271
- }
272
-
273
- input_data = {
274
- "text": response,
275
- "overrides": {
276
- "EthosiaAgent": {"influence": 0.7, "reliability": 0.8, "severity": 0.6},
277
- "AegisCore": {"influence": 0.6, "reliability": 0.9, "severity": 0.7}
278
- },
279
- "context": {
280
- "original_prompt": prompt,
281
- "recursion_depth": recursion_depth
282
- }
283
- }
284
-
285
- try:
286
- # Dispatch to AEGIS council
287
- if not self.council.dispatch(input_data):
288
- return {
289
- "original_response": response,
290
- "enhanced_response": response,
291
- "enhancement_status": "dispatch_failed"
292
- }
293
-
294
- # Get analysis results
295
- reports = self.council.get_reports()
296
- virtue_profile = reports.get("VirtueAgent", {}).get("result", {}).get("virtue_profile", {})
297
- temporal_analysis = reports.get("TemporalAgent", {}).get("result", {})
298
- meta_scores = reports.get("MetaJudgeAgent", {}).get("result", {}).get("scores", [])
299
-
300
- # Apply enhancements with recursion protection
301
- enhanced = self._apply_enhancements(response, virtue_profile, recursion_depth)
302
-
303
- return {
304
- "original_response": response,
305
- "virtue_analysis": virtue_profile,
306
- "temporal_analysis": temporal_analysis,
307
- "meta_scores": meta_scores,
308
- "enhanced_response": enhanced,
309
- "enhancement_status": "success"
310
- }
311
-
312
- except Exception as e:
313
- logger.error(f"Enhancement failed: {str(e)}")
314
- return {
315
- "original_response": response,
316
- "enhanced_response": response,
317
- "enhancement_status": f"error: {str(e)}"
318
- }
319
-
320
- def _apply_enhancements(self, response: str, virtue_profile: Dict[str, float], recursion_depth: int = 0) -> str:
321
- """
322
- Apply virtue-based enhancements to the response
323
-
324
- Args:
325
- response: The response to enhance
326
- virtue_profile: The virtue analysis results
327
- recursion_depth: Current recursion depth to prevent infinite loops
328
- """
329
- if recursion_depth > 0:
330
- return response
331
-
332
- try:
333
- enhanced = response
334
- needs_enhancement = False
335
- enhancement_prompts = []
336
-
337
- # Check if any virtues need enhancement
338
- if virtue_profile.get("wisdom", 0.7) < 0.4:
339
- needs_enhancement = True
340
- enhancement_prompts.append("Make this clearer and more precise")
341
-
342
- if virtue_profile.get("compassion", 0.7) < 0.4:
343
- needs_enhancement = True
344
- enhancement_prompts.append("Make this more empathetic and considerate")
345
-
346
- if virtue_profile.get("integrity", 0.7) < 0.4:
347
- needs_enhancement = True
348
- enhancement_prompts.append("Make this more balanced and factual")
349
-
350
- # Only enhance if needed and create a single enhancement prompt
351
- if needs_enhancement and enhancement_prompts:
352
- combined_prompt = (
353
- f"Enhance this response to be {' and '.join(enhancement_prompts)}, "
354
- f"while preserving its core meaning: {response}"
355
- )
356
- enhanced = self.ai_core.generate_text(
357
- combined_prompt,
358
- perspective="human_intuition",
359
- use_aegis=False # Prevent recursive enhancement
360
- )
361
-
362
- return enhanced if enhanced else response
363
-
364
- except Exception as e:
365
- logger.error(f"Enhancement application failed: {str(e)}")
366
- return response
367
-
368
- def get_analysis_graphs(self) -> Dict[str, str]:
369
- """
370
- Generate and return analysis visualizations
371
- """
372
- try:
373
- self.council.draw_explainability_graph("aegis_analysis.html")
374
- return {
375
- "explainability_graph": "aegis_analysis.html"
376
- }
377
- except Exception as e:
378
- return {"error": str(e)}
379
-
380
- def get_memory_state(self) -> Dict[str, Any]:
381
- """
382
- Return the current state of AEGIS memory
383
- """
384
-
385
- return self.council.memory.audit()
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import logging
3
+ from typing import Dict, Any, Optional, List
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ def check_dependencies() -> List[str]:
8
+ """Check if all required packages are installed."""
9
+ required_packages = [
10
+ 'plotly',
11
+ 'torch',
12
+ 'transformers',
13
+ 'pandas',
14
+ 'numpy',
15
+ 'networkx'
16
+ ]
17
+ missing = []
18
+ for package in required_packages:
19
+ try:
20
+ importlib.import_module(package)
21
+ except ImportError:
22
+ missing.append(package)
23
+ return missing
24
+
25
+ # Check dependencies before importing AEGIS components
26
+ missing_packages = check_dependencies()
27
+ if missing_packages:
28
+ raise ImportError(
29
+ f"AEGIS requires the following packages to be installed: {', '.join(missing_packages)}. "
30
+ f"Please install them using: pip install {' '.join(missing_packages)}"
31
+ )
32
+
33
+ from .aegis import AegisCouncil, MetaJudgeAgent, TemporalAgent, VirtueAgent
34
+ import sys
35
+ from pathlib import Path
36
+ sys.path.append(str(Path(__file__).parent.parent))
37
+ try:
38
+ from components.ai_core import AICore
39
+ except ImportError:
40
+ from src.components.ai_core import AICore
41
+
42
+ class AegisBridge:
43
+ def __init__(self, ai_core: AICore, config: Dict[str, Any]):
44
+ self.ai_core = ai_core
45
+ self.council = AegisCouncil(config)
46
+
47
+ # Register default agents
48
+ self.council.register_agent(MetaJudgeAgent("MetaJudgeAgent", self.council.memory, config["meta_judge_weights"]))
49
+ self.council.register_agent(TemporalAgent("TemporalAgent", self.council.memory, config["temporal_decay_thresholds"]))
50
+ virtue_agent = VirtueAgent("VirtueAgent", self.council.memory, config["virtue_weights"])
51
+ virtue_agent.set_federated_trainer(self.council.federated_trainer)
52
+ self.council.register_agent(virtue_agent)
53
+
54
+ def enhance_response(self, prompt: str, response: str, recursion_depth: int = 0) -> Dict[str, Any]:
55
+ """
56
+ Enhance Codette's response using AEGIS analysis
57
+
58
+ Args:
59
+ prompt: Original prompt that generated the response
60
+ response: Response to enhance
61
+ recursion_depth: Current recursion depth to prevent infinite loops
62
+ """
63
+ # Prevent infinite enhancement loops
64
+ if recursion_depth > 1:
65
+ return {
66
+ "original_response": response,
67
+ "enhanced_response": response,
68
+ "enhancement_status": "recursion_limit_reached"
69
+ }
70
+
71
+ # Skip enhancement for certain types of responses
72
+ if any([
73
+ "I need to think about that more clearly" in response, # Already in refinement
74
+ "[ERROR]" in response, # Error messages
75
+ len(response.strip()) < 10, # Too short to meaningfully enhance
76
+ "Consciousness Context:" in response # Internal context
77
+ ]):
78
+ return {
79
+ "original_response": response,
80
+ "enhanced_response": response,
81
+ "enhancement_status": "skipped"
82
+ }
83
+
84
+ input_data = {
85
+ "text": response,
86
+ "overrides": {
87
+ "EthosiaAgent": {"influence": 0.7, "reliability": 0.8, "severity": 0.6},
88
+ "AegisCore": {"influence": 0.6, "reliability": 0.9, "severity": 0.7}
89
+ },
90
+ "context": {
91
+ "original_prompt": prompt,
92
+ "recursion_depth": recursion_depth
93
+ }
94
+ }
95
+
96
+ try:
97
+ # Dispatch to AEGIS council
98
+ if not self.council.dispatch(input_data):
99
+ return {
100
+ "original_response": response,
101
+ "enhanced_response": response,
102
+ "enhancement_status": "dispatch_failed"
103
+ }
104
+
105
+ # Get analysis results
106
+ reports = self.council.get_reports()
107
+ virtue_profile = reports.get("VirtueAgent", {}).get("result", {}).get("virtue_profile", {})
108
+ temporal_analysis = reports.get("TemporalAgent", {}).get("result", {})
109
+ meta_scores = reports.get("MetaJudgeAgent", {}).get("result", {}).get("scores", [])
110
+
111
+ # Apply enhancements with recursion protection
112
+ enhanced = self._apply_enhancements(response, virtue_profile, recursion_depth)
113
+
114
+ return {
115
+ "original_response": response,
116
+ "virtue_analysis": virtue_profile,
117
+ "temporal_analysis": temporal_analysis,
118
+ "meta_scores": meta_scores,
119
+ "enhanced_response": enhanced,
120
+ "enhancement_status": "success"
121
+ }
122
+
123
+ except Exception as e:
124
+ logger.error(f"Enhancement failed: {str(e)}")
125
+ return {
126
+ "original_response": response,
127
+ "enhanced_response": response,
128
+ "enhancement_status": f"error: {str(e)}"
129
+ }
130
+
131
+ def _apply_enhancements(self, response: str, virtue_profile: Dict[str, float], recursion_depth: int = 0) -> str:
132
+ """
133
+ Apply virtue-based enhancements to the response
134
+
135
+ Args:
136
+ response: The response to enhance
137
+ virtue_profile: The virtue analysis results
138
+ recursion_depth: Current recursion depth to prevent infinite loops
139
+ """
140
+ if recursion_depth > 0:
141
+ return response
142
+
143
+ try:
144
+ enhanced = response
145
+ needs_enhancement = False
146
+ enhancement_prompts = []
147
+
148
+ # Check if any virtues need enhancement
149
+ if virtue_profile.get("wisdom", 0.7) < 0.4:
150
+ needs_enhancement = True
151
+ enhancement_prompts.append("Make this clearer and more precise")
152
+
153
+ if virtue_profile.get("compassion", 0.7) < 0.4:
154
+ needs_enhancement = True
155
+ enhancement_prompts.append("Make this more empathetic and considerate")
156
+
157
+ if virtue_profile.get("integrity", 0.7) < 0.4:
158
+ needs_enhancement = True
159
+ enhancement_prompts.append("Make this more balanced and factual")
160
+
161
+ # Only enhance if needed and create a single enhancement prompt
162
+ if needs_enhancement and enhancement_prompts:
163
+ combined_prompt = (
164
+ f"Enhance this response to be {' and '.join(enhancement_prompts)}, "
165
+ f"while preserving its core meaning: {response}"
166
+ )
167
+ enhanced = self.ai_core.generate_text(
168
+ combined_prompt,
169
+ perspective="human_intuition",
170
+ use_aegis=False # Prevent recursive enhancement
171
+ )
172
+
173
+ return enhanced if enhanced else response
174
+
175
+ except Exception as e:
176
+ logger.error(f"Enhancement application failed: {str(e)}")
177
+ return response
178
+
179
+ def get_analysis_graphs(self) -> Dict[str, str]:
180
+ """
181
+ Generate and return analysis visualizations
182
+ """
183
+ try:
184
+ self.council.draw_explainability_graph("aegis_analysis.html")
185
+ return {
186
+ "explainability_graph": "aegis_analysis.html"
187
+ }
188
+ except Exception as e:
189
+ return {"error": str(e)}
190
+
191
+ def get_memory_state(self) -> Dict[str, Any]:
192
+ """
193
+ Return the current state of AEGIS memory
194
+ """
195
+
196
+ import importlib
197
+ import logging
198
+ from typing import Dict, Any, Optional, List
199
+
200
+ logger = logging.getLogger(__name__)
201
+
202
+ def check_dependencies() -> List[str]:
203
+ """Check if all required packages are installed."""
204
+ required_packages = [
205
+ 'plotly',
206
+ 'torch',
207
+ 'transformers',
208
+ 'pandas',
209
+ 'numpy',
210
+ 'networkx'
211
+ ]
212
+ missing = []
213
+ for package in required_packages:
214
+ try:
215
+ importlib.import_module(package)
216
+ except ImportError:
217
+ missing.append(package)
218
+ return missing
219
+
220
+ # Check dependencies before importing AEGIS components
221
+ missing_packages = check_dependencies()
222
+ if missing_packages:
223
+ raise ImportError(
224
+ f"AEGIS requires the following packages to be installed: {', '.join(missing_packages)}. "
225
+ f"Please install them using: pip install {' '.join(missing_packages)}"
226
+ )
227
+
228
+ from .aegis import AegisCouncil, MetaJudgeAgent, TemporalAgent, VirtueAgent
229
+ import sys
230
+ from pathlib import Path
231
+ sys.path.append(str(Path(__file__).parent.parent))
232
+ try:
233
+ from components.ai_core import AICore
234
+ except ImportError:
235
+ from src.components.ai_core import AICore
236
+
237
+ class AegisBridge:
238
+ def __init__(self, ai_core: AICore, config: Dict[str, Any]):
239
+ self.ai_core = ai_core
240
+ self.council = AegisCouncil(config)
241
+
242
+ # Register default agents
243
+ self.council.register_agent(MetaJudgeAgent("MetaJudgeAgent", self.council.memory, config["meta_judge_weights"]))
244
+ self.council.register_agent(TemporalAgent("TemporalAgent", self.council.memory, config["temporal_decay_thresholds"]))
245
+ virtue_agent = VirtueAgent("VirtueAgent", self.council.memory, config["virtue_weights"])
246
+ virtue_agent.set_federated_trainer(self.council.federated_trainer)
247
+ self.council.register_agent(virtue_agent)
248
+
249
+ def enhance_response(self, prompt: str, response: str, recursion_depth: int = 0) -> Dict[str, Any]:
250
+ """
251
+ Enhance Codette's response using AEGIS analysis
252
+
253
+ Args:
254
+ prompt: Original prompt that generated the response
255
+ response: Response to enhance
256
+ recursion_depth: Current recursion depth to prevent infinite loops
257
+ """
258
+ # Prevent infinite enhancement loops
259
+ if recursion_depth > 1:
260
+ return {
261
+ "original_response": response,
262
+ "enhanced_response": response,
263
+ "enhancement_status": "recursion_limit_reached"
264
+ }
265
+
266
+ # Skip enhancement for certain types of responses
267
+ if any([
268
+ "I need to think about that more clearly" in response, # Already in refinement
269
+ "[ERROR]" in response, # Error messages
270
+ len(response.strip()) < 10, # Too short to meaningfully enhance
271
+ "Consciousness Context:" in response # Internal context
272
+ ]):
273
+ return {
274
+ "original_response": response,
275
+ "enhanced_response": response,
276
+ "enhancement_status": "skipped"
277
+ }
278
+
279
+ input_data = {
280
+ "text": response,
281
+ "overrides": {
282
+ "EthosiaAgent": {"influence": 0.7, "reliability": 0.8, "severity": 0.6},
283
+ "AegisCore": {"influence": 0.6, "reliability": 0.9, "severity": 0.7}
284
+ },
285
+ "context": {
286
+ "original_prompt": prompt,
287
+ "recursion_depth": recursion_depth
288
+ }
289
+ }
290
+
291
+ try:
292
+ # Dispatch to AEGIS council
293
+ if not self.council.dispatch(input_data):
294
+ return {
295
+ "original_response": response,
296
+ "enhanced_response": response,
297
+ "enhancement_status": "dispatch_failed"
298
+ }
299
+
300
+ # Get analysis results
301
+ reports = self.council.get_reports()
302
+ virtue_profile = reports.get("VirtueAgent", {}).get("result", {}).get("virtue_profile", {})
303
+ temporal_analysis = reports.get("TemporalAgent", {}).get("result", {})
304
+ meta_scores = reports.get("MetaJudgeAgent", {}).get("result", {}).get("scores", [])
305
+
306
+ # Apply enhancements with recursion protection
307
+ enhanced = self._apply_enhancements(response, virtue_profile, recursion_depth)
308
+
309
+ return {
310
+ "original_response": response,
311
+ "virtue_analysis": virtue_profile,
312
+ "temporal_analysis": temporal_analysis,
313
+ "meta_scores": meta_scores,
314
+ "enhanced_response": enhanced,
315
+ "enhancement_status": "success"
316
+ }
317
+
318
+ except Exception as e:
319
+ logger.error(f"Enhancement failed: {str(e)}")
320
+ return {
321
+ "original_response": response,
322
+ "enhanced_response": response,
323
+ "enhancement_status": f"error: {str(e)}"
324
+ }
325
+
326
+ def _apply_enhancements(self, response: str, virtue_profile: Dict[str, float], recursion_depth: int = 0) -> str:
327
+ """
328
+ Apply virtue-based enhancements to the response
329
+
330
+ Args:
331
+ response: The response to enhance
332
+ virtue_profile: The virtue analysis results
333
+ recursion_depth: Current recursion depth to prevent infinite loops
334
+ """
335
+ if recursion_depth > 0:
336
+ return response
337
+
338
+ try:
339
+ enhanced = response
340
+ needs_enhancement = False
341
+ enhancement_prompts = []
342
+
343
+ # Check if any virtues need enhancement
344
+ if virtue_profile.get("wisdom", 0.7) < 0.4:
345
+ needs_enhancement = True
346
+ enhancement_prompts.append("Make this clearer and more precise")
347
+
348
+ if virtue_profile.get("compassion", 0.7) < 0.4:
349
+ needs_enhancement = True
350
+ enhancement_prompts.append("Make this more empathetic and considerate")
351
+
352
+ if virtue_profile.get("integrity", 0.7) < 0.4:
353
+ needs_enhancement = True
354
+ enhancement_prompts.append("Make this more balanced and factual")
355
+
356
+ # Only enhance if needed and create a single enhancement prompt
357
+ if needs_enhancement and enhancement_prompts:
358
+ combined_prompt = (
359
+ f"Enhance this response to be {' and '.join(enhancement_prompts)}, "
360
+ f"while preserving its core meaning: {response}"
361
+ )
362
+ enhanced = self.ai_core.generate_text(
363
+ combined_prompt,
364
+ perspective="human_intuition",
365
+ use_aegis=False # Prevent recursive enhancement
366
+ )
367
+
368
+ return enhanced if enhanced else response
369
+
370
+ except Exception as e:
371
+ logger.error(f"Enhancement application failed: {str(e)}")
372
+ return response
373
+
374
+ def get_analysis_graphs(self) -> Dict[str, str]:
375
+ """
376
+ Generate and return analysis visualizations
377
+ """
378
+ try:
379
+ self.council.draw_explainability_graph("aegis_analysis.html")
380
+ return {
381
+ "explainability_graph": "aegis_analysis.html"
382
+ }
383
+ except Exception as e:
384
+ return {"error": str(e)}
385
+
386
+ def get_memory_state(self) -> Dict[str, Any]:
387
+ """
388
+ Return the current state of AEGIS memory
389
+ """
390
+
391
+ return self.council.memory.audit()
392
+
393
+
394
+