📋 Planning Agents
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Hiểu Plan-and-Execute Pattern cho AI Agents
✅ Viết được Planning Prompt để break down tasks
✅ Implement step-by-step executor trong n8n
✅ Xây dựng Adaptive Re-planning khi step fails
✅ Nắm được ReAct Pattern (Reason + Act)
✅ Build được Multi-Step Research Agent
Planning agents có thể break down complex tasks thành steps, execute sequentially, và adapt khi gặp problems.
🔍 Plan-and-Execute Pattern
Checkpoint
Plan-and-Execute Pattern hoạt động như thế nào? Điều gì xảy ra khi một step thất bại?
🛠️ Planning Prompt
1// OpenAI node: Generate execution plan2const planPrompt = `3You are a task planning agent. Break down this task into executable steps.45Task: "${$json.task}"67Available tools:8- web_search: Search the internet for information9- calculator: Perform calculations10- database_query: Query a database11- send_email: Send an email12- create_document: Create a document13- http_request: Call any API1415Create a step-by-step plan:161. Each step should use exactly one tool172. Steps should be in correct order183. Include expected output for each step194. Include fallback if a step fails2021Return JSON:22{23 "task": "original task",24 "steps": [25 {26 "step": 1,27 "action": "tool_name",28 "description": "what this step does",29 "input": "what to send to the tool",30 "expectedOutput": "what to expect back",31 "fallback": "what to do if this fails"32 }33 ],34 "estimatedTime": "total time estimate"35}`;Checkpoint
Planning Prompt cần chứa những thông tin gì? Tại sao mỗi step cần có fallback?
⚡ Executing Plans trong n8n
1// Code node: Step executor (inside Loop)2const step = $json.currentStep;3const previousResults = $json.previousResults || [];45// Build context from previous steps6const context = previousResults.map(r => 7 `Step ${r.step}: ${r.result}`8).join('\n');910// Route to appropriate tool11let toolConfig;12switch (step.action) {13 case "web_search":14 toolConfig = {15 route: "http_request",16 url: `https://api.search.com/search?q=${encodeURIComponent(step.input)}`,17 method: "GET"18 };19 break;20 case "database_query":21 toolConfig = {22 route: "database",23 query: step.input24 };25 break;26 case "send_email":27 toolConfig = {28 route: "email",29 to: step.input.to,30 subject: step.input.subject,31 body: step.input.body32 };33 break;34 default:35 toolConfig = { route: "code", input: step.input };36}3738return { json: { ...step, toolConfig, context } };Checkpoint
Step executor trong n8n hoạt động như thế nào? Làm sao để route đúng tool cho mỗi step?
🔄 Adaptive Re-planning
1// When a step fails, re-plan remaining steps2const replanPrompt = `3Original plan:4${JSON.stringify($json.originalPlan, null, 2)}56Completed steps:7${$json.completedSteps.map(s => `Step ${s.step}: ${s.status} - ${s.result}`).join('\n')}89Failed step:10Step ${$json.failedStep.step}: ${$json.failedStep.error}1112Create a revised plan for the remaining work.13Consider what was already done and the failure reason.1415Return JSON with revised remaining steps.`;Checkpoint
Adaptive Re-planning hoạt động như thế nào? Prompt cần chứa những context gì để re-plan hiệu quả?
🧠 ReAct Pattern (Reason + Act)
1// ReAct: Agent reasons about what to do, acts, observes, repeats23const reactPrompt = `4You are a ReAct agent. For each step:51. Thought: Reason about what to do62. Action: Choose a tool and input73. Observation: Process the result84. Repeat until task is complete910Task: ${$json.task}1112Available Actions: search, calculate, lookup, respond1314Format:15Thought: [reasoning]16Action: [tool_name] [input]17Observation: [result after execution]18... repeat ...19Thought: I now have enough information20Action: respond [final answer]21`;2223// n8n implements this via Agent node loops24// Agent node with Tools = ReAct patternCheckpoint
ReAct Pattern gồm những bước nào? So sánh ReAct với Plan-and-Execute, khi nào dùng pattern nào?
🔬 Multi-Step Research Agent
1// Research Agent implementation2// Step 1: Plan search queries3const planPrompt = `4For the research question: "${$json.question}"5Generate 3-5 specific search queries that would help answer this.6Return as JSON array: ["query1", "query2", ...]`;78// Step 2: Execute searches (Loop)9// Step 3: Analyze each result (AI)10// Step 4: Synthesize into report (AI with all context)Checkpoint
Research Agent cần những steps nào? Làm sao để synthesize findings từ multiple search results?
🛡️ Error Handling & Tips
1// Code node: Agent error handler2const maxRetries = 3;3const currentRetry = $json.retryCount || 0;45if ($json.stepResult.error) {6 if (currentRetry < maxRetries) {7 // Retry with modified approach8 return {9 json: {10 action: "retry",11 retryCount: currentRetry + 1,12 modifiedInput: `Previous attempt failed: ${$json.stepResult.error}. Try a different approach.`13 }14 };15 } else {16 // Skip and continue with fallback17 return {18 json: {19 action: "skip",20 result: $json.currentStep.fallback || "Step skipped due to errors"21 }22 };23 }24}2526// Success27return { json: { action: "continue", result: $json.stepResult.data } };- Simple first: Start với 3-5 step plans, không quá complex
- Fallbacks: Luôn có fallback cho mỗi step
- Max steps: Set limit (10-15 steps max) để tránh infinite loops
- Logging: Log mỗi step result để debug
Checkpoint
Cách xử lý lỗi trong Planning Agent? Tại sao cần set max steps limit?
📚 Bài tập thực hành
- Build planning agent: input task, output execution plan
- Implement step-by-step executor với Loop node
- Add adaptive re-planning khi step fails
- Build research agent thực hiện multi-step investigation
Checkpoint
Bạn đã build được planning agent hoàn chỉnh chưa? Agent có thể re-plan khi gặp lỗi không?
🚀 Bài tiếp theo
Bài tiếp theo: Custom Tools →
