Lesson 04 — Intermediate
PLANNING & TASK DECOMPOSITION:
COMPLEX TASKS KO SIMPLE STEPS MEIN TODNA.
Planning se complex tasks simple steps mein divide hote hain — agents better decisions le paate hain. Bina planning ke agent confused ho jaata hai, planning se woh organized aur efficient hota hai.
WHY: Planning agents ke liye kyun zaroori hai?
Socho tumhe ek thesis likhni hai — agar ek saath sab kuch likhne ki koshish karo toh pagal ho jaoge. Lekin agar pehle outline banao, phir har section par kaam karo, toh kaam aasan ho jaata hai. Yehi planning hai — complex task ko manageable chunks mein todna. Agents ke liye bhi yehi rule apply hota hai.
Bade task ko chhote steps mein todna — jaise "build a chatbot" ko "design conversation flow", "train model", "test responses", "deploy" mein todna.
Step-by-step sochna — ek ek step karke problem solve karna. Jaise maths mein solution likhte ho — pehle given, phir formula, phir calculation.
Multiple paths explore karna — ek se zyada options dekhna aur best choose karna. Jaise chess mein har move ka sochna.
Apne kaam ko evaluate karna — kya sahi hai, kya galat hai, kya improve ho sakta hai. Self-improvement ka powerful tool.
Task Decomposition: Bade task ko chhote pieces mein
Task decomposition sabse basic planning technique hai. Agent ek bada task leta hai aur usse logically chhote subtasks mein tod deta hai. Har subtask independently solve kiya ja sakta hai.
# Task decomposition
class Planner:
def __init__(self):
self.tasks = []
def decompose(self, main_task):
# Simple decomposition
subtasks = [
{"step": 1, "task": f"Analyze: {main_task}", "status": "pending"},
{"step": 2, "task": "Gather information", "status": "pending"},
{"step": 3, "task": "Execute plan", "status": "pending"},
{"step": 4, "task": "Verify results", "status": "pending"}
]
self.tasks = subtasks
return subtasks
def execute_next(self):
for task in self.tasks:
if task["status"] == "pending":
task["status"] = "done"
return task
return None
def get_progress(self):
done = sum(1 for t in self.tasks if t["status"] == "done")
return f"{done}/{len(self.tasks)} tasks complete"
planner = Planner()
print(planner.decompose("Build a chatbot"))
print(planner.execute_next())
print(planner.get_progress())Chain of Thought: Step-by-Step Reasoning
Chain of Thought (CoT) technique hai jismein agent ek ek step karke sochta hai. Ye LLM ko complex problems solve karne mein help karti hai — direct answer dene ki jagah reasoning dikhati hai.
# Chain of Thought reasoning
class ChainOfThought:
def __init__(self):
self.steps = []
def think(self, problem):
# Break problem into reasoning steps
self.steps = [
f"Problem: {problem}",
"Step 1: What do we know?",
"Step 2: What do we need to find?",
"Step 3: Apply relevant concepts",
"Step 4: Calculate/derive answer",
"Step 5: Verify the answer"
]
return self.steps
def show_reasoning(self):
print("=== Chain of Thought ===")
for i, step in enumerate(self.steps):
print(f" {i+1}. {step}")
# Usage
cot = ChainOfThought()
print(cot.think("Calculate 15% tip on $80 bill"))
cot.show_reasoning()Tree of Thoughts: Multiple Paths Explore Karna
Tree of Thoughts (ToT) mein agent ek problem ke liye multiple approaches sochta hai, unhe evaluate karta hai, aur best choose karta hai. Jaise chess player har move ka sochta hai — ye approach tree banati hai.
# Tree of Thoughts - Multiple paths
class TreeOfThoughts:
def __init__(self):
self.paths = []
def explore(self, problem):
# Generate multiple thought paths
self.paths = [
{"path": "A", "thought": f"Direct approach for: {problem}", "score": 0.7},
{"path": "B", "thought": f"Alternative approach for: {problem}", "score": 0.9},
{"path": "C", "thought": f"Creative approach for: {problem}", "score": 0.6}
]
return self.paths
def evaluate(self):
# Score each path and pick best
best = max(self.paths, key=lambda x: x["score"])
return best
def show_tree(self):
print("=== Thought Tree ===")
for p in self.paths:
marker = "?" if p == self.evaluate() else " "
print(f" {marker} Path {p['path']}: {p['thought']} (score: {p['score']})")
# Usage
tot = TreeOfThoughts()
print(tot.explore("How to improve code quality"))
tot.show_tree()
print(f"\nBest path: {tot.evaluate()['path']}")Self-Critique: Apne Kaam Ko Evaluate Karna
Self-critique mein agent apne output ko evaluate karta hai — kya sahi hai, kya galat hai, kya improve ho sakta hai. Ye self-improvement ka powerful mechanism hai.
# Self-critique pattern
class SelfCritic:
def __init__(self):
self.criteria = []
def set_criteria(self, criteria_list):
self.criteria = criteria_list
def critique(self, work):
# Evaluate work against criteria
results = []
for criterion in self.criteria:
score = self._evaluate(work, criterion)
results.append({
"criterion": criterion,
"score": score,
"feedback": self._get_feedback(score)
})
return results
def _evaluate(self, work, criterion):
# Simple scoring (in real use, LLM would evaluate)
import random
return random.uniform(0.5, 1.0)
def _get_feedback(self, score):
if score > 0.8: return "Excellent"
elif score > 0.6: return "Good, but room for improvement"
else: return "Needs significant work"
def summary(self, results):
avg_score = sum(r["score"] for r in results) / len(results)
return f"Average quality: {avg_score:.2f}/1.0"
# Usage
critic = SelfCritic()
critic.set_criteria(["Clarity", "Completeness", "Correctness"])
work = "My code solution for the problem"
results = critic.critique(work)
for r in results:
print(f" {r['criterion']}: {r['score']:.2f} - {r['feedback']}")
print(critic.summary(results))Real-World Planning Example
Ab ek complete example dekhte hain — agent jo planning use karke complex task solve karta hai:
# Complete planning agent
class PlanningAgent:
def __init__(self):
self.planner = Planner()
self.critic = SelfCritic()
def solve(self, task):
print(f"Task: {task}")
# Step 1: Decompose
print("\n1. Decomposing task...")
subtasks = self.planner.decompose(task)
for t in subtasks:
print(f" - {t['task']}")
# Step 2: Execute each step
print("\n2. Executing steps...")
while True:
next_task = self.planner.execute_next()
if not next_task:
break
print(f" Done: {next_task['task']}")
# Step 3: Self-critique
print("\n3. Self-evaluation...")
self.critic.set_criteria(["Completeness", "Quality", "Efficiency"])
results = self.critic.critique("completed task")
for r in results:
print(f" {r['criterion']}: {r['score']:.2f}")
# Progress
print(f"\nProgress: {self.planner.get_progress()}")
return "Task completed successfully!"
# Use it
agent = PlanningAgent()
agent.solve("Build a recommendation system")Try it: Build a Task Planner
Neeche code likho ya edit karo, phir "Run" pe click karo. Dekho kaise planning kaam karti hai:
Exercise: Test Your Knowledge
Quick check
"Task decomposition kya hai?"
Socho: jab ek bada task bahut mushkil lagta hai, toh kya karte ho✓ Usse chhote hisson mein baantte ho na?
Key Takeaways
- Task Decomposition: Bade task ko chhote steps mein todna — agents organized aur efficient hote hain.
- Chain of Thought: Step-by-step sochna — complex problems solve karne ka tarika.
- Tree of Thoughts: Multiple paths explore karna — best approach choose karna.
- Self-Critique: Apne kaam ko evaluate karna — self-improvement ka tool.
- Planning se clarity: Agent ko pata hota hai ki kya karna hai, kab karna hai, aur kaise karna hai.
Ab Memory Systems par chalo — taaki aap samajh sako ki agents ko yaad kaise rakhte hain aur context kaise maintain karte hain.