Agent Planning
Planning enables Agents to break down complex tasks into manageable steps. Agents can create plans, track progress, and adapt as they work through tasks.Agent with Planning
Copy
import { Agent, Plan, PlanStep, createTool } from 'praisonai';
// Tool to create a plan
const createPlanTool = createTool({
name: 'create_plan',
description: 'Create a step-by-step plan for a task',
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Plan name' },
steps: { type: 'array', items: { type: 'string' }, description: 'List of steps' }
},
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`;
}
});
// Tool to execute a step
const executeStepTool = createTool({
name: 'execute_step',
description: 'Execute and complete a plan step',
parameters: {
type: 'object',
properties: {
stepDescription: { type: 'string', description: 'Step to execute' }
},
required: ['stepDescription']
},
execute: async ({ stepDescription }) => {
// Agent executes the step
return `Completed: ${stepDescription}`;
}
});
const planningAgent = new Agent({
name: 'Planning Agent',
instructions: `You break down complex tasks into plans and execute them step by step.
1. First, create a plan using create_plan
2. Then execute each step using execute_step
3. Report progress after each step`,
tools: [createPlanTool, executeStepTool]
});
await planningAgent.chat('Build a simple web scraper');
// Agent creates plan: 1. Setup project 2. Install dependencies 3. Write scraper 4. Test
// Agent executes each step in order
Multi-Agent Planning
Agents collaborate on a shared plan:Copy
import { Agent, Plan, PlanStep, PraisonAIAgents } 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

