【从0到1构建一个ClaudeAgent】规划与协调-子Agent

【从0到1构建一个ClaudeAgent】规划与协调-子Agent子任务污染主对话上下文怎么办 因此这里主要展示了如何构建一个多智能体系统 在 原作者的 Python 代码 里 run subagent nbsp 函数就像一个 虫洞 把任务传送到一个新的平行宇宙 子线程 子上下文 去执行 执行完只带回结果 在 Java 中 我们通常通过创建新的类实例 来实现这种隔离 父 Agent 和子 Agent 拥有各自独立的 nbsp

大家好,我是讯享网,很高兴认识大家。这里提供最前沿的Ai技术和互联网信息。



子任务污染主对话上下文怎么办?

因此这里主要展示了如何构建一个多智能体系统

在 原作者的Python代码 里,run_subagent 函数就像一个“虫洞”,把任务传送到一个新的平行宇宙(子线程/子上下文)去执行,执行完只带回结果。

在 Java 中,我们通常通过创建新的类实例来实现这种隔离。父 Agent 和子 Agent 拥有各自独立的 messages 列表,互不干扰。

public class AgentWithSubAgents } // ... 省略相同的 ToolExecutor 接口和基础工具注册 // --- 2. 子 Agent 类 (核心隔离单元) --- public static class SubAgent List 
  
    
    
      > results = new ArrayList<>(); List 
     
       > content = (List 
      
        >) response.get("content"); for (Map 
       
         block : content) catch (Exception e) Map 
        
          result = new HashMap<>(); result.put("type", "tool_result"); result.put("tool_use_id", toolId); result.put("content", output); results.add(result); } } messages.add(Map.of("role", "user", "content", results)); } // 提取最终文本结果 return extractText(response); } } // --- 3. 父 Agent 核心循环 --- // 父 Agent 拥有所有工具,包括 TASK private final List 
         
           > parentTools = new ArrayList<>(); { // 复制基础工具 parentTools.addAll(Arrays.asList( createToolSpec("bash", "Run shell command", "command"), createToolSpec("read_file", "Read file", "path"), createToolSpec("write_file", "Write file", "path", "content"), createToolSpec("edit_file", "Edit file", "path", "old_text", "new_text") )); // 添加 TASK 工具 parentTools.add(createTaskToolSpec()); } // 创建任务工具规格 private static Map 
          
            createTaskToolSpec() { Map 
           
             spec = new HashMap<>(); spec.put("name", "task"); spec.put("description", "Spawn a subagent with fresh context."); Map 
            
              schema = new HashMap<>(); schema.put("type", "object"); Map 
             
               props = new HashMap<>(); props.put("prompt", Map.of("type", "string", "description", "The task for the subagent")); props.put("description", Map.of("type", "string", "description", "Short description")); schema.put("properties", props); schema.put("required", Arrays.asList("prompt")); spec.put("input_schema", schema); return spec; } public void agentLoop(List 
              
                > messages) else catch (Exception e) } System.out.println(" Result: " + output.substring(0, Math.min(output.length(), 100))); Map 
               
                 result = new HashMap<>(); result.put("type", "tool_result"); result.put("tool_use_id", toolId); result.put("content", output); results.add(result); } } messages.add(Map.of("role", "user", "content", results)); } } // --- 辅助方法 --- private static String extractText(Map 
                
                  response) return "(no summary)"; } } 
                 
                
               
              
             
            
           
          
         
        
       
      
    

核心思想:引入分层架构和上下文隔离,让Agent能够分解复杂任务,分配给专门的”子Agent”处理,避免上下文污染。

// 子 Agent 类 - 独立的执行单元 public static class SubAgent {

private final List 
  
    
    
      > messages = new ArrayList<>(); // 独立上下文 private static final String SYSTEM_PROMPT = "You are a coding subagent. Complete the task and summarize findings."; // 独立上下文:每个子任务有自己独立的消息历史 // 系统提示:为子任务定义专门的角色,如"编码专家" // 子 Agent 只能使用基础工具,不能递归创建子 Agent private final List 
     
       > allowedTools = Arrays.asList( createToolSpec("bash", "Run shell command", "command"), createToolSpec("read_file", "Read file", "path"), // 权限控制:限制工具集,防止无限递归 ); public String executeTask(String prompt) { messages.clear(); // 清空历史,从零开始 messages.add(Map.of("role", "user", "content", prompt)); // 每次调用都是全新的上下文,避免历史干扰 // 安全循环限制,防止死循环 for (int i = 0; i < 30; i++) { // 最多30轮 // ... 执行子任务 } } 
      
    

}

  • 上下文隔离:每个子任务在干净的环境中执行,不继承父任务的上下文污染
  • 角色专业化:可以通过不同的SYSTEM_PROMPT让子Agent专注特定领域
  • 防递归保护:子Agent不能调用task工具,防止无限递归
  • 资源限制:限制最大轮数,防止死循环

核心思想:将”委派子任务”抽象为一种工具,实现任务分解和并行化

// 父 Agent 的工具列表 private final List 
  
    
    
      > parentTools = new ArrayList<>(); { 
    

// 基础工具 parentTools.addAll(Arrays.asList( createToolSpec("bash", "Run shell command", "command"), // ... 其他基础工具 )); // 添加 TASK 工具 parentTools.add(createTaskToolSpec()); // 关键:父Agent独有的委派能力 

}

// 任务工具规格定义 private static Map createTaskToolSpec() {

Map 
  
    
    
      spec = new HashMap<>(); spec.put("name", "task"); spec.put("description", "Spawn a subagent with fresh context."); // 工具描述:明确这是创建子Agent的委派工具 Map 
     
       schema = new HashMap<>(); schema.put("type", "object"); Map 
      
        props = new HashMap<>(); props.put("prompt", Map.of("type", "string", "description", "The task for the subagent")); props.put("description", Map.of("type", "string", "description", "Short description")); schema.put("properties", props); schema.put("required", Arrays.asList("prompt")); spec.put("input_schema", schema); // 工具规格:定义输入参数 return spec; 
       
      
    

}

  • 委派抽象:将”让子Agent做某事”封装为一个工具调用
  • 权限控制:只有父Agent有这个工具,子Agent没有
  • 接口设计:明确的任务描述接口,便于LLM使用

// 父 Agent 的核心循环 public void agentLoop(List 
  
    
    
      > messages) else 
    

 // 将子Agent的结果返回给父Agent result.put("content", output); } } } 

}

  • 主从模式:父Agent是管理者,子Agent是工作者
  • 结果聚合:子Agent返回结果,父Agent继续处理
  • 上下文切换:子任务执行时,父Agent暂停等待
  • 可重用子Agent:一个子Agent实例可处理多个任务

从 AgentWithTodo 到 AgentWithSubAgents 的升级

维度 AgentWithTodo AgentWithSubAgents 架构模式 单例模式 分层模式(父子) 上下文管理 共享上下文 上下文隔离 任务处理 线性顺序 并行/委派 复杂性 状态管理 分治策略 可扩展性 有限 强大

小讯
上一篇 2026-04-14 23:53
下一篇 2026-04-14 23:51

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/258316.html