MinAI - Về trang chủ
Lý thuyết
5/1335 phút
Đang tải...

Planning Agents

Xây dựng agents có khả năng lập kế hoạch và thực thi multi-step tasks

📋 Planning Agents

0

🎯 Mục tiêu bài học

TB5 min

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.

1

🔍 Plan-and-Execute Pattern

TB5 min
Diagram
Đang vẽ diagram...

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?

2

🛠️ Planning Prompt

TB5 min
JavaScript
1// OpenAI node: Generate execution plan
2const planPrompt = `
3You are a task planning agent. Break down this task into executable steps.
4
5Task: "${$json.task}"
6
7Available tools:
8- web_search: Search the internet for information
9- calculator: Perform calculations
10- database_query: Query a database
11- send_email: Send an email
12- create_document: Create a document
13- http_request: Call any API
14
15Create a step-by-step plan:
161. Each step should use exactly one tool
172. Steps should be in correct order
183. Include expected output for each step
194. Include fallback if a step fails
20
21Return 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?

3

⚡ Executing Plans trong n8n

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Code node: Step executor (inside Loop)
2const step = $json.currentStep;
3const previousResults = $json.previousResults || [];
4
5// Build context from previous steps
6const context = previousResults.map(r =>
7 `Step ${r.step}: ${r.result}`
8).join('\n');
9
10// Route to appropriate tool
11let 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.input
24 };
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.body
32 };
33 break;
34 default:
35 toolConfig = { route: "code", input: step.input };
36}
37
38return { 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?

4

🔄 Adaptive Re-planning

TB5 min
JavaScript
1// When a step fails, re-plan remaining steps
2const replanPrompt = `
3Original plan:
4${JSON.stringify($json.originalPlan, null, 2)}
5
6Completed steps:
7${$json.completedSteps.map(s => `Step ${s.step}: ${s.status} - ${s.result}`).join('\n')}
8
9Failed step:
10Step ${$json.failedStep.step}: ${$json.failedStep.error}
11
12Create a revised plan for the remaining work.
13Consider what was already done and the failure reason.
14
15Return 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ả?

5

🧠 ReAct Pattern (Reason + Act)

TB5 min
JavaScript
1// ReAct: Agent reasons about what to do, acts, observes, repeats
2
3const reactPrompt = `
4You are a ReAct agent. For each step:
51. Thought: Reason about what to do
62. Action: Choose a tool and input
73. Observation: Process the result
84. Repeat until task is complete
9
10Task: ${$json.task}
11
12Available Actions: search, calculate, lookup, respond
13
14Format:
15Thought: [reasoning]
16Action: [tool_name] [input]
17Observation: [result after execution]
18... repeat ...
19Thought: I now have enough information
20Action: respond [final answer]
21`;
22
23// n8n implements this via Agent node loops
24// Agent node with Tools = ReAct pattern

Checkpoint

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?

6

🔬 Multi-Step Research Agent

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Research Agent implementation
2// Step 1: Plan search queries
3const planPrompt = `
4For the research question: "${$json.question}"
5Generate 3-5 specific search queries that would help answer this.
6Return as JSON array: ["query1", "query2", ...]`;
7
8// 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?

7

🛡️ Error Handling & Tips

TB5 min
JavaScript
1// Code node: Agent error handler
2const maxRetries = 3;
3const currentRetry = $json.retryCount || 0;
4
5if ($json.stepResult.error) {
6 if (currentRetry < maxRetries) {
7 // Retry with modified approach
8 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 fallback
17 return {
18 json: {
19 action: "skip",
20 result: $json.currentStep.fallback || "Step skipped due to errors"
21 }
22 };
23 }
24}
25
26// Success
27return { json: { action: "continue", result: $json.stepResult.data } };
Planning Tips
  • 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?

8

📚 Bài tập thực hành

TB5 min
Exercises
  1. Build planning agent: input task, output execution plan
  2. Implement step-by-step executor với Loop node
  3. Add adaptive re-planning khi step fails
  4. 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 →