Agent Planning
Planning enables Agents to break down complex tasks into manageable steps. Use the simplifiedPlanningAgent for automatic plan creation and execution.
PlanningAgent (Recommended)
ThePlanningAgent automatically creates and executes plans:
Copy
import { PlanningAgent } from 'praisonai';
const agent = new PlanningAgent({
instructions: 'You break down tasks into clear steps.',
maxSteps: 5 // Limit steps per plan
});
// Create and execute a plan in one call
const result = await agent.planAndExecute('Build a simple web scraper');
console.log('Plan:', result.plan.name);
console.log('Steps:', result.plan.steps.length);
console.log('Success:', result.success);
console.log('Results:', result.results);
Create Plan Only
Create a plan without executing:Copy
import { PlanningAgent } from 'praisonai';
const agent = new PlanningAgent();
// Just create the plan
const plan = await agent.createPlan('Launch a new product');
console.log('Plan steps:');
plan.steps.forEach((step, i) => {
console.log(`${i + 1}. ${step.description}`);
});
// Execute steps manually
for (const step of plan.steps) {
const result = await agent.executeStep(step);
console.log(`Completed: ${step.description}`);
}
TaskAgent for Todo Lists
UseTaskAgent for simple task management:
Copy
import { TaskAgent } from 'praisonai';
const agent = new TaskAgent();
// Add tasks with priorities
agent.addTask('Fix critical bug', 'high');
agent.addTask('Write documentation', 'medium');
agent.addTask('Review PR', 'low');
// Check pending tasks
console.log('Pending:', agent.getPendingTasks().length);
// Complete a task
agent.completeTask('bug');
// Get progress
console.log('Progress:', agent.getProgress().percentage + '%');
// Chat about tasks
const response = await agent.chat('What should I work on next?');
Advanced: Custom Planning with Tools
For more control, create custom planning tools:Copy
import { Agent, Plan, PlanStep, createTool } from 'praisonai';
const createPlanTool = createTool({
name: 'create_plan',
description: 'Create a step-by-step plan',
parameters: {
type: 'object',
properties: {
name: { type: 'string' },
steps: { type: 'array', items: { type: 'string' } }
},
required: ['name', 'steps']
},
execute: async ({ name, steps }) => {
const plan = new Plan({ name });
steps.forEach((step: string) => plan.addStep(new PlanStep({ description: step })));
return `Created plan "${name}" with ${steps.length} steps`;
}
});
const agent = new Agent({
instructions: 'Break down tasks into plans.',
tools: [createPlanTool]
});
await agent.chat('Create a plan for building a web app');
Multi-Agent Planning
Agents collaborate on a shared plan:Copy
import { Agent, Plan, PlanStep, Agents } from 'praisonai';
const sharedPlan = new Plan({ name: 'Product Launch' });
// Planner Agent creates the plan
const plannerAgent = new Agent({
name: 'Planner',
instructions: 'Create detailed project plans with clear steps.'
});
// Executor Agents work on steps
const devAgent = new Agent({
name: 'Developer',
instructions: 'Execute technical development steps.'
});
const marketingAgent = new Agent({
name: 'Marketer',
instructions: 'Execute marketing and launch steps.'
});
async function collaborativePlanning(goal: string) {
// Planner creates the plan
const planDescription = await plannerAgent.chat(`Create a plan for: ${goal}`);
// Parse and create steps
const steps = planDescription.split('\n').filter(s => s.trim());
steps.forEach(step => sharedPlan.addStep(new PlanStep({ description: step })));
// Execute steps with appropriate agents
for (const step of sharedPlan.steps) {
step.start();
const agent = step.description.includes('develop') ? devAgent : marketingAgent;
await agent.chat(`Execute this step: ${step.description}`);
step.complete();
const progress = sharedPlan.getProgress();
console.log(`Progress: ${progress.percentage}%`);
}
sharedPlan.complete();
}
await collaborativePlanning('Launch new feature');
Agent with Todo List
Agents manage tasks with priorities:Copy
import { Agent, TodoList, TodoItem, createTool } from 'praisonai';
const todos = new TodoList('Agent Tasks');
const addTaskTool = createTool({
name: 'add_task',
description: 'Add a task to the todo list',
parameters: {
type: 'object',
properties: {
task: { type: 'string', description: 'Task description' },
priority: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Priority' }
},
required: ['task']
},
execute: async ({ task, priority = 'medium' }) => {
todos.add(new TodoItem({ content: task, priority }));
return `Added: ${task} (${priority} priority)`;
}
});
const completeTaskTool = createTool({
name: 'complete_task',
description: 'Mark a task as complete',
parameters: {
type: 'object',
properties: {
task: { type: 'string', description: 'Task to complete' }
},
required: ['task']
},
execute: async ({ task }) => {
const item = todos.items.find(t => t.content.includes(task));
if (item) {
item.complete();
return `Completed: ${task}`;
}
return `Task not found: ${task}`;
}
});
const getTasksTool = createTool({
name: 'get_tasks',
description: 'Get pending tasks',
parameters: { type: 'object', properties: {} },
execute: async () => {
const pending = todos.getPending();
return pending.map(t => `[${t.priority}] ${t.content}`).join('\n') || 'No pending tasks';
}
});
const taskAgent = new Agent({
name: 'Task Manager',
instructions: `You manage a todo list.
- Add tasks with appropriate priorities
- Complete tasks when done
- Check pending tasks regularly`,
tools: [addTaskTool, completeTaskTool, getTasksTool]
});
await taskAgent.chat('Add high priority task: Fix critical bug');
await taskAgent.chat('Add medium priority task: Write documentation');
await taskAgent.chat('What tasks are pending?');
await taskAgent.chat('Complete the bug fix task');
Agent with Adaptive Planning
Agent adjusts plan based on results:Copy
import { Agent, Plan, PlanStep, createTool } from 'praisonai';
let currentPlan: Plan | null = null;
const createPlanTool = createTool({
name: 'create_plan',
description: 'Create an execution plan',
parameters: {
type: 'object',
properties: {
name: { type: 'string' },
steps: { type: 'array', items: { type: 'string' } }
},
required: ['name', 'steps']
},
execute: async ({ name, steps }) => {
currentPlan = new Plan({ name });
steps.forEach((s: string) => currentPlan!.addStep(new PlanStep({ description: s })));
return `Plan created with ${steps.length} steps`;
}
});
const executeStepTool = createTool({
name: 'execute_step',
description: 'Execute the next pending step',
parameters: { type: 'object', properties: {} },
execute: async () => {
if (!currentPlan) return 'No plan exists';
const nextStep = currentPlan.steps.find(s => s.status === 'pending');
if (!nextStep) return 'All steps completed';
nextStep.start();
// Simulate execution with possible failure
const success = Math.random() > 0.2;
if (success) {
nextStep.complete();
return `Completed: ${nextStep.description}`;
} else {
nextStep.fail();
return `Failed: ${nextStep.description} - needs replanning`;
}
}
});
const replanTool = createTool({
name: 'replan',
description: 'Add recovery steps after a failure',
parameters: {
type: 'object',
properties: {
recoverySteps: { type: 'array', items: { type: 'string' } }
},
required: ['recoverySteps']
},
execute: async ({ recoverySteps }) => {
if (!currentPlan) return 'No plan exists';
recoverySteps.forEach((s: string) => {
currentPlan!.addStep(new PlanStep({ description: s }));
});
return `Added ${recoverySteps.length} recovery steps`;
}
});
const adaptiveAgent = new Agent({
name: 'Adaptive Planner',
instructions: `You create and execute plans adaptively.
- Create a plan first
- Execute steps one by one
- If a step fails, add recovery steps and continue
- Report final status`,
tools: [createPlanTool, executeStepTool, replanTool]
});
await adaptiveAgent.chat('Deploy the application to production');
Plan Progress Tracking
Copy
import { Agent, Plan, PlanStep } from 'praisonai';
const plan = new Plan({ name: 'Data Pipeline' });
plan.addStep(new PlanStep({ description: 'Extract data' }));
plan.addStep(new PlanStep({ description: 'Transform data' }));
plan.addStep(new PlanStep({ description: 'Load to warehouse' }));
plan.addStep(new PlanStep({ description: 'Validate results' }));
// Track progress
plan.steps[0].complete();
plan.steps[1].complete();
const progress = plan.getProgress();
console.log(`Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)`);
// Progress: 2/4 (50%)
Persistent Plans
Save and restore Agent plans:Copy
import { Agent, PlanStorage, Plan, TodoList } from 'praisonai';
const storage = new PlanStorage();
// Save Agent's plan
const plan = new Plan({ name: 'Long Running Task' });
plan.addStep(new PlanStep({ description: 'Step 1' }));
plan.addStep(new PlanStep({ description: 'Step 2' }));
storage.savePlan(plan);
// Later: restore and continue
const restored = storage.getPlan(plan.id);
const nextStep = restored.steps.find(s => s.status === 'pending');
// Agent continues from where it left off

