【从0到1构建一个ClaudeAgent】协作-Agent团队 [复制链接]
发表于 2026-4-17 08:41:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一个 Agent 干不完怎么办?
Java实今世码
  1. public class AgentTeamsSystem {
  2.     // --- 配置 ---
  3.     private static final Path WORKDIR = Paths.get(System.getProperty("user.dir"));
  4.     private static final Path TEAM_DIR = WORKDIR.resolve(".team");
  5.     private static final Path INBOX_DIR = TEAM_DIR.resolve("inbox");
  6.     private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
  7.    
  8.     // 有效消息类型
  9.     private static final Set<String> VALID_MSG_TYPES = Set.of(
  10.         "message", "broadcast", "shutdown_request",
  11.         "shutdown_response", "plan_approval_response"
  12.     );
  13.    
  14.     // --- 消息系统(MessageBus)---
  15.     static class MessageBus {
  16.         private final Path inboxDir;
  17.         
  18.         public MessageBus(Path inboxDir) {
  19.             this.inboxDir = inboxDir;
  20.             try {
  21.                 Files.createDirectories(inboxDir);
  22.             } catch (IOException e) {
  23.                 throw new RuntimeException("Failed to create inbox directory", e);
  24.             }
  25.         }
  26.         
  27.         /**
  28.          * 发送消息到指定智能体
  29.          */
  30.         public String send(String sender, String to, String content,
  31.                           String msgType, Map<String, Object> extra) {
  32.             if (!VALID_MSG_TYPES.contains(msgType)) {
  33.                 return String.format("Error: Invalid type '%s'. Valid: %s",
  34.                     msgType, String.join(", ", VALID_MSG_TYPES));
  35.             }
  36.             
  37.             Map<String, Object> message = new LinkedHashMap<>();
  38.             message.put("type", msgType);
  39.             message.put("from", sender);
  40.             message.put("content", content);
  41.             message.put("timestamp", System.currentTimeMillis() / 1000.0);
  42.             
  43.             if (extra != null) {
  44.                 message.putAll(extra);
  45.             }
  46.             
  47.             Path inboxPath = inboxDir.resolve(to + ".jsonl");
  48.             try {
  49.                 String jsonLine = gson.toJson(message) + "\n";
  50.                 Files.writeString(inboxPath, jsonLine,
  51.                     StandardOpenOption.CREATE, StandardOpenOption.APPEND);
  52.                
  53.                 return String.format("Sent %s to %s", msgType, to);
  54.             } catch (IOException e) {
  55.                 return "Error: " + e.getMessage();
  56.             }
  57.         }
  58.         
  59.         /**
  60.          * 读取并清空邮箱
  61.          */
  62.         public List<Map<String, Object>> readInbox(String name) {
  63.             Path inboxPath = inboxDir.resolve(name + ".jsonl");
  64.             if (!Files.exists(inboxPath)) {
  65.                 return new ArrayList<>();
  66.             }
  67.             
  68.             try {
  69.                 List<Map<String, Object>> messages = new ArrayList<>();
  70.                 List<String> lines = Files.readAllLines(inboxPath);
  71.                
  72.                 for (String line : lines) {
  73.                     if (!line.trim().isEmpty()) {
  74.                         Type type = new TypeToken<Map<String, Object>>(){}.getType();
  75.                         Map<String, Object> message = gson.fromJson(line, type);
  76.                         messages.add(message);
  77.                     }
  78.                 }
  79.                
  80.                 // 清空邮箱(消费模式)
  81.                 Files.writeString(inboxPath, "");
  82.                
  83.                 return messages;
  84.             } catch (IOException e) {
  85.                 return new ArrayList<>();
  86.             }
  87.         }
  88.         
  89.         /**
  90.          * 广播消息到所有队友
  91.          */
  92.         public String broadcast(String sender, String content, List<String> teammates) {
  93.             int count = 0;
  94.             for (String name : teammates) {
  95.                 if (!name.equals(sender)) {
  96.                     send(sender, name, content, "broadcast");
  97.                     count++;
  98.                 }
  99.             }
  100.             return String.format("Broadcast to %d teammates", count);
  101.         }
  102.     }
  103.    
  104.     // 初始化消息总线
  105.     private static final MessageBus BUS = new MessageBus(INBOX_DIR);
  106.    
  107.     // --- 智能体管理器(TeammateManager)---
  108.     static class TeammateManager {
  109.         private final Path teamDir;
  110.         private final Path configPath;
  111.         private Map<String, Object> config;
  112.         private final Map<String, Thread> threads = new ConcurrentHashMap<>();
  113.         private final Map<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
  114.         
  115.         public TeammateManager(Path teamDir) {
  116.             this.teamDir = teamDir;
  117.             this.configPath = teamDir.resolve("config.json");
  118.             loadConfig();
  119.         }
  120.         
  121.         @SuppressWarnings("unchecked")
  122.         private void loadConfig() {
  123.             try {
  124.                 if (Files.exists(configPath)) {
  125.                     String content = Files.readString(configPath);
  126.                     Type type = new TypeToken<Map<String, Object>>(){}.getType();
  127.                     this.config = gson.fromJson(content, type);
  128.                 } else {
  129.                     this.config = new HashMap<>();
  130.                     config.put("team_name", "default");
  131.                     config.put("members", new ArrayList<Map<String, Object>>());
  132.                     saveConfig();
  133.                 }
  134.             } catch (IOException e) {
  135.                 throw new RuntimeException("Failed to load team config", e);
  136.             }
  137.         }
  138.         
  139.         @SuppressWarnings("unchecked")
  140.         public String spawn(String name, String role, String prompt) {
  141.             Map<String, Object> member = findMember(name);
  142.             
  143.             if (member != null) {
  144.                 String status = (String) member.get("status");
  145.                 if (!"idle".equals(status) && !"shutdown".equals(status)) {
  146.                     return String.format("Error: '%s' is currently %s", name, status);
  147.                 }
  148.                 member.put("status", "working");
  149.                 member.put("role", role);
  150.             } else {
  151.                 member = new LinkedHashMap<>();
  152.                 member.put("name", name);
  153.                 member.put("role", role);
  154.                 member.put("status", "working");
  155.                 ((List<Map<String, Object>>) config.get("members")).add(member);
  156.             }
  157.             
  158.             saveConfig();
  159.             
  160.             // 停止之前的线程(如果存在)
  161.             if (threads.containsKey(name)) {
  162.                 stopFlags.get(name).set(true);
  163.                 try {
  164.                     threads.get(name).join(1000);
  165.                 } catch (InterruptedException e) {
  166.                     Thread.currentThread().interrupt();
  167.                 }
  168.             }
  169.             
  170.             // 创建新的停止标志
  171.             AtomicBoolean stopFlag = new AtomicBoolean(false);
  172.             stopFlags.put(name, stopFlag);
  173.             
  174.             // 创建并启动新线程
  175.             Thread thread = new Thread(() -> teammateLoop(name, role, prompt, stopFlag),
  176.                                      "Teammate-" + name);
  177.             thread.setDaemon(true);
  178.             threads.put(name, thread);
  179.             thread.start();
  180.             
  181.             return String.format("Spawned '%s' (role: %s)", name, role);
  182.         }
  183.         
  184.         private void teammateLoop(String name, String role, String prompt, AtomicBoolean stopFlag) {
  185.             String systemPrompt = String.format(
  186.                 "You are '%s', role: %s, at %s. " +
  187.                 "Use send_message to communicate. Complete your task.",
  188.                 name, role, WORKDIR
  189.             );
  190.             
  191.             List<Map<String, Object>> messages = new ArrayList<>();
  192.             messages.add(Map.of("role", "user", "content", prompt));
  193.             
  194.             // 最大迭代次数限制
  195.             for (int i = 0; i < 50 && !stopFlag.get(); i++) {
  196.                 try {
  197.                     // 检查邮箱
  198.                     List<Map<String, Object>> inbox = BUS.readInbox(name);
  199.                     for (Map<String, Object> msg : inbox) {
  200.                         messages.add(Map.of("role", "user", "content", gson.toJson(msg)));
  201.                     }
  202.                     
  203.                     // 模拟调用 LLM
  204.                     Map<String, Object> response = simulateTeammateLLMCall(systemPrompt, messages, name);
  205.                     
  206.                     if (response == null || "end_turn".equals(response.get("stop_reason"))) {
  207.                         break;
  208.                     }
  209.                     
  210.                     // ... 执行工具调用
  211.                     
  212.                     // 短暂休眠,避免 CPU 过度使用
  213.                     Thread.sleep(100);
  214.                     
  215.                 } catch (Exception e) {
  216.                     System.err.printf("[%s] Error: %s%n", name, e.getMessage());
  217.                     break;
  218.                 }
  219.             }
  220.             
  221.             // 更新状态
  222.             @SuppressWarnings("unchecked")
  223.             Map<String, Object> member = findMember(name);
  224.             if (member != null && !"shutdown".equals(member.get("status"))) {
  225.                 member.put("status", "idle");
  226.                 saveConfig();
  227.             }
  228.             
  229.             threads.remove(name);
  230.             stopFlags.remove(name);
  231.         }
  232.         
  233.         @SuppressWarnings("unchecked")
  234.         public String listAll() {
  235.             List<Map<String, Object>> members = (List<Map<String, Object>>) config.get("members");
  236.             if (members.isEmpty()) {
  237.                 return "No teammates.";
  238.             }
  239.             
  240.             StringBuilder sb = new StringBuilder();
  241.             sb.append("Team: ").append(config.get("team_name")).append("\n");
  242.             
  243.             for (Map<String, Object> member : members) {
  244.                 sb.append(String.format("  %s (%s): %s%n",
  245.                     member.get("name"),
  246.                     member.get("role"),
  247.                     member.get("status")
  248.                 ));
  249.             }
  250.             
  251.             return sb.toString().trim();
  252.         }
  253.         
  254.         @SuppressWarnings("unchecked")
  255.         public List<String> memberNames() {
  256.             List<Map<String, Object>> members = (List<Map<String, Object>>) config.get("members");
  257.             return members.stream()
  258.                 .map(m -> (String) m.get("name"))
  259.                 .collect(Collectors.toList());
  260.         }
  261.         
  262.         /**
  263.          * 获取活动成员数量
  264.          */
  265.         @SuppressWarnings("unchecked")
  266.         public int getActiveCount() {
  267.             List<Map<String, Object>> members = (List<Map<String, Object>>) config.get("members");
  268.             int count = 0;
  269.             for (Map<String, Object> member : members) {
  270.                 if ("working".equals(member.get("status"))) {
  271.                     count++;
  272.                 }
  273.             }
  274.             return count;
  275.         }
  276.     }
  277.    
  278.     // 初始化智能体管理器
  279.     private static final TeammateManager TEAM_MANAGER = new TeammateManager(TEAM_DIR);
  280.    
  281.     // --- 工具枚举 ---
  282.     public enum ToolType {
  283.         BASH("bash", "Run a shell command."),
  284.         READ_FILE("read_file", "Read file contents."),
  285.         WRITE_FILE("write_file", "Write content to file."),
  286.         EDIT_FILE("edit_file", "Replace exact text in file."),
  287.         SPAWN_TEAMMATE("spawn_teammate", "Spawn a persistent teammate that runs in its own thread."),  // 新增
  288.         LIST_TEAMMATES("list_teammates", "List all teammates with name, role, status."),  // 新增
  289.         SEND_MESSAGE("send_message", "Send a message to a teammate's inbox."),  // 新增
  290.         READ_INBOX("read_inbox", "Read and drain the lead's inbox."),  // 新增
  291.         BROADCAST("broadcast", "Send a message to all teammates.");  // 新增
  292.         public final String name;
  293.         public final String description;
  294.         ToolType(String name, String description) { this.name = name; this.description = description; }
  295.     }
  296.     // --- 工具处理器映射 ---
  297.     private static final Map<String, ToolExecutor> TOOL_HANDLERS = new HashMap<>();
  298.    
  299.     static {
  300.         // ... 省略基础工具注册
  301.         
  302.         // 团队管理工具
  303.         TOOL_HANDLERS.put(ToolType.SPAWN_TEAMMATE.name, args -> {
  304.             String name = (String) args.get("name");
  305.             String role = (String) args.get("role");
  306.             String prompt = (String) args.get("prompt");
  307.             return TEAM_MANAGER.spawn(name, role, prompt);
  308.         });
  309.         
  310.         TOOL_HANDLERS.put(ToolType.LIST_TEAMMATES.name, args -> {
  311.             return TEAM_MANAGER.listAll();
  312.         });
  313.         
  314.         TOOL_HANDLERS.put(ToolType.SEND_MESSAGE.name, args -> {
  315.             String to = (String) args.get("to");
  316.             String content = (String) args.get("content");
  317.             String msgType = (String) args.get("msg_type");
  318.             if (msgType == null) msgType = "message";
  319.             return BUS.send("lead", to, content, msgType);
  320.         });
  321.         
  322.         TOOL_HANDLERS.put(ToolType.READ_INBOX.name, args -> {
  323.             List<Map<String, Object>> inbox = BUS.readInbox("lead");
  324.             return gson.toJson(inbox);
  325.         });
  326.         
  327.         TOOL_HANDLERS.put(ToolType.BROADCAST.name, args -> {
  328.             String content = (String) args.get("content");
  329.             return BUS.broadcast("lead", content, TEAM_MANAGER.memberNames());
  330.         });
  331.     }
  332.    
  333.     // --- Agent 主循环(领导智能体)---
  334.     public static void agentLoop(List<Map<String, Object>> messages) {
  335.         while (true) {
  336.             try {
  337.                 // 检查领导邮箱
  338.                 List<Map<String, Object>> inbox = BUS.readInbox("lead");
  339.                 if (!inbox.isEmpty()) {
  340.                     String inboxJson = gson.toJson(inbox);
  341.                     messages.add(Map.of(
  342.                         "role", "user",
  343.                         "content", "<inbox>" + inboxJson + "</inbox>"
  344.                     ));
  345.                     
  346.                     messages.add(Map.of(
  347.                         "role", "assistant",
  348.                         "content", "Noted inbox messages."
  349.                     ));
  350.                     // 邮箱自动注入:自动检查并注入收到的消息
  351.                     // 结构化格式:用XML标签包裹,便于LLM解析
  352.                 }
  353.                
  354.                 // 显示团队状态
  355.                 int activeCount = TEAM_MANAGER.getActiveCount();
  356.                 if (activeCount > 0) {
  357.                     System.out.printf("[Active teammates: %d]%n", activeCount);
  358.                 }
  359.                
  360.                 // ... 省略相同的 LLM 调用和工具执行逻辑
  361.                
  362.             } catch (Exception e) {
  363.                 System.err.println("Error in agent loop: " + e.getMessage());
  364.                 e.printStackTrace();
  365.                 return;
  366.             }
  367.         }
  368.     }
  369. }
复制代码
这段代码引入了智能体团队体系,实现了多个 Agent 之间的协作
焦点头脑:恒久队友 + 异步邮箱。
什么是恒久队友(Persistent Teammates)?它们是恒久存活、有身份意识的 Agent,通过基于文件的邮箱(JSONL 格式)异步通讯,可以大概处置惩罚超过单个实验周期的复杂使命委托。
多智能体体系架构

焦点头脑:从单智能体体系升级为多智能体协作体系,引入分布式、脚色化、可通讯的智能体团队,实现复杂的协同工作流和分布式题目办理
  1. // 系统配置
  2. private static final Path TEAM_DIR = WORKDIR.resolve(".team");
  3. private static final Path INBOX_DIR = TEAM_DIR.resolve("inbox");
  4. // 团队持久化:.team目录存储团队配置
  5. // 消息传递:inbox子目录实现智能体间通信
  6. // 文件系统基础:通过文件系统实现简单的分布式通信
复制代码

  • 多智能体协同:多个智能体可以并行工作,协同办理题目
  • 脚色化分工:差异智能体担当差异脚色,专业化分工
  • 恒久化团队:团队设置和状态可以恒久化生存
  • 去中央化通讯:基于文件体系的轻量级消息通报
消息总线体系(MessageBus)
  1. // 消息总线 - 智能体间通信基础设施
  2. static class MessageBus {
  3.     private final Path inboxDir;
  4.     // 文件系统邮箱:每个智能体一个jsonl文件
  5.     // 异步通信:发送方不阻塞,接收方主动拉取
  6.     // 松耦合:智能体间通过邮箱解耦
  7.    
  8.     /**
  9.      * 发送消息到指定智能体
  10.      */
  11.     public String send(String sender, String to, String content,
  12.                       String msgType, Map<String, Object> extra) {
  13.         if (!VALID_MSG_TYPES.contains(msgType)) {
  14.             return String.format("Error: Invalid type '%s'. Valid: %s",
  15.                 msgType, String.join(", ", VALID_MSG_TYPES));
  16.         }
  17.         // 消息类型验证:确保消息结构符合协议
  18.         
  19.         Map<String, Object> message = new LinkedHashMap<>();
  20.         message.put("type", msgType);
  21.         message.put("from", sender);
  22.         message.put("content", content);
  23.         message.put("timestamp", System.currentTimeMillis() / 1000.0);
  24.         // 结构化消息:类型、发送方、内容、时间戳
  25.         // 可扩展:支持额外字段
  26.         
  27.         Path inboxPath = inboxDir.resolve(to + ".jsonl");
  28.         try {
  29.             String jsonLine = gson.toJson(message) + "\n";
  30.             Files.writeString(inboxPath, jsonLine,
  31.                 StandardOpenOption.CREATE, StandardOpenOption.APPEND);
  32.             // 追加写入:支持多条消息
  33.             // JSONL格式:每行一个JSON对象,便于处理
  34.         }
  35.     }
  36.    
  37.     /**
  38.      * 读取并清空邮箱
  39.      */
  40.     public List<Map<String, Object>> readInbox(String name) {
  41.         Path inboxPath = inboxDir.resolve(name + ".jsonl");
  42.         if (!Files.exists(inboxPath)) {
  43.             return new ArrayList<>();
  44.         }
  45.         
  46.         try {
  47.             List<Map<String, Object>> messages = new ArrayList<>();
  48.             List<String> lines = Files.readAllLines(inboxPath);
  49.             
  50.             for (String line : lines) {
  51.                 if (!line.trim().isEmpty()) {
  52.                     Type type = new TypeToken<Map<String, Object>>(){}.getType();
  53.                     Map<String, Object> message = gson.fromJson(line, type);
  54.                     messages.add(message);
  55.                 }
  56.             }
  57.             
  58.             // 清空邮箱(消费模式)
  59.             Files.writeString(inboxPath, "");
  60.             // 消费一次:消息被读取后清空,避免重复处理
  61.             // 确保每个消息只被处理一次
  62.             
  63.             return messages;
  64.         }
  65.     }
  66. }
复制代码

  • 异步通讯:发送和吸取解耦,不壅闭发送方
  • 文件体系存储:简朴可靠,支持进程间通讯
  • 布局化消息:明白的消息格式,支持多种消息范例
  • 斲丧模式:读取后清空,克制消息重复处置惩罚
  • 可扩展协议:通过msgType支持差异的通讯语义
智能体管理器(TeammateManager)
  1. // 智能体管理器 - 多智能体生命周期管理
  2. static class TeammateManager {
  3.     private final Path teamDir;
  4.     private final Path configPath;
  5.     private Map<String, Object> config;
  6.     private final Map<String, Thread> threads = new ConcurrentHashMap<>();
  7.     private final Map<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
  8.     // 配置管理:团队配置持久化到文件
  9.     // 线程管理:每个智能体在自己的线程中运行
  10.     // 停止控制:支持优雅停止智能体
  11.    
  12.     public String spawn(String name, String role, String prompt) {
  13.         Map<String, Object> member = findMember(name);
  14.         
  15.         if (member != null) {
  16.             String status = (String) member.get("status");
  17.             if (!"idle".equals(status) && !"shutdown".equals(status)) {
  18.                 return String.format("Error: '%s' is currently %s", name, status);
  19.             }
  20.             member.put("status", "working");
  21.             member.put("role", role);
  22.         } else {
  23.             member = new LinkedHashMap<>();
  24.             member.put("name", name);
  25.             member.put("role", role);
  26.             member.put("status", "working");
  27.             ((List<Map<String, Object>>) config.get("members")).add(member);
  28.         }
  29.         // 状态管理:智能体有明确的状态机
  30.         // 重用支持:可以重用已有的智能体
  31.         // 角色配置:为智能体分配特定角色
  32.         
  33.         saveConfig();
  34.         
  35.         // 创建新的停止标志
  36.         AtomicBoolean stopFlag = new AtomicBoolean(false);
  37.         stopFlags.put(name, stopFlag);
  38.         
  39.         // 创建并启动新线程
  40.         Thread thread = new Thread(() -> teammateLoop(name, role, prompt, stopFlag),
  41.                                  "Teammate-" + name);
  42.         thread.setDaemon(true);
  43.         threads.put(name, thread);
  44.         thread.start();
  45.         // 独立线程:每个智能体在独立线程中运行
  46.         // 守护线程:不会阻止JVM退出
  47.         // 命名线程:便于调试和监控监控
  48.         
  49.         return String.format("Spawned '%s' (role: %s)", name, role);
  50.     }
  51.    
  52.     private void teammateLoop(String name, String role, String prompt, AtomicBoolean stopFlag) {
  53.         String systemPrompt = String.format(
  54.             "You are '%s', role: %s, at %s. " +
  55.             "Use send_message to communicate. Complete your task.",
  56.             name, role, WORKDIR
  57.         );
  58.         // 个性化系统提示:为每个智能体定制角色
  59.         // 明确角色:让智能体知道自己的身份和职责
  60.         
  61.         List<Map<String, Object>> messages = new ArrayList<>();
  62.         messages.add(Map.of("role", "user", "content", prompt));
  63.         // 初始化消息:从传入的prompt开始
  64.         
  65.         // 最大迭代次数限制
  66.         for (int i = 0; i < 50 && !stopFlag.get(); i++) {
  67.             try {
  68.                 // 检查邮箱
  69.                 List<Map<String, Object>> inbox = BUS.readInbox(name);
  70.                 for (Map<String, Object> msg : inbox) {
  71.                     messages.add(Map.of("role", "user", "content", gson.toJson(msg)));
  72.                 }
  73.                 // 邮箱检查:每次迭代前检查新消息
  74.                 // 消息注入:将收到的消息加入上下文
  75.                 // 持续通信:支持动态的任务调整
  76.                
  77.                 // 短暂休眠,避免 CPU 过度使用
  78.                 Thread.sleep(100);
  79.                 // 节能设计:避免忙等待
  80.             }
  81.         }
  82.         
  83.         // 更新状态
  84.         Map<String, Object> member = findMember(name);
  85.         if (member != null && !"shutdown".equals(member.get("status"))) {
  86.             member.put("status", "idle");
  87.             saveConfig();
  88.         }
  89.         // 状态恢复:完成后状态恢复为idle
  90.         // 配置持久化:状态变化立即保存
  91.     }
  92. }
复制代码

  • 生命周期管理:智能体的创建、运行、克制、烧毁
  • 状态恒久化:智能体状态生存到文件,重启可规复
  • 独立实验:每个智能体在自己的线程中独立运行
  • 通讯集成:主动查抄邮箱,支持动态通讯
  • 优雅克制:支持安全的克制机制
多智能体通讯工具集
  1. // 团队管理工具集
  2. public enum ToolType {
  3.     SPAWN_TEAMMATE("spawn_teammate", "Spawn a persistent teammate that runs in its own thread."),
  4.     LIST_TEAMMATES("list_teammates", "List all teammates with name, role, status."),
  5.     SEND_MESSAGE("send_message", "Send a message to a teammate's inbox."),
  6.     READ_INBOX("read_inbox", "Read and drain the lead's inbox."),
  7.     BROADCAST("broadcast", "Send a message to all teammates.");
  8.     // 团队创建:动态生成新的智能体
  9.     // 状态查询:查看所有智能体状态
  10.     // 点对点通信:向特定智能体发送消息
  11.     // 广播通信:向所有智能体发送消息
  12.     // 邮箱读取:获取收到的消息
  13. }
  14. // 工具处理器
  15. TOOL_HANDLERS.put(ToolType.SEND_MESSAGE.name, args -> {
  16.     String to = (String) args.get("to");
  17.     String content = (String) args.get("content");
  18.     String msgType = (String) args.get("msg_type");
  19.     if (msgType == null) msgType = "message";
  20.     return BUS.send("lead", to, content, msgType);
  21.     // 领导身份:所有消息都以"lead"身份发送
  22.     // 灵活消息类型:支持不同类型的消息
  23. });
  24. TOOL_HANDLERS.put(ToolType.BROADCAST.name, args -> {
  25.     String content = (String) args.get("content");
  26.     return BUS.broadcast("lead", content, TEAM_MANAGER.memberNames());
  27.     // 批量发送:向所有团队成员发送消息
  28.     // 排除自己:广播不包含发送者自己
  29. });
复制代码

  • 完备的通讯API:提供完备的智能体间通讯本领
  • 向导-成员模式:明白的向导智能体控制整个团队
  • 机动的通讯模式:支持点对点、广播、邮箱读取
  • 与现有体系集成:与根本工具无缝集成
向导智能体主循环
  1. // Agent 主循环(领导智能体)
  2. public static void agentLoop(List<Map<String, Object>> messages) {
  3.     while (true) {
  4.         try {
  5.             // 检查领导邮箱
  6.             List<Map<String, Object>> inbox = BUS.readInbox("lead");
  7.             if (!inbox.isEmpty()) {
  8.                 String inboxJson = gson.toJson(inbox);
  9.                 messages.add(Map.of(
  10.                     "role", "user",
  11.                     "content", "<inbox>" + inboxJson + "</inbox>"
  12.                 ));
  13.                
  14.                 messages.add(Map.of(
  15.                     "role", "assistant",
  16.                     "content", "Noted inbox messages."
  17.                 ));
  18.                 // 自动邮箱检查:每次迭代前检查新消息
  19.                 // 结构化注入:用XML标签包裹,便于解析
  20.                 // 对话完整:添加assistant响应,保持结构
  21.             }
  22.             
  23.             // 显示团队状态
  24.             int activeCount = TEAM_MANAGER.getActiveCount();
  25.             if (activeCount > 0) {
  26.                 System.out.printf("[Active teammates: %d]%n", activeCount);
  27.             }
  28.             // 状态监控监控:实时显示活跃智能体数量
  29.         }
  30.     }
  31. }
复制代码

  • 主动通讯:向导智能体主动吸取和处置惩罚消息
  • 状态感知:实时相识团队状态
  • 决议依据:基于团队反馈做出更好的决议
  • 向导和谐:向导智能体负责和谐解个团队
架构演进与代价

从 BackgroundTasksSystem 到 AgentTeamsSystem 的升级
维度BackgroundTasksSystemAgentTeamsSystem架构模式主从异步使命多智能体协作智能水平被动实验使命主动协作办理通讯方式效果关照布局化消息通报脚色分工无明白的脚色化分工决议机制会合决议分布式协同决议
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表