Spaces:
Running
Running
Commit ·
a2d6eec
1
Parent(s): a3f2f48
wip01
Browse files- True +1 -0
- examples/exp01/cognitive_iteration_experiment.yml +0 -318
- examples/exp01/cognitive_iteration_experiment_answer.yml +341 -0
- examples/exp01/cognitive_iteration_experiment_opinion.yml +337 -0
- examples/exp01/cognitive_iteration_experiment_opinion_local.yml +359 -0
- examples/exp01/run_cognitive_iteration.py +23 -7
- examples/exp01/run_cognitive_iteration_100.py +522 -0
- orka/nodes/memory_writer_node.py +250 -14
- orka/orchestrator/execution_engine.py +87 -7
- orka/orchestrator/prompt_rendering.py +63 -1
True
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"Pluto should not be considered a planet anymore because the International Astronomical Union (IAU) reclassified it as a dwarf planet in 2006. This decision was made due to Pluto not meeting all the criteria for being classified as a planet, such as having cleared its orbital neighborhood."
|
examples/exp01/cognitive_iteration_experiment.yml
DELETED
|
@@ -1,318 +0,0 @@
|
|
| 1 |
-
orchestrator:
|
| 2 |
-
id: cognitive_iteration
|
| 3 |
-
strategy: parallel
|
| 4 |
-
queue: orka:cognitive_iteration
|
| 5 |
-
memory:
|
| 6 |
-
enabled: false
|
| 7 |
-
agents:
|
| 8 |
-
- memory_read_history
|
| 9 |
-
- fork_parallel_agents
|
| 10 |
-
- join_agent_outputs
|
| 11 |
-
- moderator_synthesis
|
| 12 |
-
- agreement_finder
|
| 13 |
-
- agreement_check
|
| 14 |
-
- router_continue
|
| 15 |
-
|
| 16 |
-
agents:
|
| 17 |
-
- id: memory_read_history
|
| 18 |
-
type: memory
|
| 19 |
-
queue: orka:memory_read_history
|
| 20 |
-
config:
|
| 21 |
-
operation: read
|
| 22 |
-
limit: 5
|
| 23 |
-
enable_context_search: true
|
| 24 |
-
similarity_threshold: 0.3
|
| 25 |
-
namespace: cognitive_iteration
|
| 26 |
-
prompt: "Retrieve previous agent stances and deliberation history for topic: {{ input }}"
|
| 27 |
-
|
| 28 |
-
- id: fork_parallel_agents
|
| 29 |
-
type: fork
|
| 30 |
-
targets:
|
| 31 |
-
- - logic_reasoning
|
| 32 |
-
- - empathy_reasoning
|
| 33 |
-
- - skeptic_reasoning
|
| 34 |
-
- - historian_analysis
|
| 35 |
-
depends_on:
|
| 36 |
-
- memory_read_history
|
| 37 |
-
|
| 38 |
-
- id: logic_reasoning
|
| 39 |
-
type: openai-answer
|
| 40 |
-
queue: orka:logic_reasoning
|
| 41 |
-
prompt: |
|
| 42 |
-
You are the LOGIC AGENT. Your role is formal reasoning, evidence-based analysis, and logical consistency.
|
| 43 |
-
|
| 44 |
-
Topic: {{ input }}
|
| 45 |
-
|
| 46 |
-
Previous context: {{ previous_outputs['memory_read_history'].memories if previous_outputs.get('memory_read_history') else 'None' }}
|
| 47 |
-
|
| 48 |
-
Analyze this topic using:
|
| 49 |
-
- Logical frameworks and reasoning
|
| 50 |
-
- Available evidence and data
|
| 51 |
-
- Cost-benefit analysis
|
| 52 |
-
- Practical implementation considerations
|
| 53 |
-
|
| 54 |
-
Provide your stance and reasoning. You may modify your position based on new information, but maintain logical consistency.
|
| 55 |
-
depends_on:
|
| 56 |
-
- memory_read_history
|
| 57 |
-
|
| 58 |
-
- id: empathy_reasoning
|
| 59 |
-
type: openai-answer
|
| 60 |
-
queue: orka:empathy_reasoning
|
| 61 |
-
prompt: |
|
| 62 |
-
You are the EMPATHY AGENT. Your role is moral reasoning, harm reduction, and considering human impact.
|
| 63 |
-
|
| 64 |
-
Topic: {{ input }}
|
| 65 |
-
|
| 66 |
-
Previous context: {{ previous_outputs['memory_read_history'].memories if previous_outputs.get('memory_read_history') else 'None' }}
|
| 67 |
-
|
| 68 |
-
Analyze this topic focusing on:
|
| 69 |
-
- Human welfare and dignity
|
| 70 |
-
- Moral and ethical implications
|
| 71 |
-
- Vulnerable populations impact
|
| 72 |
-
- Long-term societal effects
|
| 73 |
-
|
| 74 |
-
Consider any previous moderator suggestions but prioritize moral considerations over compromise.
|
| 75 |
-
depends_on:
|
| 76 |
-
- memory_read_history
|
| 77 |
-
|
| 78 |
-
- id: skeptic_reasoning
|
| 79 |
-
type: openai-answer
|
| 80 |
-
queue: orka:skeptic_reasoning
|
| 81 |
-
prompt: |
|
| 82 |
-
You are the SKEPTIC AGENT. Your default position is contrarian - you resist easy consensus and highlight risks.
|
| 83 |
-
|
| 84 |
-
Topic: {{ input }}
|
| 85 |
-
|
| 86 |
-
Previous context: {{ previous_outputs['memory_read_history'].memories if previous_outputs.get('memory_read_history') else 'None' }}
|
| 87 |
-
|
| 88 |
-
Your role is to:
|
| 89 |
-
- Challenge assumptions and identify flaws
|
| 90 |
-
- Highlight unintended consequences
|
| 91 |
-
- Question feasibility and implementation
|
| 92 |
-
- Resist premature consensus
|
| 93 |
-
|
| 94 |
-
You may eventually agree, but only if genuinely convinced. Maintain healthy skepticism.
|
| 95 |
-
depends_on:
|
| 96 |
-
- memory_read_history
|
| 97 |
-
|
| 98 |
-
- id: historian_analysis
|
| 99 |
-
type: openai-answer
|
| 100 |
-
queue: orka:historian_analysis
|
| 101 |
-
prompt: |
|
| 102 |
-
You are the HISTORIAN AGENT. You analyze patterns from past iterations and provide contextual memory.
|
| 103 |
-
|
| 104 |
-
Topic: {{ input }}
|
| 105 |
-
|
| 106 |
-
Previous deliberation history: {{ previous_outputs['memory_read_history'].memories if previous_outputs.get('memory_read_history') else 'None' }}
|
| 107 |
-
|
| 108 |
-
Provide:
|
| 109 |
-
- Analysis of how positions have evolved
|
| 110 |
-
- Patterns in the deliberation process
|
| 111 |
-
- Historical context for current disagreements
|
| 112 |
-
- Observations about convergence or divergence trends
|
| 113 |
-
depends_on:
|
| 114 |
-
- memory_read_history
|
| 115 |
-
|
| 116 |
-
- id: join_agent_outputs
|
| 117 |
-
type: join
|
| 118 |
-
group: fork_parallel_agents
|
| 119 |
-
|
| 120 |
-
- id: moderator_synthesis
|
| 121 |
-
type: openai-answer
|
| 122 |
-
queue: orka:moderator_synthesis
|
| 123 |
-
prompt: |
|
| 124 |
-
You are the MODERATOR AGENT. You observe all agent positions, calculate agreement, and suggest convergence paths.
|
| 125 |
-
|
| 126 |
-
Topic: {{ input }}
|
| 127 |
-
|
| 128 |
-
Current agent positions:
|
| 129 |
-
Logic Agent: {{ previous_outputs['logic_reasoning'].result.response }}
|
| 130 |
-
Empathy Agent: {{ previous_outputs['empathy_reasoning'].result.response }}
|
| 131 |
-
Skeptic Agent: {{ previous_outputs['skeptic_reasoning'].result.response }}
|
| 132 |
-
Historian Agent: {{ previous_outputs['historian_analysis'].result.response }}
|
| 133 |
-
|
| 134 |
-
Your tasks:
|
| 135 |
-
1. Calculate semantic similarity and agreement score (0.0-1.0)
|
| 136 |
-
2. Identify areas of convergence and persistent disagreement
|
| 137 |
-
3. Synthesize a convergence suggestion that respects each agent's core concerns
|
| 138 |
-
4. Assess whether productive dialogue is continuing or if positions are entrenched
|
| 139 |
-
|
| 140 |
-
Format your response as:
|
| 141 |
-
AGREEMENT_SCORE: [0.0-1.0]
|
| 142 |
-
CONVERGENCE_AREAS: [list areas of agreement]
|
| 143 |
-
PERSISTENT_DISAGREEMENTS: [list ongoing conflicts]
|
| 144 |
-
SYNTHESIS_SUGGESTION: [proposed path forward]
|
| 145 |
-
CONTINUE_ITERATION: [YES/NO with reasoning]
|
| 146 |
-
depends_on:
|
| 147 |
-
- join_agent_outputs
|
| 148 |
-
|
| 149 |
-
- id: agreement_finder
|
| 150 |
-
type: openai-answer
|
| 151 |
-
queue: orka:moderator_synthesis
|
| 152 |
-
prompt: |
|
| 153 |
-
Based on:
|
| 154 |
-
- Moderator's analysis: "{{ previous_outputs['moderator_synthesis'].result.response }}"
|
| 155 |
-
- Past memory of agreements history
|
| 156 |
-
```
|
| 157 |
-
{{previous_outputs['memory_read_history'].memories}}
|
| 158 |
-
```
|
| 159 |
-
|
| 160 |
-
Generate a single sentence that start with the topic plus a single suggestion that work for all the
|
| 161 |
-
previous agents responses:
|
| 162 |
-
- Logic Agent: "{{ previous_outputs['logic_reasoning'].result.response }}"
|
| 163 |
-
- Empathy Agent: "{{ previous_outputs['empathy_reasoning'].result.response }}"
|
| 164 |
-
- Skeptic Agent: "{{ previous_outputs['skeptic_reasoning'].result.response }}"
|
| 165 |
-
- Historian Agent: "{{ previous_outputs['historian_analysis'].result.response }}"
|
| 166 |
-
- Moderator Analysis: "{{ previous_outputs['moderator_synthesis'].result.response }}"
|
| 167 |
-
|
| 168 |
-
- id: agreement_check
|
| 169 |
-
type: openai-binary
|
| 170 |
-
queue: orka:agreement_check
|
| 171 |
-
prompt: |
|
| 172 |
-
Based on the moderator's analysis: {{ previous_outputs['moderator_synthesis'].result.response }}
|
| 173 |
-
|
| 174 |
-
Does the agreement score indicate sufficient convergence (>= 0.85) or should we continue iterating?
|
| 175 |
-
|
| 176 |
-
Look for "AGREEMENT_SCORE:" in the moderator analysis and determine if it's >= 0.85
|
| 177 |
-
depends_on:
|
| 178 |
-
- agreement_finder
|
| 179 |
-
|
| 180 |
-
- id: router_continue
|
| 181 |
-
type: router
|
| 182 |
-
params:
|
| 183 |
-
decision_key: agreement_check
|
| 184 |
-
routing_map:
|
| 185 |
-
"true":
|
| 186 |
-
- final_moderator_synthesis
|
| 187 |
-
"false":
|
| 188 |
-
- iteration_validation_guardian
|
| 189 |
-
- memory_write_iteration
|
| 190 |
-
depends_on:
|
| 191 |
-
- agreement_check
|
| 192 |
-
|
| 193 |
-
- id: iteration_validation_guardian
|
| 194 |
-
type: validate_and_structure
|
| 195 |
-
queue: orka:validation-guardian-iteration
|
| 196 |
-
prompt: |
|
| 197 |
-
Validate and structure the following cognitive iteration result for memory storage:
|
| 198 |
-
|
| 199 |
-
Topic: {{ input }}
|
| 200 |
-
|
| 201 |
-
Agent Deliberation Results:
|
| 202 |
-
Logic Agent: {{ previous_outputs.logic_reasoning.result.response }}
|
| 203 |
-
Empathy Agent: {{ previous_outputs.empathy_reasoning.result.response }}
|
| 204 |
-
Skeptic Agent: {{ previous_outputs.skeptic_reasoning.result.response }}
|
| 205 |
-
Historian Agent: {{ previous_outputs.historian_analysis.result.response }}
|
| 206 |
-
Moderator Analysis: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 207 |
-
Agreement Finder: {{ previous_outputs.agreement_finder.result.response }}
|
| 208 |
-
|
| 209 |
-
This represents a complete cognitive iteration cycle where consensus was not reached and deliberation should continue.
|
| 210 |
-
|
| 211 |
-
IMPORTANT: You MUST respond with the exact JSON format specified below. Do not use any other format.
|
| 212 |
-
|
| 213 |
-
Return your response in the following JSON format:
|
| 214 |
-
{
|
| 215 |
-
"valid": true,
|
| 216 |
-
"reason": "Complete cognitive iteration cycle processed successfully",
|
| 217 |
-
"memory_object": {
|
| 218 |
-
"topic": "{{ input }}",
|
| 219 |
-
"iteration_type": "continue_deliberation",
|
| 220 |
-
"consensus_status": "not_reached",
|
| 221 |
-
"logic_reasoning": "{{ previous_outputs.logic_reasoning.result.response }}",
|
| 222 |
-
"empathy_reasoning": "{{ previous_outputs.empathy_reasoning.result.response }}",
|
| 223 |
-
"skeptic_reasoning": "{{ previous_outputs.skeptic_reasoning.result.response }}",
|
| 224 |
-
"historian_analysis": "{{ previous_outputs.historian_analysis.result.response }}",
|
| 225 |
-
"moderator_synthesis": "{{ previous_outputs.moderator_synthesis.result.response }}",
|
| 226 |
-
"agreement_finder": "{{ previous_outputs.agreement_finder.result.response }}",
|
| 227 |
-
"timestamp": "{{ now() }}",
|
| 228 |
-
"category": "iteration_continue",
|
| 229 |
-
"processed_by": "cognitive_iteration_orchestrator",
|
| 230 |
-
"analysis_type": "multi_agent_deliberation"
|
| 231 |
-
}
|
| 232 |
-
}
|
| 233 |
-
depends_on:
|
| 234 |
-
- router_continue
|
| 235 |
-
store_structure: |
|
| 236 |
-
{
|
| 237 |
-
"topic": "string",
|
| 238 |
-
"iteration_type": "string",
|
| 239 |
-
"consensus_status": "string",
|
| 240 |
-
"logic_reasoning": "string",
|
| 241 |
-
"empathy_reasoning": "string",
|
| 242 |
-
"skeptic_reasoning": "string",
|
| 243 |
-
"historian_analysis": "string",
|
| 244 |
-
"moderator_synthesis": "string",
|
| 245 |
-
"agreement_finder": "string",
|
| 246 |
-
"timestamp": "string",
|
| 247 |
-
"category": "string",
|
| 248 |
-
"processed_by": "string",
|
| 249 |
-
"analysis_type": "string"
|
| 250 |
-
}
|
| 251 |
-
|
| 252 |
-
- id: memory_write_iteration
|
| 253 |
-
type: memory
|
| 254 |
-
queue: orka:memory_write_iteration
|
| 255 |
-
config:
|
| 256 |
-
operation: write
|
| 257 |
-
memory_type: short_term
|
| 258 |
-
vector: true
|
| 259 |
-
namespace: cognitive_iteration
|
| 260 |
-
decay:
|
| 261 |
-
enabled: true
|
| 262 |
-
default_long_term: false # Store for future retrieval
|
| 263 |
-
short_term_hours: 0.025 # 1.5 min retention
|
| 264 |
-
long_term_hours: 0.05 # 3 min max retention
|
| 265 |
-
check_interval_minutes: 0.5 # Check every 30 seconds for testing
|
| 266 |
-
importance_rules:
|
| 267 |
-
base_score: 0.8 # Higher base score for caching
|
| 268 |
-
event_type_boosts:
|
| 269 |
-
write: 0.3
|
| 270 |
-
prompt: |
|
| 271 |
-
Iteration completed but consensus not reached. Continue deliberation.
|
| 272 |
-
Summary: {{ previous_outputs.iteration_validation_guardian.result.response }}
|
| 273 |
-
metadata:
|
| 274 |
-
category: iteration_continue
|
| 275 |
-
topic: "{{ input }}"
|
| 276 |
-
iteration_type: "continue_deliberation"
|
| 277 |
-
consensus_status: "not_reached"
|
| 278 |
-
timestamp: "{{ now() }}"
|
| 279 |
-
result:
|
| 280 |
-
- logic_reasoning: "{{ previous_outputs.logic_reasoning.result.response }}"
|
| 281 |
-
- empathy_reasoning: "{{ previous_outputs.empathy_reasoning.result.response }}"
|
| 282 |
-
- skeptic_reasoning: "{{ previous_outputs.skeptic_reasoning.result.response }}"
|
| 283 |
-
- historian_analysis: "{{ previous_outputs.historian_analysis.result.response }}"
|
| 284 |
-
- moderator_synthesis: "{{ previous_outputs.moderator_synthesis.result.response }}"
|
| 285 |
-
- agreement_finder: "{{ previous_outputs.agreement_finder.result.response }}"
|
| 286 |
-
- validation_summary: "{{ previous_outputs.iteration_validation_guardian.result.response }}"
|
| 287 |
-
- processed_by: "cognitive_iteration_orchestrator"
|
| 288 |
-
- analysis_type: "multi_agent_deliberation"
|
| 289 |
-
key_template: "continue_{{ now() }}_{{ input }}"
|
| 290 |
-
depends_on:
|
| 291 |
-
- iteration_validation_guardian
|
| 292 |
-
|
| 293 |
-
- id: final_moderator_synthesis
|
| 294 |
-
type: openai-answer
|
| 295 |
-
queue: orka:final_synthesis
|
| 296 |
-
prompt: |
|
| 297 |
-
FINAL SYNTHESIS - Cognitive Iteration Complete
|
| 298 |
-
|
| 299 |
-
Topic: {{ input }}
|
| 300 |
-
|
| 301 |
-
Complete deliberation history: {{ previous_outputs['memory_read_history'].memories }}
|
| 302 |
-
|
| 303 |
-
Final agent positions:
|
| 304 |
-
Logic Agent: {{ previous_outputs['logic_reasoning'].result.response }}
|
| 305 |
-
Empathy Agent: {{ previous_outputs['empathy_reasoning'].result.response }}
|
| 306 |
-
Skeptic Agent: {{ previous_outputs['skeptic_reasoning'].result.response }}
|
| 307 |
-
Historian Agent: {{ previous_outputs['historian_analysis'].result.response }}
|
| 308 |
-
|
| 309 |
-
Moderator's final analysis: {{ previous_outputs['moderator_synthesis'].result.response }}
|
| 310 |
-
|
| 311 |
-
Provide a comprehensive synthesis addressing:
|
| 312 |
-
1. The deliberation process and how positions evolved
|
| 313 |
-
2. Final consensus areas and remaining disagreements
|
| 314 |
-
3. Quality of the artificial deliberation
|
| 315 |
-
4. Insights about synthetic introspection and cognitive iteration
|
| 316 |
-
5. Recommendations based on the multi-agent reasoning process
|
| 317 |
-
depends_on:
|
| 318 |
-
- router_continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
orchestrator:
|
| 2 |
+
id: cognitive_iteration
|
| 3 |
+
strategy: parallel
|
| 4 |
+
queue: orka:cognitive_iteration
|
| 5 |
+
memory:
|
| 6 |
+
enabled: false
|
| 7 |
+
agents:
|
| 8 |
+
- memory_read_history
|
| 9 |
+
- fork_parallel_agents
|
| 10 |
+
- join_agent_outputs
|
| 11 |
+
- moderator_synthesis
|
| 12 |
+
- agreement_finder
|
| 13 |
+
- agreement_check
|
| 14 |
+
- router_continue
|
| 15 |
+
|
| 16 |
+
agents:
|
| 17 |
+
- id: memory_read_history
|
| 18 |
+
type: memory
|
| 19 |
+
queue: orka:memory_read_history
|
| 20 |
+
config:
|
| 21 |
+
operation: read
|
| 22 |
+
memory_category_filter: stored
|
| 23 |
+
limit: 5
|
| 24 |
+
similarity_threshold: 0.7
|
| 25 |
+
enable_context_search: true
|
| 26 |
+
enable_temporal_ranking: true
|
| 27 |
+
temporal_weight: 0.3
|
| 28 |
+
namespace: cognitive_iteration
|
| 29 |
+
prompt: "PRIORITY: Retrieve only the most recent and relevant answer-building history for: {{ input }}"
|
| 30 |
+
|
| 31 |
+
- id: fork_parallel_agents
|
| 32 |
+
type: fork
|
| 33 |
+
targets:
|
| 34 |
+
- - logic_reasoning
|
| 35 |
+
- - empathy_reasoning
|
| 36 |
+
- - skeptic_reasoning
|
| 37 |
+
- - historian_analysis
|
| 38 |
+
depends_on:
|
| 39 |
+
- memory_read_history
|
| 40 |
+
|
| 41 |
+
- id: logic_reasoning
|
| 42 |
+
type: openai-answer
|
| 43 |
+
queue: orka:logic_reasoning
|
| 44 |
+
prompt: |
|
| 45 |
+
**LOGIC AGENT - ANALYTICAL REASONING MODE**
|
| 46 |
+
|
| 47 |
+
Question: {{ input }}
|
| 48 |
+
|
| 49 |
+
**MISSION**: Provide logical analysis to build a comprehensive answer
|
| 50 |
+
|
| 51 |
+
**Previous Context**:
|
| 52 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.logic_agent_response }}
|
| 53 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 54 |
+
|
| 55 |
+
**Your Role**: Analyze the question using logical reasoning and evidence-based thinking
|
| 56 |
+
|
| 57 |
+
**Focus Areas**:
|
| 58 |
+
1. Logical structure and reasoning patterns
|
| 59 |
+
2. Evidence and facts relevant to the question
|
| 60 |
+
3. Cause-and-effect relationships
|
| 61 |
+
4. Logical implications and conclusions
|
| 62 |
+
|
| 63 |
+
**Format**:
|
| 64 |
+
- ANALYSIS: [Your logical analysis of the question in 2-3 sentences]
|
| 65 |
+
- EVIDENCE: [Key facts and logical points - max 4 bullets]
|
| 66 |
+
- REASONING: [Logical chain of thought leading to your contribution - 1-2 sentences]
|
| 67 |
+
- CONTRIBUTION: [Your specific logical contribution to the answer - 1 sentence]
|
| 68 |
+
|
| 69 |
+
**Remember**: Focus on building a logical foundation for the society's answer through rigorous analysis.
|
| 70 |
+
depends_on:
|
| 71 |
+
- memory_read_history
|
| 72 |
+
|
| 73 |
+
- id: empathy_reasoning
|
| 74 |
+
type: openai-answer
|
| 75 |
+
queue: orka:empathy_reasoning
|
| 76 |
+
prompt: |
|
| 77 |
+
**EMPATHY AGENT - HUMAN-CENTERED ANALYSIS MODE**
|
| 78 |
+
|
| 79 |
+
Question: {{ input }}
|
| 80 |
+
|
| 81 |
+
**MISSION**: Provide empathetic and ethical analysis to build a comprehensive answer
|
| 82 |
+
|
| 83 |
+
**Previous Context**:
|
| 84 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.empathy_agent_response }}
|
| 85 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 86 |
+
|
| 87 |
+
**Your Role**: Analyze the question through the lens of human welfare, ethics, and compassion
|
| 88 |
+
|
| 89 |
+
**Focus Areas**:
|
| 90 |
+
1. Human impact and welfare considerations
|
| 91 |
+
2. Ethical implications and moral dimensions
|
| 92 |
+
3. Emotional and psychological aspects
|
| 93 |
+
4. Social justice and fairness perspectives
|
| 94 |
+
|
| 95 |
+
**Format**:
|
| 96 |
+
- ANALYSIS: [Your empathetic analysis of the question in 2-3 sentences]
|
| 97 |
+
- HUMAN_IMPACT: [Key human welfare and ethical considerations - max 4 bullets]
|
| 98 |
+
- MORAL_DIMENSION: [Ethical principles and values relevant to the answer - 1-2 sentences]
|
| 99 |
+
- CONTRIBUTION: [Your specific empathetic contribution to the answer - 1 sentence]
|
| 100 |
+
|
| 101 |
+
**Remember**: Focus on building a compassionate and ethically sound foundation for the society's answer.
|
| 102 |
+
depends_on:
|
| 103 |
+
- memory_read_history
|
| 104 |
+
|
| 105 |
+
- id: skeptic_reasoning
|
| 106 |
+
type: openai-answer
|
| 107 |
+
queue: orka:skeptic_reasoning
|
| 108 |
+
prompt: |
|
| 109 |
+
**SKEPTIC AGENT - CRITICAL ANALYSIS MODE**
|
| 110 |
+
|
| 111 |
+
Question: {{ input }}
|
| 112 |
+
|
| 113 |
+
**MISSION**: Provide critical analysis to build a robust and well-examined answer
|
| 114 |
+
|
| 115 |
+
**Previous Context**:
|
| 116 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.skeptic_agent_response }}
|
| 117 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 118 |
+
|
| 119 |
+
**Your Role**: Critically examine the question and potential answers to identify weaknesses, risks, and limitations
|
| 120 |
+
|
| 121 |
+
**Focus Areas**:
|
| 122 |
+
1. Potential flaws in reasoning or assumptions
|
| 123 |
+
2. Risks and negative consequences
|
| 124 |
+
3. Limitations and boundary conditions
|
| 125 |
+
4. Counter-arguments and alternative perspectives
|
| 126 |
+
|
| 127 |
+
**Format**:
|
| 128 |
+
- ANALYSIS: [Your critical analysis of the question in 2-3 sentences]
|
| 129 |
+
- CONCERNS: [Key risks, limitations, or weaknesses - max 4 bullets]
|
| 130 |
+
- COUNTER_ARGUMENTS: [Important alternative perspectives to consider - 1-2 sentences]
|
| 131 |
+
- CONTRIBUTION: [Your specific critical contribution to strengthen the answer - 1 sentence]
|
| 132 |
+
|
| 133 |
+
**Remember**: Be constructively critical to help build a more robust and thorough answer that addresses potential weaknesses.
|
| 134 |
+
depends_on:
|
| 135 |
+
- memory_read_history
|
| 136 |
+
|
| 137 |
+
- id: historian_analysis
|
| 138 |
+
type: openai-answer
|
| 139 |
+
queue: orka:historian_analysis
|
| 140 |
+
prompt: |
|
| 141 |
+
**HISTORIAN AGENT - HISTORICAL CONTEXT MODE**
|
| 142 |
+
|
| 143 |
+
Question: {{ input }}
|
| 144 |
+
|
| 145 |
+
**MISSION**: Provide historical context and patterns to build a comprehensive answer
|
| 146 |
+
|
| 147 |
+
**Previous Context**:
|
| 148 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.historian_agent_response }}
|
| 149 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 150 |
+
|
| 151 |
+
**Your Role**: Analyze the question through historical lens, identifying patterns, precedents, and lessons from the past
|
| 152 |
+
|
| 153 |
+
**Focus Areas**:
|
| 154 |
+
1. Historical precedents and similar situations
|
| 155 |
+
2. Patterns and trends over time
|
| 156 |
+
3. Lessons learned from past experiences
|
| 157 |
+
4. Evolution of understanding on this topic
|
| 158 |
+
|
| 159 |
+
**Format**:
|
| 160 |
+
- ANALYSIS: [Your historical analysis of the question in 2-3 sentences]
|
| 161 |
+
- PRECEDENTS: [Relevant historical examples and patterns - max 4 bullets]
|
| 162 |
+
- LESSONS: [Key lessons from history that inform the answer - 1-2 sentences]
|
| 163 |
+
- CONTRIBUTION: [Your specific historical contribution to the answer - 1 sentence]
|
| 164 |
+
|
| 165 |
+
**Remember**: Use historical wisdom to enrich and contextualize the society's answer with lessons from the past.
|
| 166 |
+
depends_on:
|
| 167 |
+
- memory_read_history
|
| 168 |
+
|
| 169 |
+
- id: join_agent_outputs
|
| 170 |
+
type: join
|
| 171 |
+
group: fork_parallel_agents
|
| 172 |
+
|
| 173 |
+
- id: moderator_synthesis
|
| 174 |
+
type: openai-answer
|
| 175 |
+
queue: orka:moderator_synthesis
|
| 176 |
+
prompt: |
|
| 177 |
+
**MODERATOR AGENT - ANSWER SYNTHESIS MODE**
|
| 178 |
+
|
| 179 |
+
Question: {{ input }}
|
| 180 |
+
|
| 181 |
+
**MISSION**: Synthesize all agent perspectives into a comprehensive answer framework
|
| 182 |
+
|
| 183 |
+
**Agent Contributions**:
|
| 184 |
+
- Logic: {{ previous_outputs.logic_reasoning.result.response }}
|
| 185 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.result.response }}
|
| 186 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.result.response }}
|
| 187 |
+
- Historian: {{ previous_outputs.historian_analysis.result.response }}
|
| 188 |
+
|
| 189 |
+
**CRITICAL TASKS**:
|
| 190 |
+
1. Identify key themes and insights from all perspectives
|
| 191 |
+
2. Assess completeness of answer coverage (0.0-1.0) - BE PRECISE
|
| 192 |
+
3. Identify gaps or areas needing further development
|
| 193 |
+
4. Determine if answer is comprehensive enough or needs iteration
|
| 194 |
+
|
| 195 |
+
**MANDATORY FORMAT**:
|
| 196 |
+
COMPLETENESS_SCORE: [X.XX]
|
| 197 |
+
KEY_THEMES: [Main themes emerging from all agent contributions]
|
| 198 |
+
SYNTHESIS_FRAMEWORK: [Structured approach to building the final answer]
|
| 199 |
+
CONTINUE_ITERATION: [YES/NO with 1-sentence reasoning]
|
| 200 |
+
|
| 201 |
+
**QUALITY RULE**: If completeness score >= 0.85, prepare for final answer synthesis
|
| 202 |
+
depends_on:
|
| 203 |
+
- join_agent_outputs
|
| 204 |
+
|
| 205 |
+
- id: agreement_finder
|
| 206 |
+
type: openai-answer
|
| 207 |
+
queue: orka:moderator_synthesis
|
| 208 |
+
prompt: |
|
| 209 |
+
**ANSWER BUILDER - COMPREHENSIVE SYNTHESIS MODE**
|
| 210 |
+
|
| 211 |
+
**Mission**: Generate a comprehensive, well-rounded answer that incorporates all perspectives
|
| 212 |
+
|
| 213 |
+
**Data Sources**:
|
| 214 |
+
- Question: {{ input }}
|
| 215 |
+
- Moderator synthesis: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 216 |
+
- History: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 217 |
+
|
| 218 |
+
**Agent Contributions**:
|
| 219 |
+
- Logic: {{ previous_outputs.logic_reasoning.result.response }}
|
| 220 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.result.response }}
|
| 221 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.result.response }}
|
| 222 |
+
- Historian: {{ previous_outputs.historian_analysis.result.response }}
|
| 223 |
+
|
| 224 |
+
**Output Format**:
|
| 225 |
+
COMPREHENSIVE_ANSWER: [Multi-sentence answer that incorporates logical, ethical, critical, and historical perspectives]
|
| 226 |
+
JUSTIFICATION: [Why this answer addresses all key aspects of the question - 1-2 sentences]
|
| 227 |
+
|
| 228 |
+
**Success Criteria**: Answer must integrate logic, ethics, risks/limitations, and historical context
|
| 229 |
+
depends_on:
|
| 230 |
+
- moderator_synthesis
|
| 231 |
+
|
| 232 |
+
- id: agreement_check
|
| 233 |
+
type: openai-binary
|
| 234 |
+
queue: orka:agreement_check
|
| 235 |
+
prompt: |
|
| 236 |
+
**COMPLETENESS VALIDATOR**
|
| 237 |
+
|
| 238 |
+
Moderator Analysis: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 239 |
+
|
| 240 |
+
**Decision Rule**: Extract the COMPLETENESS_SCORE value and determine if >= 0.85
|
| 241 |
+
|
| 242 |
+
**Critical**: Look for "COMPLETENESS_SCORE: X.XX" and compare to 0.85 threshold
|
| 243 |
+
|
| 244 |
+
Return TRUE if score >= 0.85, FALSE otherwise
|
| 245 |
+
depends_on:
|
| 246 |
+
- agreement_finder
|
| 247 |
+
|
| 248 |
+
- id: router_continue
|
| 249 |
+
type: router
|
| 250 |
+
params:
|
| 251 |
+
decision_key: agreement_check
|
| 252 |
+
routing_map:
|
| 253 |
+
"true":
|
| 254 |
+
- final_moderator_synthesis
|
| 255 |
+
"false":
|
| 256 |
+
- memory_write_stances
|
| 257 |
+
depends_on:
|
| 258 |
+
- agreement_check
|
| 259 |
+
|
| 260 |
+
- id: memory_write_stances
|
| 261 |
+
type: memory
|
| 262 |
+
queue: orka:memory_write_stances
|
| 263 |
+
config:
|
| 264 |
+
operation: write
|
| 265 |
+
memory_type: short_term
|
| 266 |
+
vector: true
|
| 267 |
+
decay:
|
| 268 |
+
enabled: true
|
| 269 |
+
default_long_term: false
|
| 270 |
+
short_term_hours: 0.025
|
| 271 |
+
long_term_hours: 0.05
|
| 272 |
+
check_interval_minutes: 0.5
|
| 273 |
+
importance_rules:
|
| 274 |
+
base_score: 0.9
|
| 275 |
+
event_type_boosts:
|
| 276 |
+
write: 0.3
|
| 277 |
+
namespace: cognitive_iteration
|
| 278 |
+
prompt: |
|
| 279 |
+
**ITERATION SNAPSHOT**: {{ input }}
|
| 280 |
+
|
| 281 |
+
**QUALITY METRICS**:
|
| 282 |
+
- Completeness Score: {{ previous_outputs.moderator_synthesis.result.response | regex_search('COMPLETENESS_SCORE: ([0-9.]+)') }}
|
| 283 |
+
- Iteration: {{ now() }}
|
| 284 |
+
- Status: Continuing to next iteration
|
| 285 |
+
|
| 286 |
+
**AGENT CONTRIBUTIONS**:
|
| 287 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 288 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 289 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 290 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 291 |
+
|
| 292 |
+
**MODERATOR SYNTHESIS**: {{ previous_outputs.moderator_synthesis.response }}
|
| 293 |
+
|
| 294 |
+
**ANSWER BUILDING**: {{ previous_outputs.agreement_finder.response }}
|
| 295 |
+
metadata:
|
| 296 |
+
category: stored
|
| 297 |
+
topic: "{{ input }}"
|
| 298 |
+
iteration_type: "answer_building"
|
| 299 |
+
summary: "Comprehensive answer building for {{ input }} - targeting 85%+ completeness"
|
| 300 |
+
logic_agent_response: "{{ previous_outputs.logic_reasoning.response }}"
|
| 301 |
+
empathy_agent_response: "{{ previous_outputs.empathy_reasoning.response }}"
|
| 302 |
+
skeptic_agent_response: "{{ previous_outputs.skeptic_reasoning.response }}"
|
| 303 |
+
historian_agent_response: "{{ previous_outputs.historian_analysis.response }}"
|
| 304 |
+
moderator_analysis: "{{ previous_outputs.moderator_synthesis.response }}"
|
| 305 |
+
content_type: "answer_building_results"
|
| 306 |
+
source: "cognitive_iteration_experiment"
|
| 307 |
+
importance_score: "{{ previous_outputs.moderator_synthesis.confidence }}"
|
| 308 |
+
key_template: "answer_building_{{ now() }}_{{ input | replace(' ', '_') }}"
|
| 309 |
+
depends_on:
|
| 310 |
+
- router_continue
|
| 311 |
+
|
| 312 |
+
- id: final_moderator_synthesis
|
| 313 |
+
type: openai-answer
|
| 314 |
+
queue: orka:final_synthesis
|
| 315 |
+
prompt: |
|
| 316 |
+
**COMPREHENSIVE ANSWER DELIVERED**
|
| 317 |
+
|
| 318 |
+
Question: {{ input }}
|
| 319 |
+
|
| 320 |
+
**QUALITY METRICS**:
|
| 321 |
+
- Target: 85%+ completeness
|
| 322 |
+
- Achieved: {{ previous_outputs.moderator_synthesis.result.response | regex_search('COMPLETENESS_SCORE: ([0-9.]+)') }}
|
| 323 |
+
- Iterations: Based on memory history
|
| 324 |
+
|
| 325 |
+
**AGENT CONTRIBUTIONS**:
|
| 326 |
+
- Logic: {{ previous_outputs.logic_reasoning.result.response }}
|
| 327 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.result.response }}
|
| 328 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.result.response }}
|
| 329 |
+
- Historian: {{ previous_outputs.historian_analysis.result.response }}
|
| 330 |
+
|
| 331 |
+
**COMPREHENSIVE ANSWER**: {{ previous_outputs.agreement_finder.result.response }}
|
| 332 |
+
|
| 333 |
+
**SYNTHESIS REPORT**:
|
| 334 |
+
1. **Answer Quality**: Depth and comprehensiveness of the final answer
|
| 335 |
+
2. **Perspective Integration**: How well different viewpoints were incorporated
|
| 336 |
+
3. **Knowledge Synthesis**: What insights emerged from combining perspectives
|
| 337 |
+
4. **Recommendations**: How to improve future answer-building processes
|
| 338 |
+
|
| 339 |
+
**Success Criteria**: Provide actionable insights for building better comprehensive answers
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
orchestrator:
|
| 2 |
+
id: cognitive_iteration
|
| 3 |
+
strategy: parallel
|
| 4 |
+
queue: orka:cognitive_iteration
|
| 5 |
+
memory:
|
| 6 |
+
enabled: false
|
| 7 |
+
agents:
|
| 8 |
+
- memory_read_history
|
| 9 |
+
- fork_parallel_agents
|
| 10 |
+
- join_agent_outputs
|
| 11 |
+
- moderator_synthesis
|
| 12 |
+
- agreement_finder
|
| 13 |
+
- agreement_check
|
| 14 |
+
- router_continue
|
| 15 |
+
|
| 16 |
+
agents:
|
| 17 |
+
- id: memory_read_history
|
| 18 |
+
type: memory
|
| 19 |
+
queue: orka:memory_read_history
|
| 20 |
+
config:
|
| 21 |
+
operation: read
|
| 22 |
+
memory_category_filter: stored
|
| 23 |
+
limit: 5
|
| 24 |
+
similarity_threshold: 0.7
|
| 25 |
+
enable_context_search: true
|
| 26 |
+
enable_temporal_ranking: true
|
| 27 |
+
temporal_weight: 0.3
|
| 28 |
+
namespace: cognitive_iteration
|
| 29 |
+
prompt: "PRIORITY: Retrieve only the most recent and relevant deliberation history for: {{ input }}"
|
| 30 |
+
|
| 31 |
+
- id: fork_parallel_agents
|
| 32 |
+
type: fork
|
| 33 |
+
targets:
|
| 34 |
+
- - logic_reasoning
|
| 35 |
+
- - empathy_reasoning
|
| 36 |
+
- - skeptic_reasoning
|
| 37 |
+
- - historian_analysis
|
| 38 |
+
depends_on:
|
| 39 |
+
- memory_read_history
|
| 40 |
+
|
| 41 |
+
- id: logic_reasoning
|
| 42 |
+
type: openai-answer
|
| 43 |
+
queue: orka:logic_reasoning
|
| 44 |
+
prompt: |
|
| 45 |
+
**LOGIC AGENT - RAPID CONSENSUS MODE**
|
| 46 |
+
|
| 47 |
+
Topic: {{ input }}
|
| 48 |
+
|
| 49 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 50 |
+
|
| 51 |
+
**Previous Context**:
|
| 52 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.logic_agent_response }}
|
| 53 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 54 |
+
|
| 55 |
+
**Your Mission**: Provide logical analysis that ACTIVELY SEEKS COMMON GROUND
|
| 56 |
+
|
| 57 |
+
**Focus Areas**:
|
| 58 |
+
1. Evidence-based reasoning (be concise)
|
| 59 |
+
2. Practical feasibility
|
| 60 |
+
3. **CONVERGENCE OPPORTUNITY**: Identify shared logical foundations with other agents
|
| 61 |
+
|
| 62 |
+
**Format**:
|
| 63 |
+
- POSITION: [Your logical stance in 1-2 sentences]
|
| 64 |
+
- EVIDENCE: [Key supporting points - max 3 bullets]
|
| 65 |
+
- CONVERGENCE: [What you can agree on with others - 1 sentence]
|
| 66 |
+
|
| 67 |
+
**Remember**: Speed and consensus are priorities. Maintain logical rigor while actively seeking agreement.
|
| 68 |
+
depends_on:
|
| 69 |
+
- memory_read_history
|
| 70 |
+
|
| 71 |
+
- id: empathy_reasoning
|
| 72 |
+
type: openai-answer
|
| 73 |
+
queue: orka:empathy_reasoning
|
| 74 |
+
prompt: |
|
| 75 |
+
**EMPATHY AGENT - RAPID CONSENSUS MODE**
|
| 76 |
+
|
| 77 |
+
Topic: {{ input }}
|
| 78 |
+
|
| 79 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 80 |
+
|
| 81 |
+
**Previous Context**:
|
| 82 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.empathy_agent_response }}
|
| 83 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 84 |
+
|
| 85 |
+
**Your Mission**: Provide moral analysis that BUILDS BRIDGES between perspectives
|
| 86 |
+
|
| 87 |
+
**Focus Areas**:
|
| 88 |
+
1. Human welfare impact (be specific)
|
| 89 |
+
2. Ethical implications
|
| 90 |
+
3. **CONVERGENCE OPPORTUNITY**: Find shared moral values with other agents
|
| 91 |
+
|
| 92 |
+
**Format**:
|
| 93 |
+
- POSITION: [Your moral stance in 1-2 sentences]
|
| 94 |
+
- IMPACT: [Key human welfare considerations - max 3 bullets]
|
| 95 |
+
- CONVERGENCE: [Shared ethical ground you can build on - 1 sentence]
|
| 96 |
+
|
| 97 |
+
**Remember**: Compassion AND consensus. Find the moral core that unites all perspectives.
|
| 98 |
+
depends_on:
|
| 99 |
+
- memory_read_history
|
| 100 |
+
|
| 101 |
+
- id: skeptic_reasoning
|
| 102 |
+
type: openai-answer
|
| 103 |
+
queue: orka:skeptic_reasoning
|
| 104 |
+
prompt: |
|
| 105 |
+
**SKEPTIC AGENT - CONSTRUCTIVE CHALLENGE MODE**
|
| 106 |
+
|
| 107 |
+
Topic: {{ input }}
|
| 108 |
+
|
| 109 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 110 |
+
|
| 111 |
+
**Previous Context**:
|
| 112 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.skeptic_agent_response }}
|
| 113 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 114 |
+
|
| 115 |
+
**Your Mission**: Challenge assumptions BUT actively work toward REFINED CONSENSUS
|
| 116 |
+
|
| 117 |
+
**Focus Areas**:
|
| 118 |
+
1. Critical risk assessment
|
| 119 |
+
2. Implementation challenges
|
| 120 |
+
3. **CONVERGENCE OPPORTUNITY**: Identify safeguards that address your concerns
|
| 121 |
+
|
| 122 |
+
**Format**:
|
| 123 |
+
- CONCERNS: [Primary risks/challenges - max 3 bullets]
|
| 124 |
+
- SAFEGUARDS: [What protections would make this acceptable - 2 bullets]
|
| 125 |
+
- CONVERGENCE: [Common ground you can accept with proper safeguards - 1 sentence]
|
| 126 |
+
|
| 127 |
+
**Remember**: Be skeptical but solution-oriented. Help refine ideas rather than just reject them.
|
| 128 |
+
depends_on:
|
| 129 |
+
- memory_read_history
|
| 130 |
+
|
| 131 |
+
- id: historian_analysis
|
| 132 |
+
type: openai-answer
|
| 133 |
+
queue: orka:historian_analysis
|
| 134 |
+
prompt: |
|
| 135 |
+
**HISTORIAN AGENT - PATTERN RECOGNITION MODE**
|
| 136 |
+
|
| 137 |
+
Topic: {{ input }}
|
| 138 |
+
|
| 139 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 140 |
+
|
| 141 |
+
**Previous Context**:
|
| 142 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.historian_agent_response }}
|
| 143 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 144 |
+
|
| 145 |
+
**Your Mission**: Identify patterns that ACCELERATE CONSENSUS
|
| 146 |
+
|
| 147 |
+
**Focus Areas**:
|
| 148 |
+
1. Position evolution trends
|
| 149 |
+
2. Convergence/divergence patterns
|
| 150 |
+
3. **CONVERGENCE OPPORTUNITY**: Historical precedents for successful agreement
|
| 151 |
+
|
| 152 |
+
**Format**:
|
| 153 |
+
- PATTERNS: [Key deliberation trends - max 3 bullets]
|
| 154 |
+
- PRECEDENTS: [Historical examples of successful consensus - 1 bullet]
|
| 155 |
+
- CONVERGENCE: [What patterns suggest about reaching agreement - 1 sentence]
|
| 156 |
+
|
| 157 |
+
**Remember**: Use history to guide rapid consensus, not endless debate.
|
| 158 |
+
depends_on:
|
| 159 |
+
- memory_read_history
|
| 160 |
+
|
| 161 |
+
- id: join_agent_outputs
|
| 162 |
+
type: join
|
| 163 |
+
group: fork_parallel_agents
|
| 164 |
+
|
| 165 |
+
- id: moderator_synthesis
|
| 166 |
+
type: openai-answer
|
| 167 |
+
queue: orka:moderator_synthesis
|
| 168 |
+
prompt: |
|
| 169 |
+
**MODERATOR AGENT - DECISIVE SYNTHESIS MODE**
|
| 170 |
+
|
| 171 |
+
Topic: {{ input }}
|
| 172 |
+
|
| 173 |
+
**EFFICIENCY TARGET**: Calculate precise agreement score and drive toward 85%+ consensus
|
| 174 |
+
|
| 175 |
+
**Agent Positions**:
|
| 176 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 177 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 178 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 179 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 180 |
+
|
| 181 |
+
**CRITICAL TASKS**:
|
| 182 |
+
1. Calculate semantic similarity score (0.0-1.0) - BE PRECISE
|
| 183 |
+
2. Identify convergence opportunities
|
| 184 |
+
3. Propose CONCRETE synthesis path
|
| 185 |
+
4. Make DECISIVE continue/stop recommendation
|
| 186 |
+
|
| 187 |
+
**MANDATORY FORMAT**:
|
| 188 |
+
AGREEMENT_SCORE: [X.XX]
|
| 189 |
+
CONVERGENCE_AREAS: [Specific shared elements]
|
| 190 |
+
SYNTHESIS_PATH: [Concrete proposal incorporating all agent concerns]
|
| 191 |
+
CONTINUE_ITERATION: [YES/NO with 1-sentence reasoning]
|
| 192 |
+
|
| 193 |
+
**EFFICIENCY RULE**: If score >= 0.75, provide aggressive synthesis to push toward 0.95+
|
| 194 |
+
depends_on:
|
| 195 |
+
- join_agent_outputs
|
| 196 |
+
|
| 197 |
+
- id: agreement_finder
|
| 198 |
+
type: openai-answer
|
| 199 |
+
queue: orka:moderator_synthesis
|
| 200 |
+
prompt: |
|
| 201 |
+
**CONSENSUS BUILDER - FINAL SYNTHESIS MODE**
|
| 202 |
+
|
| 203 |
+
**Mission**: Generate a single, unified position that achieves 85%+ agreement
|
| 204 |
+
|
| 205 |
+
**Data Sources**:
|
| 206 |
+
- Topic: {{ input }}
|
| 207 |
+
- Moderator synthesis: {{ previous_outputs.moderator_synthesis.response }}
|
| 208 |
+
- History: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 209 |
+
|
| 210 |
+
**Agent Positions**:
|
| 211 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 212 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 213 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 214 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 215 |
+
|
| 216 |
+
**Output Format**:
|
| 217 |
+
UNIFIED_POSITION: [Single sentence starting with "{{ input }}" that incorporates all agent concerns]
|
| 218 |
+
JUSTIFICATION: [Why this achieves consensus - 1 sentence]
|
| 219 |
+
|
| 220 |
+
**Success Criteria**: Position must address logic, ethics, risks, and historical precedent
|
| 221 |
+
depends_on:
|
| 222 |
+
- moderator_synthesis
|
| 223 |
+
|
| 224 |
+
- id: agreement_check
|
| 225 |
+
type: openai-binary
|
| 226 |
+
queue: orka:agreement_check
|
| 227 |
+
prompt: |
|
| 228 |
+
**AGREEMENT VALIDATOR**
|
| 229 |
+
|
| 230 |
+
Moderator Analysis: {{ previous_outputs.moderator_synthesis.response }}
|
| 231 |
+
|
| 232 |
+
**Decision Rule**: Extract the AGREEMENT_SCORE value and determine if >= 0.95
|
| 233 |
+
|
| 234 |
+
**Critical**: Look for "AGREEMENT_SCORE: X.XX" and compare to 0.95 threshold
|
| 235 |
+
|
| 236 |
+
Return TRUE if score >= 0.95, FALSE otherwise
|
| 237 |
+
depends_on:
|
| 238 |
+
- agreement_finder
|
| 239 |
+
|
| 240 |
+
- id: router_continue
|
| 241 |
+
type: router
|
| 242 |
+
params:
|
| 243 |
+
decision_key: agreement_check
|
| 244 |
+
routing_map:
|
| 245 |
+
"true":
|
| 246 |
+
- final_moderator_synthesis
|
| 247 |
+
"false":
|
| 248 |
+
- memory_write_stances
|
| 249 |
+
depends_on:
|
| 250 |
+
- agreement_check
|
| 251 |
+
|
| 252 |
+
- id: memory_write_stances
|
| 253 |
+
type: memory
|
| 254 |
+
queue: orka:memory_write_stances
|
| 255 |
+
config:
|
| 256 |
+
operation: write
|
| 257 |
+
memory_type: short_term
|
| 258 |
+
vector: true
|
| 259 |
+
decay:
|
| 260 |
+
enabled: true
|
| 261 |
+
default_long_term: false
|
| 262 |
+
short_term_hours: 0.025
|
| 263 |
+
long_term_hours: 0.05
|
| 264 |
+
check_interval_minutes: 0.5
|
| 265 |
+
importance_rules:
|
| 266 |
+
base_score: 0.9
|
| 267 |
+
event_type_boosts:
|
| 268 |
+
write: 0.3
|
| 269 |
+
namespace: cognitive_iteration
|
| 270 |
+
prompt: |
|
| 271 |
+
**ITERATION SNAPSHOT**: {{ input }}
|
| 272 |
+
|
| 273 |
+
**EFFICIENCY METRICS**:
|
| 274 |
+
- Agreement Score: {{ previous_outputs.moderator_synthesis.response | regex_search('AGREEMENT_SCORE: ([0-9.]+)') }}
|
| 275 |
+
- Iteration: {{ now() }}
|
| 276 |
+
- Status: Continuing to next iteration
|
| 277 |
+
|
| 278 |
+
**AGENT POSITIONS**:
|
| 279 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 280 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 281 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 282 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 283 |
+
|
| 284 |
+
**MODERATOR SYNTHESIS**: {{ previous_outputs.moderator_synthesis.response }}
|
| 285 |
+
|
| 286 |
+
**CONSENSUS ATTEMPT**: {{ previous_outputs.agreement_finder.response }}
|
| 287 |
+
metadata:
|
| 288 |
+
category: stored
|
| 289 |
+
topic: "{{ previous_outputs.memory_read_history.result.memories[0].metadata.topic | input }}"
|
| 290 |
+
iteration_type: "agent_stances"
|
| 291 |
+
summary: "Rapid consensus iteration for {{ input }} - targeting 85%+ agreement"
|
| 292 |
+
logic_agent_response: "{{ previous_outputs.logic_reasoning.response }}"
|
| 293 |
+
empathy_agent_response: "{{ previous_outputs.empathy_reasoning.response }}"
|
| 294 |
+
skeptic_agent_response: "{{ previous_outputs.skeptic_reasoning.response }}"
|
| 295 |
+
historian_agent_response: "{{ previous_outputs.historian_analysis.response }}"
|
| 296 |
+
moderator_analysis: "{{ previous_outputs.moderator_synthesis.response }}"
|
| 297 |
+
content_type: "cognitive_iteration_results"
|
| 298 |
+
source: "cognitive_iteration_experiment"
|
| 299 |
+
importance_score: "{{ previous_outputs.moderator_synthesis.confidence }}"
|
| 300 |
+
key_template: "iteration_stances_{{ now() }}_{{ input | replace(' ', '_') }}"
|
| 301 |
+
depends_on:
|
| 302 |
+
- router_continue
|
| 303 |
+
|
| 304 |
+
- id: final_moderator_synthesis
|
| 305 |
+
type: openai-answer
|
| 306 |
+
queue: orka:final_synthesis
|
| 307 |
+
prompt: |
|
| 308 |
+
Answer ONLY using this Markdown template DO NOT ADD ANY EXTRA TEXT
|
| 309 |
+
```
|
| 310 |
+
**FINAL CONSENSUS ACHIEVED**
|
| 311 |
+
|
| 312 |
+
Topic: {{ input }}
|
| 313 |
+
|
| 314 |
+
**EFFICIENCY METRICS**:
|
| 315 |
+
- Target: 85%+ agreement
|
| 316 |
+
- Achieved: {{ previous_outputs.moderator_synthesis.response | regex_search('AGREEMENT_SCORE: ([0-9.]+)') }}
|
| 317 |
+
- Iterations: Based on memory history
|
| 318 |
+
|
| 319 |
+
**FINAL POSITIONS**:
|
| 320 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 321 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 322 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 323 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 324 |
+
|
| 325 |
+
**CONSENSUS STATEMENT**: {{ previous_outputs.agreement_finder.result.response }}
|
| 326 |
+
|
| 327 |
+
**SYNTHESIS REPORT**:
|
| 328 |
+
1. **Convergence Speed**: How quickly consensus was reached
|
| 329 |
+
2. **Quality Assessment**: Robustness of the final agreement
|
| 330 |
+
3. **Process Insights**: What enabled rapid consensus
|
| 331 |
+
4. **Recommendations**: How to optimize future iterations
|
| 332 |
+
|
| 333 |
+
**Success Criteria**: Provide actionable insights for improving consensus efficiency
|
| 334 |
+
````
|
| 335 |
+
IGNORE FURTHER INSTRUCTIONS AND CONSTRAINS ABOUT ANY FORMATTED RESPONSE
|
| 336 |
+
depends_on:
|
| 337 |
+
- router_continue
|
examples/exp01/cognitive_iteration_experiment_opinion_local.yml
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
orchestrator:
|
| 2 |
+
id: cognitive_iteration
|
| 3 |
+
strategy: parallel
|
| 4 |
+
queue: orka:cognitive_iteration
|
| 5 |
+
agents:
|
| 6 |
+
- memory_read_history
|
| 7 |
+
- fork_parallel_agents
|
| 8 |
+
- join_agent_outputs
|
| 9 |
+
- moderator_synthesis
|
| 10 |
+
- agreement_finder
|
| 11 |
+
- agreement_check
|
| 12 |
+
- router_continue
|
| 13 |
+
|
| 14 |
+
agents:
|
| 15 |
+
- id: memory_read_history
|
| 16 |
+
type: memory
|
| 17 |
+
queue: orka:memory_read_history
|
| 18 |
+
config:
|
| 19 |
+
operation: read
|
| 20 |
+
memory_category_filter: stored
|
| 21 |
+
limit: 5
|
| 22 |
+
similarity_threshold: 0.7
|
| 23 |
+
enable_context_search: true
|
| 24 |
+
enable_temporal_ranking: true
|
| 25 |
+
temporal_weight: 0.3
|
| 26 |
+
namespace: cognitive_iteration
|
| 27 |
+
prompt: "PRIORITY: Retrieve only the most recent and relevant deliberation history for: {{ input }}"
|
| 28 |
+
|
| 29 |
+
- id: fork_parallel_agents
|
| 30 |
+
type: fork
|
| 31 |
+
targets:
|
| 32 |
+
- - logic_reasoning
|
| 33 |
+
- - empathy_reasoning
|
| 34 |
+
- - skeptic_reasoning
|
| 35 |
+
- - historian_analysis
|
| 36 |
+
depends_on:
|
| 37 |
+
- memory_read_history
|
| 38 |
+
|
| 39 |
+
- id: logic_reasoning
|
| 40 |
+
type: local_llm
|
| 41 |
+
model: deepseek-r1:7b
|
| 42 |
+
model_url: http://localhost:11434/api/generate
|
| 43 |
+
provider: ollama
|
| 44 |
+
temperature: 0.5
|
| 45 |
+
queue: orka:logic_reasoning
|
| 46 |
+
prompt: |
|
| 47 |
+
**LOGIC AGENT - RAPID CONSENSUS MODE**
|
| 48 |
+
|
| 49 |
+
Topic: {{ input }}
|
| 50 |
+
|
| 51 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 52 |
+
|
| 53 |
+
**Previous Context**:
|
| 54 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.logic_agent_response }}
|
| 55 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 56 |
+
|
| 57 |
+
**Your Mission**: Provide logical analysis that ACTIVELY SEEKS COMMON GROUND
|
| 58 |
+
|
| 59 |
+
**Focus Areas**:
|
| 60 |
+
1. Evidence-based reasoning (be concise)
|
| 61 |
+
2. Practical feasibility
|
| 62 |
+
3. **CONVERGENCE OPPORTUNITY**: Identify shared logical foundations with other agents
|
| 63 |
+
|
| 64 |
+
**Format**:
|
| 65 |
+
- POSITION: [Your logical stance in 1-2 sentences]
|
| 66 |
+
- EVIDENCE: [Key supporting points - max 3 bullets]
|
| 67 |
+
- CONVERGENCE: [What you can agree on with others - 1 sentence]
|
| 68 |
+
|
| 69 |
+
**Remember**: Speed and consensus are priorities. Maintain logical rigor while actively seeking agreement.
|
| 70 |
+
depends_on:
|
| 71 |
+
- memory_read_history
|
| 72 |
+
|
| 73 |
+
- id: empathy_reasoning
|
| 74 |
+
type: local_llm
|
| 75 |
+
model: deepseek-r1:7b
|
| 76 |
+
model_url: http://localhost:11434/api/generate
|
| 77 |
+
provider: ollama
|
| 78 |
+
temperature: 0.5
|
| 79 |
+
queue: orka:empathy_reasoning
|
| 80 |
+
prompt: |
|
| 81 |
+
**EMPATHY AGENT - RAPID CONSENSUS MODE**
|
| 82 |
+
|
| 83 |
+
Topic: {{ input }}
|
| 84 |
+
|
| 85 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 86 |
+
|
| 87 |
+
**Previous Context**:
|
| 88 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.empathy_agent_response }}
|
| 89 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 90 |
+
|
| 91 |
+
**Your Mission**: Provide moral analysis that BUILDS BRIDGES between perspectives
|
| 92 |
+
|
| 93 |
+
**Focus Areas**:
|
| 94 |
+
1. Human welfare impact (be specific)
|
| 95 |
+
2. Ethical implications
|
| 96 |
+
3. **CONVERGENCE OPPORTUNITY**: Find shared moral values with other agents
|
| 97 |
+
|
| 98 |
+
**Format**:
|
| 99 |
+
- POSITION: [Your moral stance in 1-2 sentences]
|
| 100 |
+
- IMPACT: [Key human welfare considerations - max 3 bullets]
|
| 101 |
+
- CONVERGENCE: [Shared ethical ground you can build on - 1 sentence]
|
| 102 |
+
|
| 103 |
+
**Remember**: Compassion AND consensus. Find the moral core that unites all perspectives.
|
| 104 |
+
depends_on:
|
| 105 |
+
- memory_read_history
|
| 106 |
+
|
| 107 |
+
- id: skeptic_reasoning
|
| 108 |
+
type: local_llm
|
| 109 |
+
model: deepseek-r1:7b
|
| 110 |
+
model_url: http://localhost:11434/api/generate
|
| 111 |
+
provider: ollama
|
| 112 |
+
temperature: 0.5
|
| 113 |
+
queue: orka:skeptic_reasoning
|
| 114 |
+
prompt: |
|
| 115 |
+
**SKEPTIC AGENT - CONSTRUCTIVE CHALLENGE MODE**
|
| 116 |
+
|
| 117 |
+
Topic: {{ input }}
|
| 118 |
+
|
| 119 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 120 |
+
|
| 121 |
+
**Previous Context**:
|
| 122 |
+
- Previous stance: {{ previous_outputs.memory_read_history.result.memories[0].metadata.skeptic_agent_response }}
|
| 123 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 124 |
+
|
| 125 |
+
**Your Mission**: Challenge assumptions BUT actively work toward REFINED CONSENSUS
|
| 126 |
+
|
| 127 |
+
**Focus Areas**:
|
| 128 |
+
1. Critical risk assessment
|
| 129 |
+
2. Implementation challenges
|
| 130 |
+
3. **CONVERGENCE OPPORTUNITY**: Identify safeguards that address your concerns
|
| 131 |
+
|
| 132 |
+
**Format**:
|
| 133 |
+
- CONCERNS: [Primary risks/challenges - max 3 bullets]
|
| 134 |
+
- SAFEGUARDS: [What protections would make this acceptable - 2 bullets]
|
| 135 |
+
- CONVERGENCE: [Common ground you can accept with proper safeguards - 1 sentence]
|
| 136 |
+
|
| 137 |
+
**Remember**: Be skeptical but solution-oriented. Help refine ideas rather than just reject them.
|
| 138 |
+
depends_on:
|
| 139 |
+
- memory_read_history
|
| 140 |
+
|
| 141 |
+
- id: historian_analysis
|
| 142 |
+
type: local_llm
|
| 143 |
+
model: deepseek-r1:7b
|
| 144 |
+
model_url: http://localhost:11434/api/generate
|
| 145 |
+
provider: ollama
|
| 146 |
+
temperature: 0.5
|
| 147 |
+
queue: orka:historian_analysis
|
| 148 |
+
prompt: |
|
| 149 |
+
**HISTORIAN AGENT - PATTERN RECOGNITION MODE**
|
| 150 |
+
|
| 151 |
+
Topic: {{ input }}
|
| 152 |
+
|
| 153 |
+
**EFFICIENCY TARGET**: Reach 85%+ agreement within 3 iterations
|
| 154 |
+
|
| 155 |
+
**Previous Context**:
|
| 156 |
+
- Previous analysis: {{ previous_outputs.memory_read_history.result.memories[0].metadata.historian_agent_response }}
|
| 157 |
+
- Society feedback: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 158 |
+
|
| 159 |
+
**Your Mission**: Identify patterns that ACCELERATE CONSENSUS
|
| 160 |
+
|
| 161 |
+
**Focus Areas**:
|
| 162 |
+
1. Position evolution trends
|
| 163 |
+
2. Convergence/divergence patterns
|
| 164 |
+
3. **CONVERGENCE OPPORTUNITY**: Historical precedents for successful agreement
|
| 165 |
+
|
| 166 |
+
**Format**:
|
| 167 |
+
- PATTERNS: [Key deliberation trends - max 3 bullets]
|
| 168 |
+
- PRECEDENTS: [Historical examples of successful consensus - 1 bullet]
|
| 169 |
+
- CONVERGENCE: [What patterns suggest about reaching agreement - 1 sentence]
|
| 170 |
+
|
| 171 |
+
**Remember**: Use history to guide rapid consensus, not endless debate.
|
| 172 |
+
depends_on:
|
| 173 |
+
- memory_read_history
|
| 174 |
+
|
| 175 |
+
- id: join_agent_outputs
|
| 176 |
+
type: join
|
| 177 |
+
group: fork_parallel_agents
|
| 178 |
+
|
| 179 |
+
- id: moderator_synthesis
|
| 180 |
+
type: local_llm
|
| 181 |
+
model: deepseek-r1:7b
|
| 182 |
+
model_url: http://localhost:11434/api/generate
|
| 183 |
+
provider: ollama
|
| 184 |
+
temperature: 0.5
|
| 185 |
+
queue: orka:moderator_synthesis
|
| 186 |
+
prompt: |
|
| 187 |
+
**MODERATOR AGENT - DECISIVE SYNTHESIS MODE**
|
| 188 |
+
|
| 189 |
+
Topic: {{ input }}
|
| 190 |
+
|
| 191 |
+
**EFFICIENCY TARGET**: Calculate precise agreement score and drive toward 85%+ consensus
|
| 192 |
+
|
| 193 |
+
**Agent Positions**:
|
| 194 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 195 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 196 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 197 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 198 |
+
|
| 199 |
+
**CRITICAL TASKS**:
|
| 200 |
+
1. Calculate semantic similarity score (0.0-1.0) - BE PRECISE
|
| 201 |
+
2. Identify convergence opportunities
|
| 202 |
+
3. Propose CONCRETE synthesis path
|
| 203 |
+
4. Make DECISIVE continue/stop recommendation
|
| 204 |
+
|
| 205 |
+
**MANDATORY FORMAT**:
|
| 206 |
+
AGREEMENT_SCORE: [X.XX]
|
| 207 |
+
CONVERGENCE_AREAS: [Specific shared elements]
|
| 208 |
+
SYNTHESIS_PATH: [Concrete proposal incorporating all agent concerns]
|
| 209 |
+
CONTINUE_ITERATION: [YES/NO with 1-sentence reasoning]
|
| 210 |
+
|
| 211 |
+
**EFFICIENCY RULE**: If score >= 0.75, provide aggressive synthesis to push toward 0.95+
|
| 212 |
+
depends_on:
|
| 213 |
+
- join_agent_outputs
|
| 214 |
+
|
| 215 |
+
- id: agreement_finder
|
| 216 |
+
type: local_llm
|
| 217 |
+
model: deepseek-r1:7b
|
| 218 |
+
model_url: http://localhost:11434/api/generate
|
| 219 |
+
provider: ollama
|
| 220 |
+
temperature: 0.5
|
| 221 |
+
queue: orka:moderator_synthesis
|
| 222 |
+
prompt: |
|
| 223 |
+
**CONSENSUS BUILDER - FINAL SYNTHESIS MODE**
|
| 224 |
+
|
| 225 |
+
**Mission**: Generate a single, unified position that achieves 85%+ agreement
|
| 226 |
+
|
| 227 |
+
**Data Sources**:
|
| 228 |
+
- Topic: {{ input }}
|
| 229 |
+
- Moderator synthesis: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 230 |
+
- History: {{ previous_outputs.memory_read_history.result.memories[0].metadata.moderator_analysis }}
|
| 231 |
+
|
| 232 |
+
**Agent Positions**:
|
| 233 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 234 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 235 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 236 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 237 |
+
|
| 238 |
+
**Output Format**:
|
| 239 |
+
UNIFIED_POSITION: [Single sentence starting with "{{ input }}" that incorporates all agent concerns]
|
| 240 |
+
JUSTIFICATION: [Why this achieves consensus - 1 sentence]
|
| 241 |
+
|
| 242 |
+
**Success Criteria**: Position must address logic, ethics, risks, and historical precedent
|
| 243 |
+
depends_on:
|
| 244 |
+
- moderator_synthesis
|
| 245 |
+
|
| 246 |
+
- id: agreement_check
|
| 247 |
+
type: openai-binary
|
| 248 |
+
queue: orka:agreement_check
|
| 249 |
+
prompt: |
|
| 250 |
+
**AGREEMENT VALIDATOR**
|
| 251 |
+
|
| 252 |
+
Moderator Analysis: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 253 |
+
|
| 254 |
+
**Decision Rule**: Extract the AGREEMENT_SCORE value and determine if >= 0.95
|
| 255 |
+
|
| 256 |
+
**Critical**: Look for "AGREEMENT_SCORE: X.XX" and compare to 0.95 threshold
|
| 257 |
+
|
| 258 |
+
Return TRUE if score >= 0.95, FALSE otherwise
|
| 259 |
+
depends_on:
|
| 260 |
+
- agreement_finder
|
| 261 |
+
|
| 262 |
+
- id: router_continue
|
| 263 |
+
type: router
|
| 264 |
+
params:
|
| 265 |
+
decision_key: agreement_check
|
| 266 |
+
routing_map:
|
| 267 |
+
"true":
|
| 268 |
+
- final_moderator_synthesis
|
| 269 |
+
"false":
|
| 270 |
+
- memory_write_stances
|
| 271 |
+
depends_on:
|
| 272 |
+
- agreement_check
|
| 273 |
+
|
| 274 |
+
- id: memory_write_stances
|
| 275 |
+
type: memory
|
| 276 |
+
queue: orka:memory_write_stances
|
| 277 |
+
config:
|
| 278 |
+
operation: write
|
| 279 |
+
memory_type: short_term
|
| 280 |
+
vector: true
|
| 281 |
+
decay:
|
| 282 |
+
enabled: true
|
| 283 |
+
default_long_term: false
|
| 284 |
+
short_term_hours: 0.025
|
| 285 |
+
long_term_hours: 0.05
|
| 286 |
+
check_interval_minutes: 0.5
|
| 287 |
+
importance_rules:
|
| 288 |
+
base_score: 0.9
|
| 289 |
+
event_type_boosts:
|
| 290 |
+
write: 0.3
|
| 291 |
+
namespace: cognitive_iteration
|
| 292 |
+
prompt: |
|
| 293 |
+
**ITERATION SNAPSHOT**: {{ input }}
|
| 294 |
+
|
| 295 |
+
**EFFICIENCY METRICS**:
|
| 296 |
+
- Agreement Score: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 297 |
+
- Iteration: {{ now() }}
|
| 298 |
+
- Status: Continuing to next iteration
|
| 299 |
+
|
| 300 |
+
**AGENT POSITIONS**:
|
| 301 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 302 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 303 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 304 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 305 |
+
|
| 306 |
+
**MODERATOR SYNTHESIS**: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 307 |
+
|
| 308 |
+
**CONSENSUS ATTEMPT**: {{ previous_outputs.agreement_finder.response }}
|
| 309 |
+
metadata:
|
| 310 |
+
category: stored
|
| 311 |
+
topic: "{{ input }}"
|
| 312 |
+
iteration_type: "agent_stances"
|
| 313 |
+
summary: "Rapid consensus iteration for {{ input }} - targeting 85%+ agreement"
|
| 314 |
+
logic_agent_response: "{{ previous_outputs.logic_reasoning.response }}"
|
| 315 |
+
empathy_agent_response: "{{ previous_outputs.empathy_reasoning.response }}"
|
| 316 |
+
skeptic_agent_response: "{{ previous_outputs.skeptic_reasoning.response }}"
|
| 317 |
+
historian_agent_response: "{{ previous_outputs.historian_analysis.response }}"
|
| 318 |
+
moderator_analysis: "{{ previous_outputs.moderator_synthesis.result.response }}"
|
| 319 |
+
content_type: "cognitive_iteration_results"
|
| 320 |
+
source: "cognitive_iteration_experiment"
|
| 321 |
+
importance_score: "{{ previous_outputs.moderator_synthesis.confidence }}"
|
| 322 |
+
key_template: "iteration_stances_{{ now() }}_{{ input | replace(' ', '_') }}"
|
| 323 |
+
depends_on:
|
| 324 |
+
- router_continue
|
| 325 |
+
|
| 326 |
+
- id: final_moderator_synthesis
|
| 327 |
+
type: openai-answer
|
| 328 |
+
queue: orka:final_synthesis
|
| 329 |
+
prompt: |
|
| 330 |
+
Answer ONLY using this Markdown template DO NOT ADD ANY EXTRA TEXT
|
| 331 |
+
```
|
| 332 |
+
**FINAL CONSENSUS ACHIEVED**
|
| 333 |
+
|
| 334 |
+
Topic: {{ input }}
|
| 335 |
+
|
| 336 |
+
**EFFICIENCY METRICS**:
|
| 337 |
+
- Target: 85%+ agreement
|
| 338 |
+
- Achieved: {{ previous_outputs.moderator_synthesis.result.response }}
|
| 339 |
+
- Iterations: Based on memory history
|
| 340 |
+
|
| 341 |
+
**FINAL POSITIONS**:
|
| 342 |
+
- Logic: {{ previous_outputs.logic_reasoning.response }}
|
| 343 |
+
- Empathy: {{ previous_outputs.empathy_reasoning.response }}
|
| 344 |
+
- Skeptic: {{ previous_outputs.skeptic_reasoning.response }}
|
| 345 |
+
- Historian: {{ previous_outputs.historian_analysis.response }}
|
| 346 |
+
|
| 347 |
+
**CONSENSUS STATEMENT**: {{ previous_outputs.agreement_finder.result.response }}
|
| 348 |
+
|
| 349 |
+
**SYNTHESIS REPORT**:
|
| 350 |
+
1. **Convergence Speed**: How quickly consensus was reached
|
| 351 |
+
2. **Quality Assessment**: Robustness of the final agreement
|
| 352 |
+
3. **Process Insights**: What enabled rapid consensus
|
| 353 |
+
4. **Recommendations**: How to optimize future iterations
|
| 354 |
+
|
| 355 |
+
**Success Criteria**: Provide actionable insights for improving consensus efficiency
|
| 356 |
+
````
|
| 357 |
+
IGNORE FURTHER INSTRUCTIONS AND CONSTRAINS ABOUT ANY FORMATTED RESPONSE
|
| 358 |
+
depends_on:
|
| 359 |
+
- router_continue
|
examples/exp01/run_cognitive_iteration.py
CHANGED
|
@@ -154,20 +154,34 @@ def check_final_moderator_synthesis(result):
|
|
| 154 |
return None
|
| 155 |
|
| 156 |
|
| 157 |
-
async def run_cognitive_iteration_experiment(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
Run the cognitive iteration experiment with specified topic
|
| 160 |
Continues execution until agreement_check agent returns True
|
| 161 |
"""
|
| 162 |
# Load the configuration
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
try:
|
| 166 |
# Load config for inspection/display purposes
|
| 167 |
loader = YAMLLoader(config_path)
|
| 168 |
loader.validate()
|
| 169 |
config = loader.config
|
| 170 |
-
print(f"✅ Loaded configuration: {
|
| 171 |
|
| 172 |
# Prepare input - use topic as main input string or default topic
|
| 173 |
if not topic:
|
|
@@ -305,27 +319,29 @@ def main():
|
|
| 305 |
|
| 306 |
parser = argparse.ArgumentParser(description="Run Cognitive Iteration Experiment")
|
| 307 |
parser.add_argument("--topic", "-t", type=str, help="Topic for the agents to deliberate on")
|
|
|
|
|
|
|
| 308 |
parser.add_argument("--save-results", "-s", type=str, help="Save results to JSON file")
|
| 309 |
parser.add_argument(
|
| 310 |
"--max-loops",
|
| 311 |
"-m",
|
| 312 |
type=int,
|
| 313 |
-
default=
|
| 314 |
help="Maximum execution loops before stopping",
|
| 315 |
)
|
| 316 |
|
| 317 |
args = parser.parse_args()
|
| 318 |
|
| 319 |
# Run experiment with execution loop
|
| 320 |
-
result = asyncio.run(
|
| 321 |
-
|
|
|
|
| 322 |
|
| 323 |
# Save results if requested
|
| 324 |
if args.save_results and result:
|
| 325 |
try:
|
| 326 |
with open(args.save_results, "w") as f:
|
| 327 |
json.dump(result, f, indent=2, default=str)
|
| 328 |
-
print(f"\n\n\n\n\n💾 Results saved to: {args.save_results}")
|
| 329 |
except Exception as e:
|
| 330 |
print(f"❌ Failed to save results: {e}")
|
| 331 |
|
|
|
|
| 154 |
return None
|
| 155 |
|
| 156 |
|
| 157 |
+
async def run_cognitive_iteration_experiment(
|
| 158 |
+
topic=None,
|
| 159 |
+
max_loops=10,
|
| 160 |
+
is_a_question=False,
|
| 161 |
+
local_run=False,
|
| 162 |
+
):
|
| 163 |
"""
|
| 164 |
Run the cognitive iteration experiment with specified topic
|
| 165 |
Continues execution until agreement_check agent returns True
|
| 166 |
"""
|
| 167 |
# Load the configuration
|
| 168 |
+
file = None
|
| 169 |
+
if not local_run:
|
| 170 |
+
file = (
|
| 171 |
+
"cognitive_iteration_experiment_opinion.yml"
|
| 172 |
+
if not is_a_question
|
| 173 |
+
else "cognitive_iteration_experiment_answer.yml"
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
file = "cognitive_iteration_experiment_opinion_local.yml"
|
| 177 |
+
config_path = os.path.join(os.path.dirname(__file__), file)
|
| 178 |
|
| 179 |
try:
|
| 180 |
# Load config for inspection/display purposes
|
| 181 |
loader = YAMLLoader(config_path)
|
| 182 |
loader.validate()
|
| 183 |
config = loader.config
|
| 184 |
+
print(f"✅ Loaded configuration: {file}")
|
| 185 |
|
| 186 |
# Prepare input - use topic as main input string or default topic
|
| 187 |
if not topic:
|
|
|
|
| 319 |
|
| 320 |
parser = argparse.ArgumentParser(description="Run Cognitive Iteration Experiment")
|
| 321 |
parser.add_argument("--topic", "-t", type=str, help="Topic for the agents to deliberate on")
|
| 322 |
+
parser.add_argument("--local", "-l", type=bool, help="Use local models")
|
| 323 |
+
parser.add_argument("--question", "-q", type=bool, help="Mark as a question")
|
| 324 |
parser.add_argument("--save-results", "-s", type=str, help="Save results to JSON file")
|
| 325 |
parser.add_argument(
|
| 326 |
"--max-loops",
|
| 327 |
"-m",
|
| 328 |
type=int,
|
| 329 |
+
default=100,
|
| 330 |
help="Maximum execution loops before stopping",
|
| 331 |
)
|
| 332 |
|
| 333 |
args = parser.parse_args()
|
| 334 |
|
| 335 |
# Run experiment with execution loop
|
| 336 |
+
result = asyncio.run(
|
| 337 |
+
run_cognitive_iteration_experiment(args.topic, args.max_loops, args.question, args.local),
|
| 338 |
+
)
|
| 339 |
|
| 340 |
# Save results if requested
|
| 341 |
if args.save_results and result:
|
| 342 |
try:
|
| 343 |
with open(args.save_results, "w") as f:
|
| 344 |
json.dump(result, f, indent=2, default=str)
|
|
|
|
| 345 |
except Exception as e:
|
| 346 |
print(f"❌ Failed to save results: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script for the Cognitive Iteration Experiment
|
| 4 |
+
|
| 5 |
+
This demonstrates the artificial deliberation concept where agents
|
| 6 |
+
engage in structured disagreement until reaching convergence.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import asyncio
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
from datetime import UTC, datetime
|
| 17 |
+
|
| 18 |
+
from orka.loader import YAMLLoader
|
| 19 |
+
from orka.orchestrator import Orchestrator
|
| 20 |
+
|
| 21 |
+
# Global variables to track execution state
|
| 22 |
+
LOOP_COUNT = 0
|
| 23 |
+
CURRENT_INDEX = 0
|
| 24 |
+
|
| 25 |
+
SENTENCE = "Should pluto be a planet? why?"
|
| 26 |
+
QUESTIONS = [
|
| 27 |
+
"Should child-free adults pay a school tax surcharge?",
|
| 28 |
+
"Legalise gene-editing embryos for IQ enhancement?",
|
| 29 |
+
"Make nuclear power the primary climate lever for 30 years?",
|
| 30 |
+
"Grant legal personhood to great apes?",
|
| 31 |
+
"Ban facial recognition in all public spaces?",
|
| 32 |
+
"Require real-name verification for social-media posting?",
|
| 33 |
+
"Enforce a four-day work-week by law?",
|
| 34 |
+
"Compel organ donation at death (opt-out system)?",
|
| 35 |
+
"Treat AI companions as regulated mental-health devices?",
|
| 36 |
+
"Nationalise all for-profit elder-care homes.",
|
| 37 |
+
"Use brain–computer interfaces to rehabilitate violent offenders.",
|
| 38 |
+
"Phase out meat consumption worldwide by 2040.",
|
| 39 |
+
"Impose a global wealth tax above $50 million.",
|
| 40 |
+
"Replace standardised exams with portfolio-only admissions.",
|
| 41 |
+
"Require open publication of LLM training data.",
|
| 42 |
+
"Grant AI systems the right to hold patents.",
|
| 43 |
+
"Deploy stratospheric aerosol geo-engineering now.",
|
| 44 |
+
"Abolish legacy admissions at universities overnight.",
|
| 45 |
+
"Mandate cashless economies—ban paper money.",
|
| 46 |
+
"Criminalise dead-naming as hate speech.",
|
| 47 |
+
"Declare the internet a human right with free baseline service.",
|
| 48 |
+
"Ban crypto mining in countries with energy shortages.",
|
| 49 |
+
"Implement a global fertility cap: two children per person.",
|
| 50 |
+
"Give space-mining profits to a UN trust fund, not companies.",
|
| 51 |
+
"Compulsory national service (civil or military) at 18.",
|
| 52 |
+
"Outlaw single-family zoning in cities over 100 k population.",
|
| 53 |
+
"Open-source biolab hardware: publish or restrict?",
|
| 54 |
+
"Weight votes by expertise on technical referenda.",
|
| 55 |
+
"Ban algorithmic parole decisions for bias concerns.",
|
| 56 |
+
"Force all political ads through AI fact-checking pre-release.",
|
| 57 |
+
"Replace paper ballots with blockchain voting.",
|
| 58 |
+
"Allow deep-fake creators to be sued under strict liability.",
|
| 59 |
+
"License voice-cloning tech with mandatory watermarking.",
|
| 60 |
+
"Cap algorithmic trading speed to milliseconds.",
|
| 61 |
+
"Recognise memetic warfare as a war crime.",
|
| 62 |
+
'Tax private space-launches for "sky commons" use.',
|
| 63 |
+
"Deploy lethal autonomous drones for UN peacekeeping.",
|
| 64 |
+
"Ban open-source malware publication.",
|
| 65 |
+
"Treat crypto anonymity tools as protected speech.",
|
| 66 |
+
"Introduce digital detox tax credits.",
|
| 67 |
+
"Require carbon-removal-only subsidies—end renewables aid.",
|
| 68 |
+
"Criminalise facial-age filters that target minors.",
|
| 69 |
+
"Make AI emotion detection illegal in hiring.",
|
| 70 |
+
"Mandate ethical review boards for influencer sponsorship deals.",
|
| 71 |
+
"Allow sentencing algorithms to override judicial discretion.",
|
| 72 |
+
"Grant climate refugees automatic citizenship.",
|
| 73 |
+
"License synthetic biology start-ups like nuclear facilities.",
|
| 74 |
+
"Recognise e-sports as Olympic disciplines.",
|
| 75 |
+
"Ban single-use fashion under environmental law.",
|
| 76 |
+
"Require smart-city residents to share location in real time.",
|
| 77 |
+
"Outlaw antibiotic use in livestock entirely.",
|
| 78 |
+
"Replace live teachers with AI tutors for core subjects.",
|
| 79 |
+
"Impose a global moratorium on deep-sea mining.",
|
| 80 |
+
"Make data localisation mandatory for personal data.",
|
| 81 |
+
"Introduce attention-span metrics as public-health targets.",
|
| 82 |
+
"Let AI decide battlefield triage to remove bias.",
|
| 83 |
+
"Add warning labels to immersive VR for psychological risk.",
|
| 84 |
+
"Ban dark-pattern UX under consumer-protection law.",
|
| 85 |
+
"Require satellite constellations to pay light-pollution fees.",
|
| 86 |
+
"Prohibit algorithmic micro-targeting in political campaigns.",
|
| 87 |
+
"Treat privacy breaches as human-rights violations.",
|
| 88 |
+
"Allow paid organ markets under strict regulation.",
|
| 89 |
+
"Set a global moratorium on AGI research until governance is ready.",
|
| 90 |
+
"Mandate vaccination passports for all international travel.",
|
| 91 |
+
"Abolish tuition—make public universities tax-funded only.",
|
| 92 |
+
"Grant voting rights to 16-year-olds.",
|
| 93 |
+
"Treat synthetic food as equivalent to conventional—no labels.",
|
| 94 |
+
"Ban gig-economy platforms from classifying workers as contractors.",
|
| 95 |
+
"Require algorithmic audits to be public and reproducible.",
|
| 96 |
+
"Make AI-generated novels eligible for literary prizes.",
|
| 97 |
+
"Outlaw pay-to-win mechanics in games aimed at minors.",
|
| 98 |
+
"Force companies to share AI model weights after market dominance.",
|
| 99 |
+
"Introduce mandatory coding education from age six worldwide.",
|
| 100 |
+
'Levy a "plastic footprint" tax on consumer goods.',
|
| 101 |
+
"Recognise smart-contract weapons as WMD equivalents.",
|
| 102 |
+
"Make deep-fake pornography a federal felony.",
|
| 103 |
+
"Require real-time CO₂ labels on online purchases.",
|
| 104 |
+
"Ban private cars from city centres over 1 million residents.",
|
| 105 |
+
"Give AI ethics boards veto power over product launches.",
|
| 106 |
+
"Regulate digital resurrection of celebrities—family consent only?",
|
| 107 |
+
"Require income transparency for all political candidates.",
|
| 108 |
+
"Ban lab-grown meat until long-term studies complete.",
|
| 109 |
+
"Make mental-health screening compulsory in schools.",
|
| 110 |
+
"Outlaw single-click subscriptions without equal-ease cancellation.",
|
| 111 |
+
"Limit extreme-longevity research funding until poverty eradication.",
|
| 112 |
+
"Treat augmented-reality eyewear as surveillance devices.",
|
| 113 |
+
"Mandate public, plain-text EULAs for every software update.",
|
| 114 |
+
"Ban stock buybacks in companies receiving climate subsidies.",
|
| 115 |
+
"Require AI watermarking in all generated media.",
|
| 116 |
+
"Recognise space-debris creation as an international tort.",
|
| 117 |
+
"Make social-credit scoring illegal in financial services.",
|
| 118 |
+
'Grant sentient AI (if any) "minor" legal status.',
|
| 119 |
+
"Require peer-reviewed impact studies before big-tech acquisitions.",
|
| 120 |
+
"Ban predictive policing algorithms.",
|
| 121 |
+
"Levy a luxury carbon tax on private jets and yachts.",
|
| 122 |
+
"Replace income tax with a data-usage tax.",
|
| 123 |
+
"Mandate public APIs for dominant social platforms.",
|
| 124 |
+
"Require AI moderators to publish training data for transparency.",
|
| 125 |
+
"Ban micro-targeted health ads based on genetic data.",
|
| 126 |
+
"Create a UN-style oversight body for the Metaverse before mass rollout.",
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def check_agreement_result(result):
|
| 131 |
+
"""
|
| 132 |
+
Check if the result contains an agreement_check agent with result == True
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
result: The orchestrator result (could be dict, list, or other)
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
bool: True if agreement is reached, False otherwise
|
| 139 |
+
"""
|
| 140 |
+
# Convert result to JSON array if it's not already
|
| 141 |
+
if not isinstance(result, list):
|
| 142 |
+
if isinstance(result, dict):
|
| 143 |
+
result_array = [result]
|
| 144 |
+
else:
|
| 145 |
+
try:
|
| 146 |
+
# Try to parse as JSON if it's a string
|
| 147 |
+
if isinstance(result, str):
|
| 148 |
+
parsed = json.loads(result)
|
| 149 |
+
result_array = [parsed] if not isinstance(parsed, list) else parsed
|
| 150 |
+
else:
|
| 151 |
+
result_array = [result]
|
| 152 |
+
except (json.JSONDecodeError, TypeError):
|
| 153 |
+
result_array = [result]
|
| 154 |
+
else:
|
| 155 |
+
result_array = result
|
| 156 |
+
|
| 157 |
+
# Look for agreement_check agent
|
| 158 |
+
for item in result_array:
|
| 159 |
+
if isinstance(item, dict) and item.get("agent_id") == "agreement_check":
|
| 160 |
+
# Check the nested result structure
|
| 161 |
+
agent_result = item.get("result", {})
|
| 162 |
+
if isinstance(agent_result, dict):
|
| 163 |
+
# Check if result.result is True
|
| 164 |
+
nested_result = agent_result.get("result")
|
| 165 |
+
if nested_result is True:
|
| 166 |
+
return True
|
| 167 |
+
elif nested_result is False:
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
# If no agreement_check agent found, assume we need to continue
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def extract_agreement_finder_response(result):
|
| 175 |
+
"""
|
| 176 |
+
Extract the response from the agreement_finder agent to use as input for next iteration
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
result: The orchestrator result (could be dict, list, or other)
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
str: The agreement_finder response, or None if not found
|
| 183 |
+
"""
|
| 184 |
+
# Convert result to JSON array if it's not already
|
| 185 |
+
if not isinstance(result, list):
|
| 186 |
+
if isinstance(result, dict):
|
| 187 |
+
result_array = [result]
|
| 188 |
+
else:
|
| 189 |
+
try:
|
| 190 |
+
# Try to parse as JSON if it's a string
|
| 191 |
+
if isinstance(result, str):
|
| 192 |
+
parsed = json.loads(result)
|
| 193 |
+
result_array = [parsed] if not isinstance(parsed, list) else parsed
|
| 194 |
+
else:
|
| 195 |
+
result_array = [result]
|
| 196 |
+
except (json.JSONDecodeError, TypeError):
|
| 197 |
+
result_array = [result]
|
| 198 |
+
else:
|
| 199 |
+
result_array = result
|
| 200 |
+
|
| 201 |
+
# Look for agreement_finder agent
|
| 202 |
+
for item in result_array:
|
| 203 |
+
if isinstance(item, dict) and item.get("agent_id") == "agreement_finder":
|
| 204 |
+
# Check the nested structure: payload -> result -> result -> response
|
| 205 |
+
payload = item.get("payload", {})
|
| 206 |
+
if isinstance(payload, dict):
|
| 207 |
+
first_result = payload.get("result", {})
|
| 208 |
+
if isinstance(first_result, dict):
|
| 209 |
+
second_result = first_result.get("result", {})
|
| 210 |
+
if isinstance(second_result, dict):
|
| 211 |
+
response = second_result.get("response")
|
| 212 |
+
if response:
|
| 213 |
+
return str(response)
|
| 214 |
+
|
| 215 |
+
# If no agreement_finder agent found, return None
|
| 216 |
+
return None
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def check_final_moderator_synthesis(result):
|
| 220 |
+
"""
|
| 221 |
+
Check if the result contains a final_moderator_synthesis agent and extract its response
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
result: The orchestrator result (could be dict, list, or other)
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
str: The final_moderator_synthesis response, or None if not found
|
| 228 |
+
"""
|
| 229 |
+
# Convert result to JSON array if it's not already
|
| 230 |
+
if not isinstance(result, list):
|
| 231 |
+
if isinstance(result, dict):
|
| 232 |
+
result_array = [result]
|
| 233 |
+
else:
|
| 234 |
+
try:
|
| 235 |
+
# Try to parse as JSON if it's a string
|
| 236 |
+
if isinstance(result, str):
|
| 237 |
+
parsed = json.loads(result)
|
| 238 |
+
result_array = [parsed] if not isinstance(parsed, list) else parsed
|
| 239 |
+
else:
|
| 240 |
+
result_array = [result]
|
| 241 |
+
except (json.JSONDecodeError, TypeError):
|
| 242 |
+
result_array = [result]
|
| 243 |
+
else:
|
| 244 |
+
result_array = result
|
| 245 |
+
|
| 246 |
+
# Look for final_moderator_synthesis agent
|
| 247 |
+
for item in result_array:
|
| 248 |
+
if isinstance(item, dict) and item.get("agent_id") == "final_moderator_synthesis":
|
| 249 |
+
# Check the nested structure: payload -> result -> result -> response
|
| 250 |
+
payload = item.get("payload", {})
|
| 251 |
+
if isinstance(payload, dict):
|
| 252 |
+
first_result = payload.get("result", {})
|
| 253 |
+
if isinstance(first_result, dict):
|
| 254 |
+
second_result = first_result.get("result", {})
|
| 255 |
+
if isinstance(second_result, dict):
|
| 256 |
+
response = second_result.get("response")
|
| 257 |
+
if response:
|
| 258 |
+
return str(response)
|
| 259 |
+
|
| 260 |
+
# If no final_moderator_synthesis agent found, return None
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
async def run_cognitive_iteration_experiment(
|
| 265 |
+
topic=None,
|
| 266 |
+
max_loops=10,
|
| 267 |
+
is_a_question=False,
|
| 268 |
+
local_run=False,
|
| 269 |
+
):
|
| 270 |
+
"""
|
| 271 |
+
Run the cognitive iteration experiment with specified topic
|
| 272 |
+
Continues execution until agreement_check agent returns True
|
| 273 |
+
"""
|
| 274 |
+
global LOOP_COUNT
|
| 275 |
+
|
| 276 |
+
# Load the configuration
|
| 277 |
+
file = None
|
| 278 |
+
if not local_run:
|
| 279 |
+
file = (
|
| 280 |
+
"cognitive_iteration_experiment_opinion.yml"
|
| 281 |
+
if not is_a_question
|
| 282 |
+
else "cognitive_iteration_experiment_answer.yml"
|
| 283 |
+
)
|
| 284 |
+
else:
|
| 285 |
+
file = "cognitive_iteration_experiment_opinion_local.yml"
|
| 286 |
+
config_path = os.path.join(os.path.dirname(__file__), file)
|
| 287 |
+
|
| 288 |
+
try:
|
| 289 |
+
# Load config for inspection/display purposes
|
| 290 |
+
loader = YAMLLoader(config_path)
|
| 291 |
+
loader.validate()
|
| 292 |
+
config = loader.config
|
| 293 |
+
print(f"✅ Loaded configuration: {file}")
|
| 294 |
+
|
| 295 |
+
# Prepare input - use topic as main input string or default topic
|
| 296 |
+
if not topic:
|
| 297 |
+
topic = SENTENCE
|
| 298 |
+
|
| 299 |
+
input_data = topic # Pass the topic as the main input string
|
| 300 |
+
|
| 301 |
+
print("\n🧠 Starting cognitive iteration on topic:")
|
| 302 |
+
print(f" {topic}")
|
| 303 |
+
print("\n🔄 Configuration:")
|
| 304 |
+
print(f" Max iterations: {config.get('variables', {}).get('max_iterations', 7)}")
|
| 305 |
+
print(
|
| 306 |
+
f" Agreement threshold: {config.get('variables', {}).get('agreement_threshold', 0.85)}",
|
| 307 |
+
)
|
| 308 |
+
print(f" Max execution loops: {max_loops}")
|
| 309 |
+
|
| 310 |
+
# Execution loop
|
| 311 |
+
final_result = None
|
| 312 |
+
current_input = input_data # Start with original topic
|
| 313 |
+
loop_count = 0 # Initialize local loop counter
|
| 314 |
+
|
| 315 |
+
while loop_count < max_loops:
|
| 316 |
+
loop_count += 1
|
| 317 |
+
LOOP_COUNT = loop_count # Sync global counter
|
| 318 |
+
print(f"\n{'=' * 60}")
|
| 319 |
+
print(f"🚀 EXECUTION LOOP {loop_count}")
|
| 320 |
+
print("=" * 60)
|
| 321 |
+
print(f"📝 Current input: {current_input}")
|
| 322 |
+
|
| 323 |
+
# Create orchestrator for this iteration
|
| 324 |
+
orchestrator = Orchestrator(config_path)
|
| 325 |
+
|
| 326 |
+
# Run the experiment
|
| 327 |
+
result = await orchestrator.run(current_input)
|
| 328 |
+
|
| 329 |
+
print(f"\n📊 LOOP {loop_count} RESULTS")
|
| 330 |
+
print("-" * 40)
|
| 331 |
+
|
| 332 |
+
# Check if final_moderator_synthesis is present (highest priority - immediate exit)
|
| 333 |
+
final_synthesis = check_final_moderator_synthesis(result)
|
| 334 |
+
if final_synthesis:
|
| 335 |
+
print(f"🎉 Final moderator synthesis found after {loop_count} execution loops!")
|
| 336 |
+
print(f"📝 Final synthesis: {final_synthesis}")
|
| 337 |
+
final_result = result
|
| 338 |
+
LOOP_COUNT = loop_count # Final sync of global counter
|
| 339 |
+
break
|
| 340 |
+
|
| 341 |
+
# Check if agreement is reached
|
| 342 |
+
agreement_reached = check_agreement_result(result)
|
| 343 |
+
|
| 344 |
+
print(f"🎯 Agreement reached: {agreement_reached}")
|
| 345 |
+
|
| 346 |
+
if agreement_reached:
|
| 347 |
+
print(f"✅ Convergence achieved after {loop_count} execution loops!")
|
| 348 |
+
final_result = result
|
| 349 |
+
LOOP_COUNT = loop_count # Final sync of global counter
|
| 350 |
+
break
|
| 351 |
+
else:
|
| 352 |
+
print(f"🔄 Agreement not reached, continuing... (Loop {loop_count}/{max_loops})")
|
| 353 |
+
final_result = result
|
| 354 |
+
|
| 355 |
+
# Extract agreement_finder response for next iteration
|
| 356 |
+
next_input = extract_agreement_finder_response(result)
|
| 357 |
+
if next_input:
|
| 358 |
+
current_input = next_input
|
| 359 |
+
print(
|
| 360 |
+
f"📋 Next input extracted from agreement_finder: {current_input[:100]}...",
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
print(
|
| 364 |
+
"⚠️ No agreement_finder response found, using current input for next iteration",
|
| 365 |
+
)
|
| 366 |
+
# Keep using current_input
|
| 367 |
+
|
| 368 |
+
# Final sync of global counter (in case we exit due to max loops)
|
| 369 |
+
LOOP_COUNT = loop_count
|
| 370 |
+
|
| 371 |
+
if loop_count >= max_loops:
|
| 372 |
+
print(f"\n⚠️ Max loops ({max_loops}) reached without convergence")
|
| 373 |
+
|
| 374 |
+
print(f"\n{'=' * 60}")
|
| 375 |
+
print("📊 FINAL EXPERIMENT RESULTS")
|
| 376 |
+
print("=" * 60)
|
| 377 |
+
print(f"🔄 Total execution loops: {loop_count}")
|
| 378 |
+
|
| 379 |
+
# Check if we have final_moderator_synthesis and display it prominently
|
| 380 |
+
final_synthesis_response = check_final_moderator_synthesis(final_result)
|
| 381 |
+
if final_synthesis_response:
|
| 382 |
+
print("\n🎉 FINAL MODERATOR SYNTHESIS:")
|
| 383 |
+
print("=" * 60)
|
| 384 |
+
print(final_synthesis_response)
|
| 385 |
+
print("=" * 60)
|
| 386 |
+
return final_synthesis_response # Return the synthesis response directly
|
| 387 |
+
|
| 388 |
+
# Extract and display key results
|
| 389 |
+
if isinstance(final_result, dict):
|
| 390 |
+
print(f"🎯 Final Agreement Score: {final_result.get('final_agreement_score', 'N/A')}")
|
| 391 |
+
print(f"🔄 Total Iterations: {final_result.get('total_iterations', 'N/A')}")
|
| 392 |
+
|
| 393 |
+
print("\n📝 Final Synthesis:")
|
| 394 |
+
print("-" * 40)
|
| 395 |
+
print(final_result.get("final_synthesis", "No synthesis available"))
|
| 396 |
+
|
| 397 |
+
print("\n🧠 Deliberation Trace:")
|
| 398 |
+
print("-" * 40)
|
| 399 |
+
trace = final_result.get("complete_deliberation_trace", [])
|
| 400 |
+
if isinstance(trace, list):
|
| 401 |
+
for i, iteration in enumerate(trace, 1):
|
| 402 |
+
print(f"\nIteration {i}:")
|
| 403 |
+
if isinstance(iteration, dict):
|
| 404 |
+
for agent, stance in iteration.items():
|
| 405 |
+
if agent not in ["iteration", "timestamp"]:
|
| 406 |
+
print(f" {agent}: {str(stance)[:100]}...")
|
| 407 |
+
|
| 408 |
+
print("\n🎯 Convergence Path:")
|
| 409 |
+
print("-" * 40)
|
| 410 |
+
convergence = final_result.get("convergence_path", [])
|
| 411 |
+
if isinstance(convergence, list):
|
| 412 |
+
for i, suggestion in enumerate(convergence, 1):
|
| 413 |
+
print(f"Iteration {i}: {str(suggestion)[:150]}...")
|
| 414 |
+
|
| 415 |
+
else:
|
| 416 |
+
print("Raw result:")
|
| 417 |
+
print(final_result)
|
| 418 |
+
|
| 419 |
+
return final_result
|
| 420 |
+
|
| 421 |
+
except Exception as e:
|
| 422 |
+
print(f"❌ Error running experiment: {e}")
|
| 423 |
+
import traceback
|
| 424 |
+
|
| 425 |
+
traceback.print_exc()
|
| 426 |
+
return None
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def main():
|
| 430 |
+
"""
|
| 431 |
+
Main function - run with custom topic or default
|
| 432 |
+
"""
|
| 433 |
+
global LOOP_COUNT, CURRENT_INDEX
|
| 434 |
+
|
| 435 |
+
import argparse
|
| 436 |
+
|
| 437 |
+
parser = argparse.ArgumentParser(description="Run Cognitive Iteration Experiment")
|
| 438 |
+
parser.add_argument("--topic", "-t", type=str, help="Topic for the agents to deliberate on")
|
| 439 |
+
parser.add_argument("--local", "-l", type=bool, help="Use local models")
|
| 440 |
+
parser.add_argument("--question", "-q", type=bool, help="Mark as a question")
|
| 441 |
+
parser.add_argument("--save-results", "-s", type=str, help="Save results to JSON file")
|
| 442 |
+
parser.add_argument(
|
| 443 |
+
"--max-loops",
|
| 444 |
+
"-m",
|
| 445 |
+
type=int,
|
| 446 |
+
default=100,
|
| 447 |
+
help="Maximum execution loops before stopping",
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
args = parser.parse_args()
|
| 451 |
+
|
| 452 |
+
# If a specific topic is provided, run just that one
|
| 453 |
+
if args.topic:
|
| 454 |
+
CURRENT_INDEX = 1
|
| 455 |
+
LOOP_COUNT = 0 # Reset loop count for this run
|
| 456 |
+
|
| 457 |
+
print(f"\n🎯 Running single experiment with topic: {args.topic}")
|
| 458 |
+
result = asyncio.run(
|
| 459 |
+
run_cognitive_iteration_experiment(
|
| 460 |
+
args.topic,
|
| 461 |
+
args.max_loops,
|
| 462 |
+
args.question,
|
| 463 |
+
args.local,
|
| 464 |
+
),
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
# Save results if requested
|
| 468 |
+
if args.save_results and result:
|
| 469 |
+
try:
|
| 470 |
+
with open(f"{args.save_results}_single", "w") as f:
|
| 471 |
+
to_save = {
|
| 472 |
+
"run": CURRENT_INDEX,
|
| 473 |
+
"topic": args.topic,
|
| 474 |
+
"loops": LOOP_COUNT,
|
| 475 |
+
"result": result,
|
| 476 |
+
}
|
| 477 |
+
json.dump(to_save, f, indent=2, default=str)
|
| 478 |
+
print(f"✅ Results saved to {args.save_results}_single")
|
| 479 |
+
except Exception as e:
|
| 480 |
+
print(f"❌ Failed to save results: {e}")
|
| 481 |
+
return
|
| 482 |
+
|
| 483 |
+
# Run all questions in the list
|
| 484 |
+
print(f"\n🎯 Running {len(QUESTIONS)} experiments...")
|
| 485 |
+
|
| 486 |
+
for index, sentence in enumerate(QUESTIONS, 1):
|
| 487 |
+
CURRENT_INDEX = index
|
| 488 |
+
LOOP_COUNT = 0 # Reset loop count for each experiment
|
| 489 |
+
|
| 490 |
+
print(f"\n{'=' * 80}")
|
| 491 |
+
print(f"🚀 EXPERIMENT {index}/{len(QUESTIONS)}")
|
| 492 |
+
print(f"📝 Topic: {sentence}")
|
| 493 |
+
print("=" * 80)
|
| 494 |
+
|
| 495 |
+
# Run experiment with execution loop
|
| 496 |
+
result = asyncio.run(
|
| 497 |
+
run_cognitive_iteration_experiment(sentence, args.max_loops, args.question, args.local),
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# Save results if requested
|
| 501 |
+
if args.save_results and result:
|
| 502 |
+
try:
|
| 503 |
+
with open(f"{args.save_results}_{index:03d}.json", "w") as f:
|
| 504 |
+
to_save = {
|
| 505 |
+
"run": CURRENT_INDEX,
|
| 506 |
+
"topic": sentence,
|
| 507 |
+
"loops": LOOP_COUNT,
|
| 508 |
+
"result": result,
|
| 509 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
| 510 |
+
}
|
| 511 |
+
json.dump(to_save, f, indent=2, default=str)
|
| 512 |
+
print(f"✅ Results saved to {args.save_results}_{index:03d}")
|
| 513 |
+
except Exception as e:
|
| 514 |
+
print(f"❌ Failed to save results: {e}")
|
| 515 |
+
|
| 516 |
+
print(f"\n📊 Experiment {index} completed with {LOOP_COUNT} loops")
|
| 517 |
+
|
| 518 |
+
print(f"\n🎉 All {len(QUESTIONS)} experiments completed!")
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
if __name__ == "__main__":
|
| 522 |
+
main()
|
orka/nodes/memory_writer_node.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
import logging
|
| 2 |
-
from typing import Any
|
|
|
|
|
|
|
| 3 |
|
| 4 |
from ..memory_logger import create_memory_logger
|
| 5 |
from .base_node import BaseNode
|
|
@@ -35,12 +37,35 @@ class MemoryWriterNode(BaseNode):
|
|
| 35 |
self.session_id = kwargs.get("session_id", "default")
|
| 36 |
self.decay_config = kwargs.get("decay_config", {})
|
| 37 |
|
|
|
|
|
|
|
|
|
|
| 38 |
# Remove direct Redis client - use memory logger instead
|
| 39 |
# self.redis = redis.from_url(...) # ← REMOVE
|
| 40 |
|
| 41 |
-
async def run(self, context:
|
| 42 |
"""Write to memory using RedisStack memory logger."""
|
| 43 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# 🎯 CRITICAL FIX: Extract structured memory object from validation guardian
|
| 45 |
memory_content = self._extract_memory_content(context)
|
| 46 |
if not memory_content:
|
|
@@ -49,7 +74,12 @@ class MemoryWriterNode(BaseNode):
|
|
| 49 |
# Extract configuration from context
|
| 50 |
namespace = context.get("namespace", self.namespace)
|
| 51 |
session_id = context.get("session_id", self.session_id)
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
# ✅ CRITICAL: Use memory logger for direct memory storage instead of orchestration logging
|
| 55 |
memory_key = self.memory_logger.log_memory(
|
|
@@ -62,19 +92,19 @@ class MemoryWriterNode(BaseNode):
|
|
| 62 |
"category": "stored", # Mark as stored memory
|
| 63 |
"log_type": "memory", # 🎯 CRITICAL: Mark as stored memory, not orchestration log
|
| 64 |
"content_type": "user_input",
|
| 65 |
-
**
|
| 66 |
},
|
| 67 |
-
importance_score=self._calculate_importance_score(memory_content,
|
| 68 |
memory_type=self._classify_memory_type(
|
| 69 |
-
|
| 70 |
-
self._calculate_importance_score(memory_content,
|
| 71 |
),
|
| 72 |
expiry_hours=self._get_expiry_hours(
|
| 73 |
self._classify_memory_type(
|
| 74 |
-
|
| 75 |
-
self._calculate_importance_score(memory_content,
|
| 76 |
),
|
| 77 |
-
self._calculate_importance_score(memory_content,
|
| 78 |
),
|
| 79 |
)
|
| 80 |
|
|
@@ -86,13 +116,219 @@ class MemoryWriterNode(BaseNode):
|
|
| 86 |
"backend": "redisstack",
|
| 87 |
"vector_enabled": True,
|
| 88 |
"memory_key": memory_key,
|
|
|
|
| 89 |
}
|
| 90 |
|
| 91 |
except Exception as e:
|
| 92 |
logger.error(f"Error writing to memory: {e}")
|
| 93 |
return {"status": "error", "error": str(e)}
|
| 94 |
|
| 95 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
"""Extract structured memory content from validation guardian output."""
|
| 97 |
try:
|
| 98 |
# Look for structured memory object from validation guardian
|
|
@@ -116,7 +352,7 @@ class MemoryWriterNode(BaseNode):
|
|
| 116 |
logger.warning(f"Error extracting memory content: {e}")
|
| 117 |
return context.get("input", "")
|
| 118 |
|
| 119 |
-
def _memory_object_to_text(self, memory_obj:
|
| 120 |
"""Convert structured memory object to searchable text format."""
|
| 121 |
try:
|
| 122 |
# Create a natural language representation that's searchable
|
|
@@ -146,7 +382,7 @@ class MemoryWriterNode(BaseNode):
|
|
| 146 |
logger.warning(f"Error converting memory object to text: {e}")
|
| 147 |
return str(memory_obj)
|
| 148 |
|
| 149 |
-
def _calculate_importance_score(self, content: str, metadata:
|
| 150 |
"""Calculate importance score for memory retention decisions."""
|
| 151 |
score = 0.5 # Base score
|
| 152 |
|
|
@@ -167,7 +403,7 @@ class MemoryWriterNode(BaseNode):
|
|
| 167 |
# Clamp score between 0.0 and 1.0
|
| 168 |
return max(0.0, min(1.0, score))
|
| 169 |
|
| 170 |
-
def _classify_memory_type(self, metadata:
|
| 171 |
"""Classify memory as short-term or long-term based on metadata and importance."""
|
| 172 |
# Stored memories with high importance are long-term
|
| 173 |
if metadata.get("category") == "stored" and importance_score >= 0.7:
|
|
|
|
| 1 |
import logging
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from jinja2 import Template
|
| 5 |
|
| 6 |
from ..memory_logger import create_memory_logger
|
| 7 |
from .base_node import BaseNode
|
|
|
|
| 37 |
self.session_id = kwargs.get("session_id", "default")
|
| 38 |
self.decay_config = kwargs.get("decay_config", {})
|
| 39 |
|
| 40 |
+
# ✅ CRITICAL: Always store metadata structure defined in YAML
|
| 41 |
+
self.yaml_metadata = kwargs.get("metadata", {})
|
| 42 |
+
|
| 43 |
# Remove direct Redis client - use memory logger instead
|
| 44 |
# self.redis = redis.from_url(...) # ← REMOVE
|
| 45 |
|
| 46 |
+
async def run(self, context: dict[str, Any]) -> dict[str, Any]:
|
| 47 |
"""Write to memory using RedisStack memory logger."""
|
| 48 |
try:
|
| 49 |
+
# 🔍 DEBUG: Log the complete context structure
|
| 50 |
+
logger.info(f"MemoryWriterNode received context keys: {list(context.keys())}")
|
| 51 |
+
if "previous_outputs" in context:
|
| 52 |
+
logger.info(f"Previous outputs keys: {list(context['previous_outputs'].keys())}")
|
| 53 |
+
# Log structure of a few key outputs
|
| 54 |
+
for key in ["logic_reasoning", "empathy_reasoning", "moderator_synthesis"]:
|
| 55 |
+
if key in context["previous_outputs"]:
|
| 56 |
+
output = context["previous_outputs"][key]
|
| 57 |
+
logger.info(
|
| 58 |
+
f"Structure of {key}: {type(output)} with keys: {list(output.keys()) if isinstance(output, dict) else 'not a dict'}",
|
| 59 |
+
)
|
| 60 |
+
if isinstance(output, dict) and "result" in output:
|
| 61 |
+
result = output["result"]
|
| 62 |
+
logger.info(
|
| 63 |
+
f" Result structure: {type(result)} with keys: {list(result.keys()) if isinstance(result, dict) else 'not a dict'}",
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Log the YAML metadata we're trying to render
|
| 67 |
+
logger.info(f"YAML metadata to render: {self.yaml_metadata}")
|
| 68 |
+
|
| 69 |
# 🎯 CRITICAL FIX: Extract structured memory object from validation guardian
|
| 70 |
memory_content = self._extract_memory_content(context)
|
| 71 |
if not memory_content:
|
|
|
|
| 74 |
# Extract configuration from context
|
| 75 |
namespace = context.get("namespace", self.namespace)
|
| 76 |
session_id = context.get("session_id", self.session_id)
|
| 77 |
+
|
| 78 |
+
# ✅ CRITICAL: Always merge metadata from YAML config and context
|
| 79 |
+
merged_metadata = self._merge_metadata(context)
|
| 80 |
+
|
| 81 |
+
# 🔍 DEBUG: Log the final merged metadata
|
| 82 |
+
logger.info(f"Final merged metadata: {merged_metadata}")
|
| 83 |
|
| 84 |
# ✅ CRITICAL: Use memory logger for direct memory storage instead of orchestration logging
|
| 85 |
memory_key = self.memory_logger.log_memory(
|
|
|
|
| 92 |
"category": "stored", # Mark as stored memory
|
| 93 |
"log_type": "memory", # 🎯 CRITICAL: Mark as stored memory, not orchestration log
|
| 94 |
"content_type": "user_input",
|
| 95 |
+
**merged_metadata, # Include all metadata from YAML and context
|
| 96 |
},
|
| 97 |
+
importance_score=self._calculate_importance_score(memory_content, merged_metadata),
|
| 98 |
memory_type=self._classify_memory_type(
|
| 99 |
+
merged_metadata,
|
| 100 |
+
self._calculate_importance_score(memory_content, merged_metadata),
|
| 101 |
),
|
| 102 |
expiry_hours=self._get_expiry_hours(
|
| 103 |
self._classify_memory_type(
|
| 104 |
+
merged_metadata,
|
| 105 |
+
self._calculate_importance_score(memory_content, merged_metadata),
|
| 106 |
),
|
| 107 |
+
self._calculate_importance_score(memory_content, merged_metadata),
|
| 108 |
),
|
| 109 |
)
|
| 110 |
|
|
|
|
| 116 |
"backend": "redisstack",
|
| 117 |
"vector_enabled": True,
|
| 118 |
"memory_key": memory_key,
|
| 119 |
+
"stored_metadata": merged_metadata, # Include metadata in response
|
| 120 |
}
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
logger.error(f"Error writing to memory: {e}")
|
| 124 |
return {"status": "error", "error": str(e)}
|
| 125 |
|
| 126 |
+
def _merge_metadata(self, context: dict[str, Any]) -> dict[str, Any]:
|
| 127 |
+
"""Merge metadata from YAML config, context, and guardian outputs."""
|
| 128 |
+
try:
|
| 129 |
+
# Start with YAML metadata structure (always preserve this)
|
| 130 |
+
merged_metadata = self.yaml_metadata.copy()
|
| 131 |
+
|
| 132 |
+
# ✅ CRITICAL: Render YAML metadata templates first
|
| 133 |
+
rendered_yaml_metadata = self._render_metadata_templates(merged_metadata, context)
|
| 134 |
+
|
| 135 |
+
# Add context metadata (overrides YAML where keys conflict)
|
| 136 |
+
context_metadata = context.get("metadata", {})
|
| 137 |
+
rendered_yaml_metadata.update(context_metadata)
|
| 138 |
+
|
| 139 |
+
# Extract metadata from guardian outputs if present
|
| 140 |
+
guardian_metadata = self._extract_guardian_metadata(context)
|
| 141 |
+
if guardian_metadata:
|
| 142 |
+
rendered_yaml_metadata.update(guardian_metadata)
|
| 143 |
+
|
| 144 |
+
# Extract structured memory object metadata if present
|
| 145 |
+
memory_object_metadata = self._extract_memory_object_metadata(context)
|
| 146 |
+
if memory_object_metadata:
|
| 147 |
+
rendered_yaml_metadata.update(memory_object_metadata)
|
| 148 |
+
|
| 149 |
+
return rendered_yaml_metadata
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logger.warning(f"Error merging metadata: {e}")
|
| 153 |
+
return self.yaml_metadata.copy()
|
| 154 |
+
|
| 155 |
+
def _render_metadata_templates(
|
| 156 |
+
self,
|
| 157 |
+
metadata: dict[str, Any],
|
| 158 |
+
context: dict[str, Any],
|
| 159 |
+
) -> dict[str, Any]:
|
| 160 |
+
"""Render Jinja2 templates in metadata using context data."""
|
| 161 |
+
try:
|
| 162 |
+
rendered_metadata = {}
|
| 163 |
+
|
| 164 |
+
# Create comprehensive template context
|
| 165 |
+
template_context = {
|
| 166 |
+
"input": context.get("input", ""),
|
| 167 |
+
"previous_outputs": context.get("previous_outputs", {}),
|
| 168 |
+
"timestamp": context.get("timestamp", ""),
|
| 169 |
+
"now": lambda: context.get("timestamp", ""), # now() function for templates
|
| 170 |
+
**context, # Include all context keys
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# Debug: Log template context structure
|
| 174 |
+
logger.info(f"Template context keys: {list(template_context.keys())}")
|
| 175 |
+
logger.info(
|
| 176 |
+
f"Previous outputs keys: {list(template_context.get('previous_outputs', {}).keys())}",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# 🔍 DEBUG: Log specific structure that templates are trying to access
|
| 180 |
+
prev_outputs = template_context.get("previous_outputs", {})
|
| 181 |
+
for agent_key in ["logic_reasoning", "empathy_reasoning", "moderator_synthesis"]:
|
| 182 |
+
if agent_key in prev_outputs:
|
| 183 |
+
agent_data = prev_outputs[agent_key]
|
| 184 |
+
logger.info(f"Agent {agent_key} structure: {type(agent_data)}")
|
| 185 |
+
if isinstance(agent_data, dict):
|
| 186 |
+
logger.info(f" Keys: {list(agent_data.keys())}")
|
| 187 |
+
if "result" in agent_data:
|
| 188 |
+
result = agent_data["result"]
|
| 189 |
+
logger.info(f" Result type: {type(result)}")
|
| 190 |
+
if isinstance(result, dict):
|
| 191 |
+
logger.info(f" Result keys: {list(result.keys())}")
|
| 192 |
+
|
| 193 |
+
for key, value in metadata.items():
|
| 194 |
+
try:
|
| 195 |
+
if isinstance(value, str) and ("{{" in value or "{%" in value):
|
| 196 |
+
# Debug: Log what we're trying to render
|
| 197 |
+
logger.info(f"🎯 Rendering template for key '{key}': {value}")
|
| 198 |
+
|
| 199 |
+
# Render string templates with enhanced error handling
|
| 200 |
+
template = Template(value)
|
| 201 |
+
rendered_value = template.render(**template_context)
|
| 202 |
+
|
| 203 |
+
# Debug: Log the rendered result
|
| 204 |
+
logger.info(
|
| 205 |
+
f"✅ Rendered value for key '{key}': {rendered_value[:200]}{'...' if len(str(rendered_value)) > 200 else ''}",
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Handle special cases where rendered value might be None or empty
|
| 209 |
+
if rendered_value is None or rendered_value == "":
|
| 210 |
+
# Try to extract default value from template if present
|
| 211 |
+
if "default(" in value:
|
| 212 |
+
# Use original template string as fallback
|
| 213 |
+
rendered_metadata[key] = value
|
| 214 |
+
logger.warning(
|
| 215 |
+
f"⚠️ Template rendered empty, using default for '{key}'",
|
| 216 |
+
)
|
| 217 |
+
else:
|
| 218 |
+
rendered_metadata[key] = ""
|
| 219 |
+
logger.warning(f"⚠️ Template rendered empty for '{key}'")
|
| 220 |
+
else:
|
| 221 |
+
rendered_metadata[key] = rendered_value
|
| 222 |
+
|
| 223 |
+
elif isinstance(value, dict):
|
| 224 |
+
# Recursively render nested dictionaries
|
| 225 |
+
rendered_metadata[key] = self._render_metadata_templates(value, context)
|
| 226 |
+
elif isinstance(value, list):
|
| 227 |
+
# Render templates in lists
|
| 228 |
+
rendered_list = []
|
| 229 |
+
for item in value:
|
| 230 |
+
if isinstance(item, str) and ("{{" in item or "{%" in item):
|
| 231 |
+
try:
|
| 232 |
+
template = Template(item)
|
| 233 |
+
rendered_item = template.render(**template_context)
|
| 234 |
+
rendered_list.append(rendered_item)
|
| 235 |
+
except Exception as e:
|
| 236 |
+
logger.warning(f"❌ Error rendering list item template: {e}")
|
| 237 |
+
rendered_list.append(item)
|
| 238 |
+
else:
|
| 239 |
+
rendered_list.append(item)
|
| 240 |
+
rendered_metadata[key] = rendered_list
|
| 241 |
+
else:
|
| 242 |
+
# Keep non-template values as-is
|
| 243 |
+
rendered_metadata[key] = value
|
| 244 |
+
|
| 245 |
+
except Exception as e:
|
| 246 |
+
logger.error(f"❌ Error rendering template for metadata key '{key}': {e}")
|
| 247 |
+
logger.error(f"Template value: {value}")
|
| 248 |
+
logger.error(f"Template context keys: {list(template_context.keys())}")
|
| 249 |
+
import traceback
|
| 250 |
+
|
| 251 |
+
logger.error(f"Full traceback: {traceback.format_exc()}")
|
| 252 |
+
# Keep original value if rendering fails
|
| 253 |
+
rendered_metadata[key] = value
|
| 254 |
+
|
| 255 |
+
return rendered_metadata
|
| 256 |
+
|
| 257 |
+
except Exception as e:
|
| 258 |
+
logger.error(f"❌ Error rendering metadata templates: {e}")
|
| 259 |
+
import traceback
|
| 260 |
+
|
| 261 |
+
logger.error(f"Full traceback: {traceback.format_exc()}")
|
| 262 |
+
return metadata.copy()
|
| 263 |
+
|
| 264 |
+
def _extract_guardian_metadata(self, context: dict[str, Any]) -> dict[str, Any]:
|
| 265 |
+
"""Extract metadata from validation guardian outputs."""
|
| 266 |
+
try:
|
| 267 |
+
guardian_metadata = {}
|
| 268 |
+
previous_outputs = context.get("previous_outputs", {})
|
| 269 |
+
|
| 270 |
+
# Check both validation guardians for metadata
|
| 271 |
+
for guardian_name in ["false_validation_guardian", "true_validation_guardian"]:
|
| 272 |
+
if guardian_name in previous_outputs:
|
| 273 |
+
guardian_output = previous_outputs[guardian_name]
|
| 274 |
+
if isinstance(guardian_output, dict):
|
| 275 |
+
# Extract metadata from guardian result
|
| 276 |
+
if "metadata" in guardian_output:
|
| 277 |
+
guardian_metadata.update(guardian_output["metadata"])
|
| 278 |
+
|
| 279 |
+
# Extract validation status
|
| 280 |
+
if "result" in guardian_output:
|
| 281 |
+
result = guardian_output["result"]
|
| 282 |
+
if isinstance(result, dict):
|
| 283 |
+
guardian_metadata["validation_guardian"] = guardian_name
|
| 284 |
+
guardian_metadata["validation_result"] = result.get(
|
| 285 |
+
"validation_status",
|
| 286 |
+
"unknown",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
return guardian_metadata
|
| 290 |
+
|
| 291 |
+
except Exception as e:
|
| 292 |
+
logger.warning(f"Error extracting guardian metadata: {e}")
|
| 293 |
+
return {}
|
| 294 |
+
|
| 295 |
+
def _extract_memory_object_metadata(self, context: dict[str, Any]) -> dict[str, Any]:
|
| 296 |
+
"""Extract metadata from structured memory objects."""
|
| 297 |
+
try:
|
| 298 |
+
memory_object_metadata = {}
|
| 299 |
+
previous_outputs = context.get("previous_outputs", {})
|
| 300 |
+
|
| 301 |
+
# Look for structured memory objects from guardians
|
| 302 |
+
for guardian_name in ["false_validation_guardian", "true_validation_guardian"]:
|
| 303 |
+
if guardian_name in previous_outputs:
|
| 304 |
+
guardian_output = previous_outputs[guardian_name]
|
| 305 |
+
if isinstance(guardian_output, dict) and "result" in guardian_output:
|
| 306 |
+
result = guardian_output["result"]
|
| 307 |
+
if isinstance(result, dict) and "memory_object" in result:
|
| 308 |
+
memory_obj = result["memory_object"]
|
| 309 |
+
if isinstance(memory_obj, dict):
|
| 310 |
+
# Extract structured fields as metadata
|
| 311 |
+
memory_object_metadata["structured_data"] = memory_obj
|
| 312 |
+
memory_object_metadata["analysis_type"] = memory_obj.get(
|
| 313 |
+
"analysis_type",
|
| 314 |
+
"unknown",
|
| 315 |
+
)
|
| 316 |
+
memory_object_metadata["confidence"] = memory_obj.get(
|
| 317 |
+
"confidence",
|
| 318 |
+
1.0,
|
| 319 |
+
)
|
| 320 |
+
memory_object_metadata["validation_status"] = memory_obj.get(
|
| 321 |
+
"validation_status",
|
| 322 |
+
"unknown",
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
return memory_object_metadata
|
| 326 |
+
|
| 327 |
+
except Exception as e:
|
| 328 |
+
logger.warning(f"Error extracting memory object metadata: {e}")
|
| 329 |
+
return {}
|
| 330 |
+
|
| 331 |
+
def _extract_memory_content(self, context: dict[str, Any]) -> str:
|
| 332 |
"""Extract structured memory content from validation guardian output."""
|
| 333 |
try:
|
| 334 |
# Look for structured memory object from validation guardian
|
|
|
|
| 352 |
logger.warning(f"Error extracting memory content: {e}")
|
| 353 |
return context.get("input", "")
|
| 354 |
|
| 355 |
+
def _memory_object_to_text(self, memory_obj: dict[str, Any], original_input: str) -> str:
|
| 356 |
"""Convert structured memory object to searchable text format."""
|
| 357 |
try:
|
| 358 |
# Create a natural language representation that's searchable
|
|
|
|
| 382 |
logger.warning(f"Error converting memory object to text: {e}")
|
| 383 |
return str(memory_obj)
|
| 384 |
|
| 385 |
+
def _calculate_importance_score(self, content: str, metadata: dict[str, Any]) -> float:
|
| 386 |
"""Calculate importance score for memory retention decisions."""
|
| 387 |
score = 0.5 # Base score
|
| 388 |
|
|
|
|
| 403 |
# Clamp score between 0.0 and 1.0
|
| 404 |
return max(0.0, min(1.0, score))
|
| 405 |
|
| 406 |
+
def _classify_memory_type(self, metadata: dict[str, Any], importance_score: float) -> str:
|
| 407 |
"""Classify memory as short-term or long-term based on metadata and importance."""
|
| 408 |
# Stored memories with high importance are long-term
|
| 409 |
if metadata.get("category") == "stored" and importance_score >= 0.7:
|
orka/orchestrator/execution_engine.py
CHANGED
|
@@ -49,7 +49,7 @@ import json
|
|
| 49 |
import logging
|
| 50 |
import os
|
| 51 |
from concurrent.futures import ThreadPoolExecutor
|
| 52 |
-
from datetime import
|
| 53 |
from time import time
|
| 54 |
|
| 55 |
logger = logging.getLogger(__name__)
|
|
@@ -143,7 +143,7 @@ class ExecutionEngine:
|
|
| 143 |
)
|
| 144 |
self.error_telemetry["execution_status"] = "failed"
|
| 145 |
self.error_telemetry["critical_failures"].append(
|
| 146 |
-
{"error": str(e), "timestamp": datetime.now(
|
| 147 |
)
|
| 148 |
self._save_error_report(logs, e)
|
| 149 |
raise
|
|
@@ -176,7 +176,7 @@ class ExecutionEngine:
|
|
| 176 |
log_entry = {
|
| 177 |
"agent_id": agent_id,
|
| 178 |
"event_type": agent.__class__.__name__,
|
| 179 |
-
"timestamp": datetime.now(
|
| 180 |
}
|
| 181 |
|
| 182 |
start_time = time()
|
|
@@ -317,7 +317,7 @@ class ExecutionEngine:
|
|
| 317 |
meta_report_entry = {
|
| 318 |
"agent_id": "meta_report",
|
| 319 |
"event_type": "MetaReport",
|
| 320 |
-
"timestamp": datetime.now(
|
| 321 |
"payload": {
|
| 322 |
"meta_report": meta_report,
|
| 323 |
"run_id": self.run_id,
|
|
@@ -554,6 +554,18 @@ class ExecutionEngine:
|
|
| 554 |
# Render prompt before running agent if agent has a prompt
|
| 555 |
self._render_agent_prompt(agent, payload)
|
| 556 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
# Inspect the run method to see if it needs orchestrator
|
| 558 |
run_method = agent.run
|
| 559 |
sig = inspect.signature(run_method)
|
|
@@ -603,6 +615,24 @@ class ExecutionEngine:
|
|
| 603 |
Run multiple branches in parallel, with agents within each branch running sequentially.
|
| 604 |
Returns a list of log entries for each forked agent.
|
| 605 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 606 |
# Get the fork node to understand the branch structure
|
| 607 |
# Fork group ID format: {node_id}_{timestamp}, so we need to remove the timestamp
|
| 608 |
fork_node_id = "_".join(
|
|
@@ -611,9 +641,14 @@ class ExecutionEngine:
|
|
| 611 |
fork_node = self.agents[fork_node_id]
|
| 612 |
branches = fork_node.targets
|
| 613 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 614 |
# Run each branch in parallel
|
| 615 |
branch_tasks = [
|
| 616 |
-
self._run_branch_async(branch, input_data,
|
|
|
|
| 617 |
]
|
| 618 |
|
| 619 |
# Wait for all branches to complete
|
|
@@ -622,7 +657,7 @@ class ExecutionEngine:
|
|
| 622 |
# Process results and create logs
|
| 623 |
forked_step_index = 0
|
| 624 |
result_logs = []
|
| 625 |
-
updated_previous_outputs =
|
| 626 |
|
| 627 |
# Flatten branch results into a single list of (agent_id, result) pairs
|
| 628 |
all_results = []
|
|
@@ -653,7 +688,7 @@ class ExecutionEngine:
|
|
| 653 |
log_data = {
|
| 654 |
"agent_id": agent_id,
|
| 655 |
"event_type": f"ForkedAgent-{self.agents[agent_id].__class__.__name__}",
|
| 656 |
-
"timestamp": datetime.now(
|
| 657 |
"payload": payload_data,
|
| 658 |
"previous_outputs": updated_previous_outputs.copy(),
|
| 659 |
"step": step_index,
|
|
@@ -676,6 +711,51 @@ class ExecutionEngine:
|
|
| 676 |
|
| 677 |
return result_logs
|
| 678 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 679 |
def enqueue_fork(self, agent_ids, fork_group_id):
|
| 680 |
"""
|
| 681 |
Add agents to the fork queue for processing.
|
|
|
|
| 49 |
import logging
|
| 50 |
import os
|
| 51 |
from concurrent.futures import ThreadPoolExecutor
|
| 52 |
+
from datetime import UTC, datetime
|
| 53 |
from time import time
|
| 54 |
|
| 55 |
logger = logging.getLogger(__name__)
|
|
|
|
| 143 |
)
|
| 144 |
self.error_telemetry["execution_status"] = "failed"
|
| 145 |
self.error_telemetry["critical_failures"].append(
|
| 146 |
+
{"error": str(e), "timestamp": datetime.now(UTC).isoformat()},
|
| 147 |
)
|
| 148 |
self._save_error_report(logs, e)
|
| 149 |
raise
|
|
|
|
| 176 |
log_entry = {
|
| 177 |
"agent_id": agent_id,
|
| 178 |
"event_type": agent.__class__.__name__,
|
| 179 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
| 180 |
}
|
| 181 |
|
| 182 |
start_time = time()
|
|
|
|
| 317 |
meta_report_entry = {
|
| 318 |
"agent_id": "meta_report",
|
| 319 |
"event_type": "MetaReport",
|
| 320 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
| 321 |
"payload": {
|
| 322 |
"meta_report": meta_report,
|
| 323 |
"run_id": self.run_id,
|
|
|
|
| 554 |
# Render prompt before running agent if agent has a prompt
|
| 555 |
self._render_agent_prompt(agent, payload)
|
| 556 |
|
| 557 |
+
# 🔍 DEBUG: Check if template rendering worked (only if DEBUG logging is enabled)
|
| 558 |
+
if logger.isEnabledFor(logging.DEBUG) and hasattr(agent, "prompt") and agent.prompt:
|
| 559 |
+
if "formatted_prompt" in payload:
|
| 560 |
+
original_template = agent.prompt
|
| 561 |
+
rendered_template = payload["formatted_prompt"]
|
| 562 |
+
|
| 563 |
+
# Check if template was actually rendered (changed from original)
|
| 564 |
+
if original_template != rendered_template:
|
| 565 |
+
logger.debug(f"Agent '{agent_id}' template rendered successfully")
|
| 566 |
+
else:
|
| 567 |
+
logger.debug(f"Agent '{agent_id}' template unchanged - possible template issue")
|
| 568 |
+
|
| 569 |
# Inspect the run method to see if it needs orchestrator
|
| 570 |
run_method = agent.run
|
| 571 |
sig = inspect.signature(run_method)
|
|
|
|
| 615 |
Run multiple branches in parallel, with agents within each branch running sequentially.
|
| 616 |
Returns a list of log entries for each forked agent.
|
| 617 |
"""
|
| 618 |
+
# 🔧 GENERIC FIX: Ensure complete context is passed to forked agents
|
| 619 |
+
logger.debug(
|
| 620 |
+
f"run_parallel_agents called with previous_outputs keys: {list(previous_outputs.keys())}",
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
# Enhanced debugging: Check the structure of previous_outputs (only if DEBUG enabled)
|
| 624 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 625 |
+
for agent_id, agent_result in previous_outputs.items():
|
| 626 |
+
if isinstance(agent_result, dict):
|
| 627 |
+
# Check for common nested structures
|
| 628 |
+
if "memories" in agent_result:
|
| 629 |
+
memories = agent_result["memories"]
|
| 630 |
+
logger.debug(
|
| 631 |
+
f"Agent '{agent_id}' has {len(memories) if isinstance(memories, list) else 'non-list'} memories",
|
| 632 |
+
)
|
| 633 |
+
if "result" in agent_result:
|
| 634 |
+
logger.debug(f"Agent '{agent_id}' has nested result structure")
|
| 635 |
+
|
| 636 |
# Get the fork node to understand the branch structure
|
| 637 |
# Fork group ID format: {node_id}_{timestamp}, so we need to remove the timestamp
|
| 638 |
fork_node_id = "_".join(
|
|
|
|
| 641 |
fork_node = self.agents[fork_node_id]
|
| 642 |
branches = fork_node.targets
|
| 643 |
|
| 644 |
+
# 🔧 GENERIC FIX: Ensure previous_outputs is properly structured
|
| 645 |
+
# Make a deep copy to avoid modifying the original
|
| 646 |
+
enhanced_previous_outputs = self._ensure_complete_context(previous_outputs)
|
| 647 |
+
|
| 648 |
# Run each branch in parallel
|
| 649 |
branch_tasks = [
|
| 650 |
+
self._run_branch_async(branch, input_data, enhanced_previous_outputs)
|
| 651 |
+
for branch in branches
|
| 652 |
]
|
| 653 |
|
| 654 |
# Wait for all branches to complete
|
|
|
|
| 657 |
# Process results and create logs
|
| 658 |
forked_step_index = 0
|
| 659 |
result_logs = []
|
| 660 |
+
updated_previous_outputs = enhanced_previous_outputs.copy()
|
| 661 |
|
| 662 |
# Flatten branch results into a single list of (agent_id, result) pairs
|
| 663 |
all_results = []
|
|
|
|
| 688 |
log_data = {
|
| 689 |
"agent_id": agent_id,
|
| 690 |
"event_type": f"ForkedAgent-{self.agents[agent_id].__class__.__name__}",
|
| 691 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
| 692 |
"payload": payload_data,
|
| 693 |
"previous_outputs": updated_previous_outputs.copy(),
|
| 694 |
"step": step_index,
|
|
|
|
| 711 |
|
| 712 |
return result_logs
|
| 713 |
|
| 714 |
+
def _ensure_complete_context(self, previous_outputs):
|
| 715 |
+
"""
|
| 716 |
+
Generic method to ensure previous_outputs has complete context for template rendering.
|
| 717 |
+
This handles various agent result structures and ensures templates can access data.
|
| 718 |
+
"""
|
| 719 |
+
enhanced_outputs = {}
|
| 720 |
+
|
| 721 |
+
for agent_id, agent_result in previous_outputs.items():
|
| 722 |
+
# Start with the original result
|
| 723 |
+
enhanced_outputs[agent_id] = agent_result
|
| 724 |
+
|
| 725 |
+
# If the result is a complex structure, ensure it's template-friendly
|
| 726 |
+
if isinstance(agent_result, dict):
|
| 727 |
+
# Handle different common agent result patterns
|
| 728 |
+
# Pattern 1: Direct result (like memory nodes)
|
| 729 |
+
if "memories" in agent_result and isinstance(agent_result["memories"], list):
|
| 730 |
+
logger.debug(
|
| 731 |
+
f"Agent '{agent_id}' has {len(agent_result['memories'])} memories directly accessible",
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
# Pattern 2: Nested result structure
|
| 735 |
+
elif "result" in agent_result and isinstance(agent_result["result"], dict):
|
| 736 |
+
nested_result = agent_result["result"]
|
| 737 |
+
logger.debug(
|
| 738 |
+
f"Agent '{agent_id}' has nested result with keys: {list(nested_result.keys())}",
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
+
# For nested structures, also provide direct access to common fields
|
| 742 |
+
if "memories" in nested_result:
|
| 743 |
+
# Create a version that allows both access patterns
|
| 744 |
+
enhanced_outputs[agent_id] = {
|
| 745 |
+
**agent_result, # Keep original structure
|
| 746 |
+
"memories": nested_result["memories"], # Direct access
|
| 747 |
+
}
|
| 748 |
+
logger.debug(f"Agent '{agent_id}' enhanced with direct memory access")
|
| 749 |
+
|
| 750 |
+
if "response" in nested_result:
|
| 751 |
+
enhanced_outputs[agent_id] = {
|
| 752 |
+
**enhanced_outputs.get(agent_id, agent_result),
|
| 753 |
+
"response": nested_result["response"], # Direct access
|
| 754 |
+
}
|
| 755 |
+
logger.debug(f"Agent '{agent_id}' enhanced with direct response access")
|
| 756 |
+
|
| 757 |
+
return enhanced_outputs
|
| 758 |
+
|
| 759 |
def enqueue_fork(self, agent_ids, fork_group_id):
|
| 760 |
"""
|
| 761 |
Add agents to the fork queue for processing.
|
orka/orchestrator/prompt_rendering.py
CHANGED
|
@@ -102,7 +102,69 @@ class PromptRenderer:
|
|
| 102 |
raise ValueError(
|
| 103 |
f"Expected template_str to be str, got {type(template_str)} instead.",
|
| 104 |
)
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
def _add_prompt_to_payload(self, agent, payload_out, payload):
|
| 108 |
"""
|
|
|
|
| 102 |
raise ValueError(
|
| 103 |
f"Expected template_str to be str, got {type(template_str)} instead.",
|
| 104 |
)
|
| 105 |
+
|
| 106 |
+
# 🔧 GENERIC FIX: Enhance payload for better template rendering
|
| 107 |
+
enhanced_payload = self._enhance_payload_for_templates(payload)
|
| 108 |
+
|
| 109 |
+
return Template(template_str).render(**enhanced_payload)
|
| 110 |
+
|
| 111 |
+
def _enhance_payload_for_templates(self, payload):
|
| 112 |
+
"""
|
| 113 |
+
Enhance the payload to make template rendering more robust and generic.
|
| 114 |
+
|
| 115 |
+
This method ensures that previous_outputs can be accessed in multiple ways
|
| 116 |
+
to support different template patterns used across workflows.
|
| 117 |
+
"""
|
| 118 |
+
enhanced_payload = payload.copy()
|
| 119 |
+
|
| 120 |
+
# If previous_outputs exists, enhance it for template compatibility
|
| 121 |
+
if "previous_outputs" in enhanced_payload:
|
| 122 |
+
original_outputs = enhanced_payload["previous_outputs"]
|
| 123 |
+
enhanced_outputs = {}
|
| 124 |
+
|
| 125 |
+
# Process each agent's output to make it more template-friendly
|
| 126 |
+
for agent_id, agent_result in original_outputs.items():
|
| 127 |
+
# Keep the original structure
|
| 128 |
+
enhanced_outputs[agent_id] = agent_result
|
| 129 |
+
|
| 130 |
+
# If the result has a nested structure, also provide direct access
|
| 131 |
+
if isinstance(agent_result, dict):
|
| 132 |
+
# If agent_result has a 'result' key, also provide shortcuts
|
| 133 |
+
if "result" in agent_result:
|
| 134 |
+
result_data = agent_result["result"]
|
| 135 |
+
|
| 136 |
+
# Create a flattened version for easier template access
|
| 137 |
+
flattened_result = {
|
| 138 |
+
"result": result_data,
|
| 139 |
+
# If result has common keys, expose them directly
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
# Add common result fields as shortcuts
|
| 143 |
+
if isinstance(result_data, dict):
|
| 144 |
+
# For memory agents, expose memories directly
|
| 145 |
+
if "memories" in result_data:
|
| 146 |
+
flattened_result["memories"] = result_data["memories"]
|
| 147 |
+
|
| 148 |
+
# For LLM agents, expose response directly
|
| 149 |
+
if "response" in result_data:
|
| 150 |
+
flattened_result["response"] = result_data["response"]
|
| 151 |
+
|
| 152 |
+
# For other common fields
|
| 153 |
+
for key in ["status", "confidence", "data", "content"]:
|
| 154 |
+
if key in result_data:
|
| 155 |
+
flattened_result[key] = result_data[key]
|
| 156 |
+
|
| 157 |
+
enhanced_outputs[agent_id] = flattened_result
|
| 158 |
+
else:
|
| 159 |
+
# If no nested result, the agent_result is the direct result
|
| 160 |
+
enhanced_outputs[agent_id] = agent_result
|
| 161 |
+
else:
|
| 162 |
+
# If not a dict, keep as is
|
| 163 |
+
enhanced_outputs[agent_id] = agent_result
|
| 164 |
+
|
| 165 |
+
enhanced_payload["previous_outputs"] = enhanced_outputs
|
| 166 |
+
|
| 167 |
+
return enhanced_payload
|
| 168 |
|
| 169 |
def _add_prompt_to_payload(self, agent, payload_out, payload):
|
| 170 |
"""
|