计划模式指南
计划模式是 ByteBuddy 的高级功能,允许 AI 在执行任务前先制定详细的执行计划,然后逐步实施,提高复杂任务的完成质量和可靠性。
什么是计划模式?
核心概念
计划模式将复杂的任务分解为多个步骤:
- 任务理解: 深入理解用户的需求和目标
- 计划制定: 创建详细的执行计划
- 计划确认: 与用户确认计划细节
- 分步执行: 按计划逐步实施
- 进度监控: 实时监控执行进度
- 结果验证: 验证每个步骤的结果
优势
- 更高质量: 通过计划确保考虑全面
- 减少错误: 分步执行降低出错概率
- 可控性: 用户可以随时干预和调整
- 可追溯: 每个步骤都有明确的记录
- 学习能力: 可以从成功和失败中学习
启用和配置计划模式
基础配置
json
{
"planMode": {
"enabled": true,
"autoTrigger": false,
"complexTasks": true,
"multiFileTasks": true
}
}高级配置
json
{
"planMode": {
"strategies": {
"taskDecomposition": {
"enabled": true,
"maxSteps": 20,
"stepGranularity": "fine"
},
"planning": {
"model": "gpt-4",
"temperature": 0.3,
"considerAlternatives": true,
"riskAssessment": true
},
"execution": {
"autoConfirm": false,
"checkpointInterval": 3,
"rollbackOnError": true
}
}
}
}计划制定过程
任务分析
yaml
task_analysis:
input: "创建一个完整的用户管理系统"
understanding:
goal: "实现用户注册、登录、权限管理功能"
scope: "Web应用,包含前端和后端"
constraints:
- "使用React前端"
- "使用Node.js后端"
- "数据库使用MongoDB"
- "需要JWT认证"
requirements:
functional:
- "用户注册"
- "用户登录"
- "密码重置"
- "角色权限管理"
- "用户资料管理"
non_functional:
- "响应时间 < 200ms"
- "安全性:防止常见攻击"
- "可扩展性:支持10万用户"
- "可用性:99.9%"计划生成
yaml
execution_plan:
title: "用户管理系统开发计划"
estimated_time: "4-6小时"
difficulty: "中级"
phases:
- phase: "项目初始化"
steps:
- "创建项目目录结构"
- "初始化前端项目 (Create React App)"
- "初始化后端项目 (Express.js)"
- "配置开发环境"
- "设置Git仓库"
- phase: "数据库设计"
steps:
- "设计用户数据模型"
- "创建MongoDB集合结构"
- "设置数据库连接"
- "创建基础CRUD操作"
- phase: "后端API开发"
steps:
- "实现用户注册API"
- "实现用户登录API"
- "实现JWT中间件"
- "实现权限验证"
- "实现密码重置功能"
- phase: "前端开发"
steps:
- "创建路由结构"
- "开发登录组件"
- "开发注册组件"
- "开发用户管理界面"
- "实现API集成"
- phase: "测试和优化"
steps:
- "编写单元测试"
- "编写集成测试"
- "性能优化"
- "安全性测试"
- "部署准备"计划执行
分步执行示例
javascript
// 步骤1: 创建项目目录结构
const executeStep1 = async () => {
const directories = [
"user-management",
"user-management/frontend",
"user-management/backend",
"user-management/docs",
];
for (const dir of directories) {
await fs.mkdir(dir, { recursive: true });
console.log(`✓ 创建目录: ${dir}`);
}
};
// 步骤2: 初始化前端项目
const executeStep2 = async () => {
await exec(
"cd user-management/frontend && npx create-react-app . --template typescript",
);
console.log("✓ 前端项目初始化完成");
};
// 每个步骤都有对应的执行函数进度监控
typescript
interface PlanExecution {
planId: string;
currentPhase: number;
currentStep: number;
totalPhases: number;
totalSteps: number;
startTime: Date;
estimatedEndTime: Date;
status: "running" | "paused" | "completed" | "failed";
checkpoints: Checkpoint[];
}
class PlanExecutor {
async executePlan(plan: ExecutionPlan): Promise<PlanExecution> {
const execution = new PlanExecution(plan);
for (let i = 0; i < plan.phases.length; i++) {
const phase = plan.phases[i];
await this.executePhase(phase, execution);
}
return execution;
}
private async executePhase(phase: Phase, execution: PlanExecution) {
for (let i = 0; i < phase.steps.length; i++) {
const step = phase.steps[i];
await this.executeStep(step, execution);
await this.createCheckpoint(execution);
}
}
}计划模式功能
智能规划
json
{
"planning": {
"autoPlanning": true,
"templateMatching": true,
"riskAnalysis": true,
"alternativeSolutions": true
}
}计划模板
json
{
"templates": [
{
"name": "React应用开发",
"phases": [
{
"name": "项目初始化",
"steps": ["创建项目结构", "初始化React项目", "配置开发环境"]
},
{
"name": "组件开发",
"steps": ["设计组件架构", "开发基础组件", "开发页面组件"]
}
]
},
{
"name": "API服务开发",
"phases": [
{
"name": "项目设置",
"steps": ["初始化Node.js项目", "配置Express.js", "设置数据库连接"]
}
]
}
]
}动态调整
typescript
class DynamicPlanner {
async adjustPlan(
currentPlan: ExecutionPlan,
feedback: UserFeedback,
context: ExecutionContext,
): Promise<ExecutionPlan> {
// 分析反馈
const analysis = await this.analyzeFeedback(feedback);
// 识别需要的调整
const adjustments = this.identifyAdjustments(analysis, context);
// 应用调整
const adjustedPlan = await this.applyAdjustments(currentPlan, adjustments);
return adjustedPlan;
}
}用户交互
计划确认界面
typescript
interface PlanConfirmation {
plan: ExecutionPlan;
options: {
allowModifications: boolean;
showEstimates: boolean;
enableCheckpoints: boolean;
};
actions: {
approve: () => Promise<void>;
modify: (modifications: PlanModification[]) => Promise<void>;
reject: (reason: string) => Promise<void>;
};
}
// 示例使用
const confirmation = new PlanConfirmation(plan, {
allowModifications: true,
showEstimates: true,
enableCheckpoints: true,
});
// 用户批准计划
await confirmation.approve();
// 用户修改计划
await confirmation.modify([
{
type: "add_step",
phase: 2,
step: { name: "添加单元测试", estimatedTime: 30 },
},
]);进度追踪
typescript
interface ProgressTracker {
currentStep: number;
totalSteps: number;
phase: string;
estimatedTimeRemaining: number;
completedSteps: string[];
errors: Error[];
}
class PlanProgressTracker {
updateProgress(step: string, status: "completed" | "failed" | "running") {
// 更新进度状态
// 通知用户
// 记录日志
}
getProgressReport(): ProgressReport {
return {
completionPercentage: this.calculateCompletion(),
timeSpent: this.getTimeSpent(),
estimatedCompletion: this.estimateCompletion(),
nextSteps: this.getNextSteps(),
};
}
}错误处理和恢复
错误处理策略
typescript
class ErrorHandler {
async handleError(
error: Error,
step: Step,
context: ExecutionContext,
): Promise<ErrorResolution> {
// 错误分类
const errorType = this.classifyError(error);
// 尝试自动恢复
if (errorType === "retriable") {
return await this.autoRecover(step, context);
}
// 请求用户干预
if (errorType === "user_intervention_required") {
return await this.requestUserIntervention(error, step);
}
// 回滚操作
if (errorType === "critical") {
return await this.rollback(step, context);
}
}
private async autoRecover(step: Step, context: ExecutionContext) {
const retryCount = context.retryCount || 0;
if (retryCount < 3) {
context.retryCount = retryCount + 1;
return await this.executeStep(step, context);
}
throw new Error(`步骤 ${step.name} 在 ${retryCount} 次重试后仍然失败`);
}
}回滚机制
typescript
class RollbackManager {
async rollback(failedStep: Step, execution: PlanExecution): Promise<void> {
// 识别需要回滚的步骤
const stepsToRollback = this.identifyRollbackSteps(failedStep, execution);
// 按相反顺序回滚
for (const step of stepsToRollback.reverse()) {
await this.rollbackStep(step);
}
// 清理资源
await this.cleanup(execution);
}
private async rollbackStep(step: Step) {
switch (step.type) {
case "file_creation":
await this.deleteFiles(step.createdFiles);
break;
case "dependency_installation":
await this.uninstallDependencies(step.dependencies);
break;
case "configuration_change":
await this.restoreConfiguration(step.configBackup);
break;
}
}
}性能优化
并行执行
typescript
class ParallelExecutor {
async executeParallelSteps(steps: Step[]): Promise<void> {
// 分析步骤依赖关系
const dependencyGraph = this.buildDependencyGraph(steps);
// 识别可并行执行的步骤组
const parallelGroups = this.identifyParallelGroups(dependencyGraph);
// 并行执行每个组
for (const group of parallelGroups) {
await Promise.all(group.map((step) => this.executeStep(step)));
}
}
}缓存机制
typescript
class PlanCache {
async getCachedPlan(request: PlanRequest): Promise<ExecutionPlan | null> {
const cacheKey = this.generateCacheKey(request);
const cached = await this.cache.get(cacheKey);
if (cached && !this.isExpired(cached)) {
return cached.plan;
}
return null;
}
async cachePlan(request: PlanRequest, plan: ExecutionPlan) {
const cacheKey = this.generateCacheKey(request);
await this.cache.set(cacheKey, {
plan,
timestamp: Date.now(),
ttl: 3600000, // 1小时
});
}
}最佳实践
规划最佳实践
- 明确目标: 确保充分理解用户需求
- 合理分解: 将复杂任务分解为可管理的步骤
- 考虑风险: 识别潜在风险并制定应对策略
- 设置里程碑: 在关键点设置检查点
- 预留缓冲: 为意外情况预留时间
执行最佳实践
- 逐步确认: 在每个关键步骤后确认
- 持续监控: 实时监控执行进度
- 及时调整: 根据实际情况调整计划
- 详细记录: 记录每个步骤的详细信息
- 用户反馈: 积极收集和处理用户反馈
错误处理最佳实践
- 预防为主: 在计划阶段识别潜在问题
- 快速恢复: 实现快速的错误恢复机制
- 详细日志: 记录详细的错误信息
- 用户友好: 提供用户友好的错误提示
- 学习改进: 从错误中学习并改进计划
通过使用计划模式,您可以更可靠地完成复杂任务,提高工作质量和效率。计划模式特别适合软件开发、系统配置、文档编写等需要多步骤完成的工作。