thefinalboss commited on
Commit
fa16dcb
·
verified ·
1 Parent(s): 3473be3

Add AICL example: 55_autonomous_agent.aicl

Browse files
data/aicl/examples/55_autonomous_agent.aicl ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AICL Example: Autonomous AI Agent System
2
+ # Production autonomous AI agent system implementing planning, tool use, memory management,
3
+ # reasoning chains, self-reflection, and multi-agent coordination for complex task execution.
4
+
5
+ Goal Build an autonomous AI agent system that can plan and execute complex multi-step tasks, use external tools, maintain persistent memory, perform chain-of-thought reasoning, self-reflect on its actions, and coordinate with other agents to accomplish goals that exceed any single agent's capability
6
+
7
+ Constraint Agent must never execute destructive actions without explicit human confirmation
8
+ Constraint Reasoning chains must be fully auditable and explainable at every step
9
+ Constraint Agent memory must respect data retention policies and support selective forgetting
10
+ Constraint Multi-agent coordination must prevent deadlock and ensure progress toward shared goals
11
+ Constraint Agent must detect and report its own uncertainty and capability limits
12
+
13
+ Risk Agent hallucination leading to incorrect tool calls with real-world consequences
14
+ Recovery Implement output validation before tool execution; require confidence thresholds for action approval; maintain rollback capability for reversible actions; log full reasoning chain for audit
15
+
16
+ Risk Infinite reasoning loops consuming excessive compute resources
17
+ Recovery Enforce maximum reasoning depth and iteration count; implement progress detection with forced termination on stagnation; require step yield for long-running chains; monitor resource consumption
18
+
19
+ Risk Tool execution failure cascading through multi-step plan
20
+ Recovery Implement graceful degradation with alternative tool selection; maintain plan checkpointing for resumption; use transactional execution for reversible step groups; alert human supervisor on repeated failures
21
+
22
+ Risk Memory pollution from incorrect or adversarial information
23
+ Recovery Validate all memory entries before persistence; implement memory confidence scoring; enable selective memory quarantine; deploy periodic memory consistency auditing
24
+
25
+ Risk Multi-agent coordination deadlock or conflicting actions
26
+ Recovery Implement deadlock detection with timeout-based resolution; deploy centralized coordination for shared resources; use priority-based action arbitration; enforce communication heartbeat protocol
27
+
28
+ Risk Agent exceeding authority boundaries during autonomous operation
29
+ Recovery Define explicit capability boundaries with enforcement; implement permission escalation flow; audit all actions against authorization policy; require confirmation for high-impact operations
30
+
31
+ Layer AgentCore
32
+ SubLayer: Planner
33
+ SubLayer: Reasoner
34
+ SubLayer: Executor
35
+ Layer ToolUse
36
+ SubLayer: ToolRegistry
37
+ SubLayer: ToolExecutor
38
+ SubLayer: OutputValidator
39
+ Layer Memory
40
+ SubLayer: WorkingMemory
41
+ SubLayer: LongTermMemory
42
+ SubLayer: EpisodicMemory
43
+ Layer SelfReflection
44
+ SubLayer: PerformanceAssessor
45
+ SubLayer: StrategyAdaptor
46
+ SubLayer: UncertaintyEstimator
47
+ Layer MultiAgent
48
+ SubLayer: AgentCoordinator
49
+ SubLayer: MessageRouter
50
+ SubLayer: ConsensusBuilder
51
+
52
+ Validation Agent must produce auditable reasoning chains for every action taken
53
+ Validation Tool execution must validate outputs against expected schemas before processing
54
+ Validation Memory confidence scoring must be applied to all stored information
55
+ Validation Agent must halt and report when uncertainty exceeds configured threshold
56
+ Validation Multi-agent tasks must make measurable progress every N communication rounds
57
+ Validation Destructive actions must require explicit human approval before execution
58
+ Validation Agent must respect compute resource budgets and terminate on budget exhaustion
59
+ Validation Self-reflection must identify at least 80% of agent's own errors in post-hoc analysis
60
+
61
+ # Level 2 - Entities
62
+
63
+ Entity AgentTask
64
+ taskId: string
65
+ taskDescription: string
66
+ goalSpecification: dict
67
+ constraints: list
68
+ priority: integer
69
+ deadline: datetime
70
+ parentTaskId: string
71
+ assignedAgentId: string
72
+ status: string
73
+ createdAt: datetime
74
+ completedAt: datetime
75
+
76
+ Entity ReasoningStep
77
+ stepId: string
78
+ taskId: string
79
+ agentId: string
80
+ stepType: string
81
+ observation: dict
82
+ thought: string
83
+ action: dict
84
+ actionResult: dict
85
+ confidence: float
86
+ timestamp: datetime
87
+ depthLevel: integer
88
+ parentStepId: string
89
+
90
+ Entity ToolDefinition
91
+ toolId: string
92
+ toolName: string
93
+ description: string
94
+ inputSchema: dict
95
+ outputSchema: dict
96
+ requiredPermissions: list
97
+ riskLevel: string
98
+ rateLimit: dict
99
+ version: string
100
+ registeredAt: datetime
101
+
102
+ Entity MemoryEntry
103
+ entryId: string
104
+ agentId: string
105
+ entryType: string
106
+ content: dict
107
+ confidence: float
108
+ source: string
109
+ timestamp: datetime
110
+ accessCount: integer
111
+ lastAccessedAt: datetime
112
+ expirationAt: datetime
113
+ tags: list
114
+ validated: boolean
115
+
116
+ Entity AgentProfile
117
+ agentId: string
118
+ agentName: string
119
+ capabilities: list
120
+ toolAccess: list
121
+ authorityLevel: string
122
+ specializations: list
123
+ performanceMetrics: dict
124
+ communicationEndpoints: list
125
+ status: string
126
+ registeredAt: datetime
127
+
128
+ Entity CoordinationMessage
129
+ messageId: string
130
+ senderId: string
131
+ recipientId: string
132
+ messageType: string
133
+ payload: dict
134
+ priority: integer
135
+ requiresAck: boolean
136
+ timestamp: datetime
137
+ ttl: string
138
+
139
+ # Level 3 - Behaviors
140
+
141
+ Behavior PlanTask
142
+ Input:
143
+ task: AgentTask
144
+ agentProfile: AgentProfile
145
+ planningConfig: dict
146
+ Output:
147
+ executionPlan: dict
148
+ planConfidence: float
149
+ resourceEstimate: dict
150
+ Action:
151
+ Decompose task into ordered sub-goals
152
+ Identify required tools and capabilities for each sub-goal
153
+ Estimate resource requirements and execution time
154
+ Generate dependency graph between sub-goals
155
+ Identify potential failure points and contingency plans
156
+ Validate plan against agent capability boundaries
157
+ Compute overall plan confidence score
158
+ Return execution plan with confidence and resource estimates
159
+
160
+ Behavior ExecuteReasoning
161
+ Input:
162
+ task: AgentTask
163
+ executionPlan: dict
164
+ memoryContext: dict
165
+ Output:
166
+ reasoningChain: list
167
+ actionDecision: dict
168
+ confidence: float
169
+ Action:
170
+ Initialize reasoning chain with task context
171
+ For each step in execution plan:
172
+ Retrieve relevant memories for current context
173
+ Generate observation about current state
174
+ Form reasoning about next action
175
+ Evaluate confidence in proposed action
176
+ If confidence below threshold, seek clarification or alternative
177
+ Record step in reasoning chain
178
+ Return complete chain with final action decision
179
+
180
+ Behavior UseTool
181
+ Input:
182
+ toolDefinition: ToolDefinition
183
+ toolInput: dict
184
+ executionContext: dict
185
+ Output:
186
+ toolOutput: dict
187
+ validationResult: dict
188
+ executionReport: dict
189
+ Action:
190
+ Validate tool input against schema
191
+ Check agent permissions for tool access
192
+ If risk level high, require human confirmation
193
+ Execute tool with timeout and error handling
194
+ Validate tool output against expected schema
195
+ Record tool usage in execution trace
196
+ If validation fails, attempt recovery or alternative tool
197
+ Return output with validation result
198
+
199
+ Behavior StoreMemory
200
+ Input:
201
+ memoryEntry: MemoryEntry
202
+ storageConfig: dict
203
+ Output:
204
+ storedEntry: MemoryEntry
205
+ storageConfirmation: dict
206
+ Action:
207
+ Validate memory entry content and metadata
208
+ Compute confidence score based on source reliability
209
+ Check for conflicts with existing memories
210
+ If conflict, apply resolution strategy or flag for review
211
+ Apply data retention policy and set expiration
212
+ Store in appropriate memory tier (working, episodic, long-term)
213
+ Index entry for efficient retrieval
214
+ Return stored entry with confirmation
215
+
216
+ Behavior ReflectOnPerformance
217
+ Input:
218
+ task: AgentTask
219
+ reasoningChain: list
220
+ outcome: dict
221
+ Output:
222
+ reflectionReport: dict
223
+ strategyAdjustments: dict
224
+ learnedLessons: list
225
+ Action:
226
+ Review reasoning chain for logical errors or biases
227
+ Evaluate outcome against expected results
228
+ Identify steps where confidence was misplaced
229
+ Assess tool usage effectiveness and alternatives
230
+ Generate lessons learned for future tasks
231
+ Propose strategy adjustments for similar future tasks
232
+ Store reflection insights in long-term memory
233
+ Return reflection report with actionable improvements
234
+
235
+ Behavior CoordinateWithAgent
236
+ Input:
237
+ coordinationMessage: CoordinationMessage
238
+ multiAgentState: dict
239
+ Output:
240
+ coordinationResult: dict
241
+ updatedState: dict
242
+ responseMessage: CoordinationMessage
243
+ Action:
244
+ Parse coordination message and assess relevance
245
+ Evaluate impact on current task execution
246
+ Resolve any conflicts with planned actions
247
+ Contribute to shared goal progress
248
+ Build consensus on shared decisions if required
249
+ Acknowledge message and provide status update
250
+ Return coordination result with updated state
251
+
252
+ # Level 4 - Conditions
253
+
254
+ Condition: ConfidenceBelowThreshold
255
+ When agent confidence in next action falls below 0.6 threshold
256
+ Then halt execution; seek human clarification; attempt alternative approach; log uncertainty event for strategy improvement
257
+
258
+ Condition: ResourceBudgetExhausted
259
+ When cumulative compute or token usage exceeds allocated budget
260
+ Then checkpoint current state; summarize progress so far; request budget extension or terminate gracefully; report incomplete work
261
+
262
+ Condition: DestructiveActionProposed
263
+ When planned action is classified as destructive or irreversible
264
+ Then pause execution; present action details to human supervisor; require explicit approval before proceeding; log approval with reasoning
265
+
266
+ Condition: CoordinationDeadlock
267
+ When multi-agent coordination detects circular dependency or no progress for N rounds
268
+ Then escalate to coordinating agent; apply timeout-based resolution; propose simplified coordination plan; alert human supervisor if unresolved
269
+
270
+ Condition: MemoryConflictDetected
271
+ When new memory entry contradicts existing high-confidence memory
272
+ Then flag conflict for resolution; compare source reliability scores; quarantine conflicting entries; request human verification if critical
273
+
274
+ Condition: ToolExecutionTimeout
275
+ When tool execution exceeds configured timeout duration
276
+ Then terminate tool execution; attempt retry with backoff; select alternative tool if available; record timeout in execution trace
277
+
278
+ # Level 5 - Events
279
+
280
+ Event: TaskStarted
281
+ On agent beginning task execution
282
+ Action: initialize execution context; load relevant memories; emit progress heartbeat; activate monitoring
283
+
284
+ Event: ReasoningStepCompleted
285
+ On each reasoning step finishing
286
+ Action: record step in audit trail; update progress tracking; check confidence thresholds; evaluate need for course correction
287
+
288
+ Event: ToolExecuted
289
+ On tool execution completing with result
290
+ Action: validate output; update execution trace; store result in working memory; emit usage metrics
291
+
292
+ Event: ReflectionCompleted
293
+ On self-reflection analysis finished
294
+ Action: store learned lessons; update strategy parameters; adjust confidence calibration; notify coordination layer
295
+
296
+ Event: CoordinationMessageReceived
297
+ On message from another agent received
298
+ Action: parse and assess message; update shared state; respond with acknowledgment; integrate information into reasoning
299
+
300
+ Event: AgentHalted
301
+ On agent voluntarily halting due to uncertainty or safety concern
302
+ Action: checkpoint state; generate summary of progress; alert human supervisor; log halt reason for analysis
303
+
304
+ Event: TaskCompleted
305
+ On task execution finished with final result
306
+ Action: trigger self-reflection; store episodic memory; report results; release resources; update performance metrics
307
+
308
+ # Level 6 - Concurrency
309
+
310
+ Parallel:
311
+ Planning and memory retrieval simultaneously
312
+ Multiple tool executions with independent resources
313
+ Reasoning chain generation alongside memory updates
314
+ Multi-agent message processing concurrent with task execution
315
+ Self-reflection analysis in background during task execution
316
+ Memory indexing parallel with storage operations
317
+
318
+ # Level 7 - Optimization
319
+
320
+ Optimize: Reasoning efficiency and accuracy
321
+ Priority: Minimize reasoning steps while maintaining accuracy; cache similar reasoning patterns; use hierarchical planning for complex tasks
322
+
323
+ Optimize: Tool selection and execution
324
+ Priority: Select most reliable tool for each action; parallelize independent tool calls; cache tool results for repeated queries
325
+
326
+ Optimize: Memory retrieval relevance
327
+ Priority: Prioritize high-confidence recent memories; use semantic similarity for retrieval; compress older memories with summarization
328
+
329
+ # Level 8 - Learning
330
+
331
+ Learn: Planning strategy from task outcomes
332
+ Goal: Generate more effective execution plans with fewer failures
333
+ Adapt: Planning heuristics, decomposition strategy, and contingency selection
334
+ Based: Historical task outcomes, plan efficiency metrics, and failure pattern analysis
335
+
336
+ Learn: Tool selection optimization
337
+ Goal: Select optimal tools considering reliability, latency, and output quality
338
+ Adapt: Tool preference rankings and selection criteria
339
+ Based: Tool execution success rates, latency history, and output quality assessments
340
+
341
+ Learn: Confidence calibration
342
+ Goal: Accurately estimate confidence such that calibrated confidence matches actual success rate
343
+ Adapt: Confidence scoring parameters and threshold values
344
+ Based: Comparison of predicted confidence vs actual outcomes across historical decisions
345
+
346
+ Learn: Memory relevance scoring
347
+ Goal: Retrieve most relevant memories for each reasoning context
348
+ Adapt: Memory retrieval weights and recency-importance trade-off parameters
349
+ Based: Memory access patterns, reasoning step outcomes, and retrieval effectiveness metrics
350
+
351
+ Learn: Multi-agent coordination patterns
352
+ Goal: Develop efficient coordination strategies that minimize communication overhead
353
+ Adapt: Communication frequency, message content selection, and consensus strategy
354
+ Based: Coordination task outcomes, communication costs, and team performance metrics
355
+
356
+ # Level 9 - Security
357
+
358
+ Security:
359
+ Encrypt: All agent memory entries at rest using AES-256 with per-agent encryption keys
360
+ Encrypt: Inter-agent communication with TLS 1.3 and message signing for authenticity
361
+ Protect: Tool execution with permission enforcement and destructive action confirmation gates
362
+ Protect: Reasoning chain integrity with append-only audit logging and tamper detection
363
+ Protect: Agent authority boundaries with signed capability certificates and runtime enforcement
364
+ Encrypt: Task specifications containing sensitive information with field-level encryption
365
+ Protect: Coordination messages from eavesdropping and injection with authenticated encryption
366
+
367
+ # Level 10 - Native
368
+
369
+ Native: python
370
+ {
371
+ import hashlib
372
+ import json
373
+ from datetime import datetime, timedelta
374
+ from typing import Dict, List, Optional, Any, Tuple
375
+ from dataclasses import dataclass, field
376
+
377
+ @dataclass
378
+ class ReasoningChain:
379
+ steps: List[Dict] = field(default_factory=list)
380
+ max_depth: int = 50
381
+ max_iterations: int = 100
382
+
383
+ def add_step(self, step_type: str, observation: Dict, thought: str,
384
+ action: Dict, confidence: float, parent_id: Optional[str] = None) -> Dict:
385
+ step = {
386
+ "step_id": hashlib.sha256(
387
+ f"{step_type}:{len(self.steps)}:{datetime.utcnow().isoformat()}".encode()
388
+ ).hexdigest()[:16],
389
+ "step_type": step_type,
390
+ "observation": observation,
391
+ "thought": thought,
392
+ "action": action,
393
+ "confidence": confidence,
394
+ "timestamp": datetime.utcnow().isoformat(),
395
+ "depth_level": self._compute_depth(parent_id),
396
+ "parent_step_id": parent_id
397
+ }
398
+ self.steps.append(step)
399
+ return step
400
+
401
+ def _compute_depth(self, parent_id: Optional[str]) -> int:
402
+ if not parent_id:
403
+ return 0
404
+ for step in self.steps:
405
+ if step["step_id"] == parent_id:
406
+ return step["depth_level"] + 1
407
+ return 0
408
+
409
+ def is_within_limits(self) -> bool:
410
+ return len(self.steps) < self.max_iterations
411
+
412
+ def get_summary(self) -> Dict:
413
+ return {
414
+ "total_steps": len(self.steps),
415
+ "avg_confidence": sum(s["confidence"] for s in self.steps) / max(len(self.steps), 1),
416
+ "step_types": list(set(s["step_type"] for s in self.steps)),
417
+ "max_depth": max((s["depth_level"] for s in self.steps), default=0)
418
+ }
419
+
420
+ @dataclass
421
+ class ToolRegistry:
422
+ tools: Dict[str, Dict] = field(default_factory=dict)
423
+
424
+ def register(self, tool_id: str, name: str, description: str,
425
+ input_schema: Dict, output_schema: Dict,
426
+ permissions: List[str], risk_level: str = "low") -> Dict:
427
+ tool = {
428
+ "tool_id": tool_id,
429
+ "tool_name": name,
430
+ "description": description,
431
+ "input_schema": input_schema,
432
+ "output_schema": output_schema,
433
+ "required_permissions": permissions,
434
+ "risk_level": risk_level,
435
+ "version": "1.0",
436
+ "registered_at": datetime.utcnow().isoformat()
437
+ }
438
+ self.tools[tool_id] = tool
439
+ return tool
440
+
441
+ def validate_input(self, tool_id: str, inputs: Dict) -> Tuple[bool, List[str]]:
442
+ tool = self.tools.get(tool_id)
443
+ if not tool:
444
+ return False, [f"Tool {tool_id} not found"]
445
+ schema = tool["input_schema"]
446
+ errors = []
447
+ for required_field, field_type in schema.get("required", {}).items():
448
+ if required_field not in inputs:
449
+ errors.append(f"Missing required field: {required_field}")
450
+ elif field_type == "string" and not isinstance(inputs[required_field], str):
451
+ errors.append(f"Field {required_field} must be string")
452
+ elif field_type == "integer" and not isinstance(inputs[required_field], int):
453
+ errors.append(f"Field {required_field} must be integer")
454
+ return len(errors) == 0, errors
455
+
456
+ def check_permission(self, tool_id: str, agent_permissions: List[str]) -> bool:
457
+ tool = self.tools.get(tool_id)
458
+ if not tool:
459
+ return False
460
+ required = set(tool["required_permissions"])
461
+ available = set(agent_permissions)
462
+ return required.issubset(available)
463
+
464
+ @dataclass
465
+ class AgentMemory:
466
+ working_memory: Dict[str, Dict] = field(default_factory=dict)
467
+ episodic_memory: List[Dict] = field(default_factory=list)
468
+ long_term_memory: Dict[str, List[Dict]] = field(default_factory=dict)
469
+ max_working_size: int = 100
470
+
471
+ def store(self, entry_type: str, content: Dict, confidence: float,
472
+ source: str, tags: List[str] = None) -> Dict:
473
+ entry = {
474
+ "entry_id": hashlib.sha256(
475
+ f"{entry_type}:{datetime.utcnow().isoformat()}".encode()
476
+ ).hexdigest()[:16],
477
+ "entry_type": entry_type,
478
+ "content": content,
479
+ "confidence": confidence,
480
+ "source": source,
481
+ "timestamp": datetime.utcnow().isoformat(),
482
+ "access_count": 0,
483
+ "tags": tags or [],
484
+ "validated": confidence >= 0.8
485
+ }
486
+
487
+ if entry_type == "working":
488
+ if len(self.working_memory) >= self.max_working_size:
489
+ self._evict_working_memory()
490
+ self.working_memory[entry["entry_id"]] = entry
491
+ elif entry_type == "episodic":
492
+ self.episodic_memory.append(entry)
493
+ elif entry_type == "long_term":
494
+ for tag in (tags or ["default"]):
495
+ self.long_term_memory.setdefault(tag, []).append(entry)
496
+
497
+ return entry
498
+
499
+ def retrieve(self, query: str, limit: int = 5, min_confidence: float = 0.5) -> List[Dict]:
500
+ results = []
501
+ for entry in self.working_memory.values():
502
+ if entry["confidence"] >= min_confidence:
503
+ results.append(entry)
504
+ results.sort(key=lambda x: x["confidence"], reverse=True)
505
+ return results[:limit]
506
+
507
+ def _evict_working_memory(self) -> None:
508
+ if not self.working_memory:
509
+ return
510
+ oldest_key = min(self.working_memory, key=lambda k: self.working_memory[k]["access_count"])
511
+ evicted = self.working_memory.pop(oldest_key)
512
+ self.episodic_memory.append(evicted)
513
+
514
+ @dataclass
515
+ class SelfReflector:
516
+ error_detection_rate_target: float = 0.8
517
+
518
+ def reflect(self, reasoning_chain: ReasoningChain, outcome: Dict) -> Dict:
519
+ steps = reasoning_chain.steps
520
+ low_confidence_steps = [s for s in steps if s["confidence"] < 0.6]
521
+ errors_identified = []
522
+
523
+ for step in steps:
524
+ if step["confidence"] < 0.5:
525
+ errors_identified.append({
526
+ "step_id": step["step_id"],
527
+ "issue": "low_confidence",
528
+ "confidence": step["confidence"],
529
+ "thought": step["thought"]
530
+ })
531
+
532
+ success = outcome.get("success", False)
533
+ lessons = []
534
+ if not success and low_confidence_steps:
535
+ lessons.append("Low confidence steps correlated with task failure")
536
+ if not success:
537
+ lessons.append("Review planning phase for missed dependencies")
538
+
539
+ return {
540
+ "total_steps": len(steps),
541
+ "low_confidence_steps": len(low_confidence_steps),
542
+ "errors_identified": errors_identified,
543
+ "lessons_learned": lessons,
544
+ "outcome_success": success,
545
+ "recommended_adjustments": self._generate_adjustments(steps, outcome)
546
+ }
547
+
548
+ def _generate_adjustments(self, steps: List[Dict], outcome: Dict) -> List[str]:
549
+ adjustments = []
550
+ if not outcome.get("success", False):
551
+ adjustments.append("Increase confidence threshold before action execution")
552
+ adjustments.append("Add more contingency plans in execution strategy")
553
+ avg_confidence = sum(s["confidence"] for s in steps) / max(len(steps), 1)
554
+ if avg_confidence < 0.7:
555
+ adjustments.append("Improve observation quality before reasoning steps")
556
+ return adjustments
557
+ }