Skip to content

Latest commit

 

History

History
483 lines (394 loc) · 14.1 KB

agent-react-optimization-design.md

File metadata and controls

483 lines (394 loc) · 14.1 KB

GameDevelopmentAgent ReAct循环优化设计文档

版本: 1.0 创建日期: 2025-09-16 最后更新: 2025-09-16

📋 项目概述

本文档记录了将GameDevelopmentAgent从过度依赖意图识别的简化模式升级为真正的ReAct自主智能模式的完整设计方案。

🎯 优化目标

  1. 实现真正的ReAct循环:Think → Act → Observe → Reflect
  2. 减少对Pipeline意图识别的依赖:从强制依赖改为辅助参考
  3. 增强Agent自主决策能力:独立分析、策略选择、动态调整
  4. 实现多阶段Prompt交互:每个阶段专用的Prompt策略

🚨 当前架构问题分析

1. 过度依赖Pipeline意图识别

// 问题:Agent完全被动接受意图识别结果
🎯 已接收Pipeline意图识别: nodeCreation,置信度: 0.66
🔧 工具筛选完成,可用工具(1个): nodeCreation

2. 缺少真正的思考过程

  • 没有对用户需求的深度分析
  • 没有多种策略的对比思考
  • 没有执行风险的预判

3. Prompt信息不足

  • 系统提示词过于通用
  • 缺少上下文信息
  • 工具描述不够详细

🏗️ 新架构设计

核心ReAct循环结构

interface ReActContext {
  iterations: number;           // 当前迭代次数
  thoughts: ThoughtStep[];      // 思考历史
  actions: ActionStep[];        // 行动历史
  observations: Observation[]; // 观察结果
  reflections: Reflection[];   // 反思记录
  userContext: UserContext;    // 用户上下文
  projectState: ProjectState;  // 项目状态
}

interface ThoughtStep {
  iteration: number;
  timestamp: Date;
  analysis: string;           // 需求分析
  strategies: Strategy[];     // 可选策略
  selectedStrategy: Strategy; // 选择的策略
  reasoning: string;          // 选择理由
  riskAssessment: Risk[];    // 风险评估
}

interface ActionStep {
  iteration: number;
  timestamp: Date;
  toolName: string;
  parameters: Record<string, any>;
  intention: string;         // 行动意图
  expectedOutcome: string;   // 预期结果
}

interface Observation {
  iteration: number;
  timestamp: Date;
  success: boolean;
  result: any;
  qualityScore: number;      // 结果质量评分
  userSatisfactionPrediction: number; // 用户满意度预测
  issuesFound: string[];     // 发现的问题
  improvementSuggestions: string[]; // 改进建议
}

ReAct循环执行流程

class GameDevelopmentAgent extends BaseAgent {
  async executeWithReAct(
    userInput: string,
    context: ReActContext,
    pipelineIntent?: IntentResult // 作为参考,非强制依赖
  ): Promise<AgentResult> {

    let currentIteration = 0;
    const maxIterations = 5;

    while (currentIteration < maxIterations && !this.isGoalAchieved(context)) {
      // 🤔 THINK: 深度思考分析阶段
      const thought = await this.think(userInput, context, pipelineIntent, currentIteration);
      context.thoughts.push(thought);

      // 🎬 ACT: 执行行动阶段
      const action = await this.act(thought, context);
      context.actions.push(action);

      // 👁️ OBSERVE: 观察结果阶段
      const observation = await this.observe(action, context);
      context.observations.push(observation);

      // 🔄 REFLECT: 反思调整阶段
      if (!observation.success || observation.qualityScore < 0.7) {
        const reflection = await this.reflect(context);
        context.reflections.push(reflection);

        if (reflection.shouldContinue) {
          currentIteration++;
          continue;
        }
      }

      if (observation.success && observation.qualityScore >= 0.8) {
        break;
      }

      currentIteration++;
    }

    return this.synthesizeResult(context);
  }
}

🔄 多阶段Prompt交互模式

架构对比

AIKernel普通模式(二段式)

🧠 LLM调用1: 分析意图 → 返回intent + tools
🔧 构建tools schema → LLM调用2: 生成function call → 执行工具
📝 LLM调用3: 基于结果总结 → 返回最终回复

Agent ReAct模式(多阶段式)

🤔 LLM调用1: 深度分析 → 返回策略选择
🎬 子阶段1: 确定工具选择 → 构建tool schema
🎬 子阶段2: LLM调用2: 生成精确参数 → 执行工具
👁️ LLM调用3: 分析执行结果 → 返回质量评估
🔄 LLM调用4: 反思总结 → 返回改进建议

多阶段Prompt管理器

enum ReActStage {
  THINK = 'think',
  ACT_PLAN = 'act_plan',
  ACT_EXECUTE = 'act_execute',
  OBSERVE = 'observe',
  REFLECT = 'reflect'
}

interface StagePromptConfig {
  stage: ReActStage;
  iteration: number;
  userInput: string;
  context: ReActContext;
  stageSpecificData?: any;
}

class ReActPromptManager {
  static buildStagePrompt(config: StagePromptConfig): string {
    const basePrompt = this.getStageBasePrompt(config.stage);
    const contextPrompt = this.formatContextForStage(config.context, config.stage);
    const stagePrompt = this.getStageSpecificPrompt(config);

    return `${basePrompt}\n\n${contextPrompt}\n\n${stagePrompt}`;
  }
}

🤔 Think阶段:纯思维分析

思考阶段特点

  • 纯思维分析:不考虑具体工具,专注理解和策略
  • 多策略对比:列出多种可行方案并分析优缺点
  • 风险预判:提前识别可能的挑战和应对方案

Think阶段Prompt模板

private static buildThinkingPrompt(config: StagePromptConfig): string {
  return `
# 🧠 ReAct思考阶段 - 第${config.iteration + 1}轮深度分析

## 当前任务
${config.userInput}

## 思考要求
请进行深度思考分析,**不要考虑具体的工具使用**:

### 1. 需求理解
- 用户的真实意图是什么?
- 隐含的需求有哪些?
- 任务的复杂程度如何?

### 2. 策略规划
- 有哪些可行的解决策略?
- 每种策略的优缺点分析
- 推荐哪种策略?为什么?

### 3. 成功标准
- 什么样的结果算是成功?
- 用户可能的满意度标准

### 4. 潜在挑战
- 可能遇到什么困难?
- 如何预防和应对?

## 输出要求
{
  "understanding": {
    "mainIntent": "主要意图",
    "hiddenNeeds": ["隐含需求1", "隐含需求2"],
    "complexity": "low|medium|high"
  },
  "strategies": [
    {
      "name": "策略名称",
      "description": "详细描述",
      "pros": ["优点1", "优点2"],
      "cons": ["缺点1"],
      "successProbability": 0.8
    }
  ],
  "recommendedStrategy": "推荐的策略名称",
  "reasoning": "推荐理由",
  "successCriteria": ["成功标准1", "成功标准2"],
  "potentialChallenges": [
    {
      "challenge": "挑战描述",
      "mitigation": "应对方案"
    }
  ]
}
`;
}

🎬 Act阶段:二段式工具执行

Act Stage 1: 工具规划

  • 策略转化:将思考阶段的策略转化为具体工具选择
  • 工具对比:分析各工具的适用性
  • 参数规划:制定详细的参数设置计划

Act Stage 2: 精确执行

  • Function Calling:使用工具schema生成精确参数
  • 参数验证:确保参数完全符合工具要求
  • 执行监控:跟踪执行过程和结果
async executeActStage(thought: ThoughtStep, context: ReActContext): Promise<ActionStep> {
  // Stage 1: 工具规划
  const planPrompt = ReActPromptManager.buildStagePrompt({
    stage: ReActStage.ACT_PLAN,
    iteration: context.iterations,
    userInput: context.originalInput,
    context,
    stageSpecificData: thought
  });

  const planResponse = await this.llmProvider.generateResponse({
    messages: [{ role: 'user', content: planPrompt }]
  });
  const executionPlan = JSON.parse(planResponse.content);

  // Stage 2: 精确执行
  const executePrompt = ReActPromptManager.buildStagePrompt({
    stage: ReActStage.ACT_EXECUTE,
    iteration: context.iterations,
    userInput: context.originalInput,
    context,
    stageSpecificData: executionPlan
  });

  const tools = [this.getToolSchema(executionPlan.selectedTool)];
  const executeResponse = await this.llmProvider.generateResponse({
    messages: [{ role: 'user', content: executePrompt }],
    tools: tools,
    tool_choice: { "type": "function", "function": { "name": executionPlan.selectedTool } }
  });

  // 执行工具调用
  const toolCall = executeResponse.tool_calls[0];
  const toolResult = await this.toolRegistry.executeTool(
    toolCall.function.name,
    JSON.parse(toolCall.function.arguments)
  );

  return {
    iteration: context.iterations,
    timestamp: new Date(),
    toolName: toolCall.function.name,
    parameters: JSON.parse(toolCall.function.arguments),
    executionPlan,
    result: toolResult,
    intention: executionPlan.selectionReason,
    expectedOutcome: executionPlan.expectedOutcome
  };
}

👁️ Observe阶段:结果质量评估

观察评估维度

  1. 执行成功性:工具是否正确执行
  2. 结果质量:生成内容的质量评分
  3. 用户满意度预测:预测用户对结果的满意度
  4. 问题识别:发现潜在问题和改进点

质量评估示例

👁️ [质量检查] 角色是否包含完整的背景故事? ✅
👁️ [质量检查] 性格特点是否具体且有趣? ✅
👁️ [质量检查] 动机是否合理且有深度? ✅
👁️ [质量检查] 是否适合游戏场景使用? ✅
👁️ [综合评分] 0.85/1.0 - 高质量结果

👁️ [满意度] 创意性: 高 - 独特的灵体角色设定
👁️ [满意度] 完整性: 高 - 包含所有要求的元素
👁️ [满意度] 可用性: 高 - 可直接用于游戏开发
👁️ [预测满意度] 0.88/1.0 - 用户很可能满意

🔄 Reflect阶段:深度反思

反思分析内容

  1. 成功因素分析:什么地方做得好?
  2. 问题根因分析:问题的根本原因是什么?
  3. 策略优化:下次如何改进?
  4. 持续改进:是否需要继续优化?

反思驱动的持续改进

🔄 [AGENT-REFLECT] 成功原因: 准确理解了用户对"深度角色"的需求
🔄 [AGENT-REFLECT] 经验总结: 角色创建需要平衡神秘感和具体细节
🔄 [AGENT-REFLECT] 下次改进: 可以询问用户偏好的角色类型和背景设定

🎯 PromptBuilder优化方案

1. Agent专属系统提示词

interface AgentPromptConfig {
  agentType: 'GameDevelopmentAgent' | 'GeneralAgent';
  capabilities: string[];
  context: AgentContext;
  behaviorInstructions: string;
  thinkingStyle: 'creative' | 'analytical' | 'practical';
  interactionMode: 'autonomous' | 'collaborative' | 'guided';
}

class PromptBuilder {
  static buildAgentSystemPrompt(config: AgentPromptConfig): string {
    const basePrompt = this.getAgentBasePrompt(config.agentType);
    const capabilityPrompt = this.buildCapabilityPrompt(config.capabilities);
    const contextPrompt = this.buildContextPrompt(config.context);
    const behaviorPrompt = this.buildBehaviorPrompt(config.behaviorInstructions);
    const thinkingPrompt = this.buildThinkingStylePrompt(config.thinkingStyle);

    return `${basePrompt}\n\n${capabilityPrompt}\n\n${contextPrompt}\n\n${behaviorPrompt}\n\n${thinkingPrompt}`;
  }
}

2. 上下文信息增强

interface AgentContext {
  // 项目状态
  projectInfo: {
    name: string;
    type: 'AVG' | 'RPG' | 'Action';
    stage: 'prototype' | 'development' | 'testing';
    existingFiles: string[];
    recentChanges: string[];
  };

  // 用户偏好
  userPreferences: {
    style: 'realistic' | 'fantasy' | 'modern';
    complexity: 'simple' | 'moderate' | 'complex';
    interactionStyle: 'guided' | 'autonomous';
  };

  // 会话历史
  conversationHistory: {
    recentRequests: string[];
    successfulActions: string[];
    failedActions: string[];
    userFeedback: string[];
  };

  // 系统状态
  systemState: {
    availableTools: string[];
    resourceUsage: number;
    performanceMetrics: Record<string, number>;
  };
}

🚀 实现路径和优先级

Phase 1: 核心ReAct循环 (高优先级)

  1. ✅ 实现ThoughtStep、ActionStep、Observation数据结构
  2. ✅ 实现基础的think-act-observe-reflect循环
  3. ✅ 集成到GameDevelopmentAgent中

Phase 2: 思考能力增强 (高优先级)

  1. ✅ 实现深度需求分析逻辑
  2. ✅ 实现多策略对比思考
  3. ✅ 实现智能工具选择机制

Phase 3: PromptBuilder优化 (中优先级)

  1. ✅ 添加Agent专属系统提示词支持
  2. ✅ 实现ReAct思考专用Prompt模板
  3. ✅ 增强上下文信息传递

Phase 4: 观察和反思增强 (中优先级)

  1. ✅ 实现结果质量评估机制
  2. ✅ 实现用户满意度预测
  3. ✅ 实现智能反思和改进建议

Phase 5: 交互能力增强 (低优先级)

  1. 🔄 实现Agent主动询问机制
  2. 🔄 实现多轮对话状态管理
  3. 🔄 实现用户偏好学习

📊 成功指标

定量指标

  • ReAct循环完成率 > 95%
  • 思考质量评分 > 0.8
  • 用户满意度预测准确率 > 80%
  • 工具选择正确率 > 90%

定性指标

  • Agent能独立分析复杂需求
  • Agent能提供多样化的解决方案
  • Agent能从失败中学习并改进
  • Agent的响应更加人性化和智能化

📈 优势对比

特性 AIKernel普通模式 Agent ReAct模式
思考深度 简单意图识别 深度策略分析
工具选择 基于意图映射 智能对比选择
参数生成 一次性生成 规划+精确生成
结果评估 简单总结 多维度质量评估
错误处理 基础重试 反思改进循环
上下文利用 有限 全程上下文跟踪
学习能力 无 每轮反思学习

🎉 结论

这个优化方案将彻底改变GameDevelopmentAgent的执行模式,从简单的工具映射转变为真正的智能化ReAct循环,大幅提升Agent的自主性和智能化程度。

通过多阶段的Prompt交互模式,Agent将具备:

  • 深度思考和策略分析能力
  • 智能化的工具选择和参数生成
  • 全面的结果质量评估
  • 持续的学习和改进能力

这将使Agent真正成为用户的智能助手,而不仅仅是工具的执行器。


文档状态: 设计完成,待实现 下一步: 开始Phase 1的核心ReAct循环实现