🧠Beyond Single-Step Prompting: The Architecture of Planning and Self-Correction
Standard LLM inference solves prompts in a single forward pass, which fails when facing complex, multi-stage problems that require strategic foresight and error correction. Autonomous Planning & Reflection empower agents to first break down ambiguous goals into ordered sub-tasks (Task Decomposition), execute them iteratively, and evaluate their own output quality (Self-Reflection / Reflexion). If errors or hallucinations are detected, the agent critiques its work, discards failed trajectories, and refines its approach before delivering a final validated result.
📊 End-to-End Agentic Planning, Execution & Reflection Workflow Diagram
1. User Goal Input
Ambiguous or complex user prompt received by agent.
2. Task Decomposition
Agent breaks goal into ordered sub-tasks (Plan generation).
3. Tool Execution
Agent executes current sub-task using registered tools/APIs.
6. Final Output / Delivery
Validated result delivered to user.
5. Self-Reflection & Critique
Evaluates result quality. If flawed, triggers replanning loop.
4. Observation Capture
Gathers output data from tool execution and environment.
Workflow Steps: Plan file edits → Apply refactor → Run test suite → Reflect on test traceback → Fix syntax error → Finalize.
import subprocess
from openai import OpenAI
client = OpenAI()
def self_correcting_code_agent(file_path: str, objective: str):
for attempt in range(3):
# 1. Execute test suite
result = subprocess.run(["pytest", file_path], capture_output=True, text=True)
if result.returncode == 0:
return f"Success: Code passed all tests on attempt {attempt+1}."
# 2. Reflection Phase: Analyze failure traceback
critique_prompt = f"Pytest failed with error:\n{result.stderr}\nReflect on why the test failed and output corrected code patch."
correction = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": critique_prompt}]).choices.message.content
# Apply correction patch to file
with open(file_path, "w") as f:
f.write(correction)
return "Max self-correction iterations reached."
Workflow Steps: Decompose financial claims → Query EDGAR database → Compare numbers → Flag variance → Generate audit memo.
def audit_financial_claims(claims: list[str], sec_filing_data: dict) -> list[str]:
audit_log = []
for claim in claims:
# Reflection & Verification
verified = sec_filing_data.get(claim['metric']) == claim['stated_value']
if not verified:
audit_log.append(f"DISCREPANCY FLAGGED: Claim {claim['metric']} of {claim['stated_value']} contradicts SEC filing.")
return audit_log
Workflow Steps: Isolate pod → Check cluster telemetry → Reflect on firewall drop failure → Escalate to security gateway.
def execute_threat_containment(threat_ip: str):
plan = ["isolate_pod", "verify_network_drop", "notify_soc"]
for step in plan:
success = execute_step(step, threat_ip)
if not success:
print(f"[Reflection] Step {step} failed. Re-planning containment strategy...")
execute_fallback_protocol(threat_ip)
break
Workflow Steps: Ingest EHR → Propose differential diagnosis → Critique against medical guidelines → Output verified recommendation.
def clinical_reflection_audit(initial_diagnosis: str, patient_labs: dict) -> str:
# Critique initial diagnosis against lab markers
if "anemia" in initial_diagnosis.lower() and patient_labs.get("hemoglobin", 14) > 13.5:
return "CRITIQUE REJECTED: Hemoglobin levels are normal. Re-evaluating differential diagnosis."
return "Diagnosis verified against laboratory telemetry."
Workflow Steps: Plan primary route → Monitor weather API → Detect roadblock → Re-plan alternative freight corridor.
def adaptive_route_planner(route_id: str, weather_alert: bool):
if weather_alert:
print("[Reflection] Primary corridor blocked by storm. Devising secondary rail/road routing plan...")
new_plan = calculate_alternative_corridor(route_id)
return new_plan
return "Proceeding along optimal scheduled route."
Workflow Steps: Parse contract → Decompose indemnity clauses → Compare with corporate playbook → Generate counter-proposal.
def review_contract_clause(clause_text: str, playbook_limit: float) -> str:
extracted_liability = parse_liability_cap(clause_text)
if extracted_liability > playbook_limit:
return f"CRITIQUE: Liability cap of ${extracted_liability} exceeds corporate threshold of ${playbook_limit}. Flagged for renegotiation."
return "Clause complies with corporate risk playbook."
Workflow Steps: Scrape competitor prices → Propose price drop → Calculate profit margin → Reflect on margin floor violation → Adjust pricing.
def evaluate_pricing_strategy(proposed_price: float, cost_basis: float, min_margin_pct: float) -> float:
margin = (proposed_price - cost_basis) / proposed_price
if margin < min_margin_pct:
safe_price = cost_basis / (1.0 - min_margin_pct)
print(f"[Reflection] Proposed price violates floor margin. Adjusting from ${proposed_price} to safe floor ${safe_price:.2f}")
return safe_price
return proposed_price
Workflow Steps: Outline syllabus → Assess quiz results → Reflect on knowledge gaps → Re-sequence remedial study plan.
def adapt_syllabus(current_syllabus: list[str], failed_topic: str) -> list[str]:
print(f"[Reflection] Student struggled with '{failed_topic}'. Inserting foundational remedial module.")
remedial_module = f"Remedial: Fundamentals of {failed_topic}"
idx = current_syllabus.index(failed_topic)
current_syllabus.insert(idx, remedial_module)
return current_syllabus
Workflow Steps: Trigger DNS switch → Monitor DB replication lag → Reflect on high latency → Throttle non-critical traffic.
def validate_regional_failover(replication_lag_ms: float) -> str:
if replication_lag_ms > 500.0:
return "[Reflection] Replication lag exceeds 500ms threshold. Deferring full traffic cutover; enabling read-replica buffering."
return "Secondary region health validated. Executing DNS traffic cutover."
Workflow Steps: Train model → Monitor loss curve → Detect plateau → Reflect & reduce learning rate → Resume training.
class LearningRateSchedulerAgent:
def __init__(self, initial_lr: float):
self.lr = initial_lr
self.best_loss = float('inf')
self.patience_counter = 0
def evaluate_epoch(self, val_loss: float) -> float:
if val_loss < self.best_loss:
self.best_loss = val_loss
self.patience_counter = 0
else:
self.patience_counter += 1
if self.patience_counter >= 3:
self.lr *= 0.5
print(f"[Reflection] Validation loss plateaued. Reducing learning rate to {self.lr}")
self.patience_counter = 0
return self.lr