Multi-Agent 协作

多个 AI Agent 协同工作,分工完成复杂任务


什么时候需要 Multi-Agent?

单一 Agent 适合独立任务;Multi-Agent 适合复杂工作流:

  • 并行调研多个主题再合并
  • 规划 + 执行分离(PlanAgent + ActionAgent)
  • 审查链(写代码 → 自测 → 代码审查)

方案1: 串行协作链

1
用户请求 → Agent A(规划) → Agent B(执行) → Agent C(审查) → 返回结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Service
public class SerialAgentChain {

private final ChatClient planner;
private final ChatClient executor;
private final ChatClient reviewer;

public String process(String task) {
// 1. 规划
String plan = planner.prompt()
.user("为以下任务制定执行计划:\n" + task)
.call()
.content();

// 2. 执行
String result = executor.prompt()
.user("按以下计划执行:\n" + plan)
.call()
.content();

// 3. 审查
String review = reviewer.prompt()
.user("审查执行结果,如有问题指出:\n" + result)
.call()
.content();

return "执行结果:\n" + result + "\n\n审查意见:\n" + review;
}
}

方案2: 并行收集再合并

1
用户请求 → 同时发给 Agent A、B、C → 汇总 → 返回
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Service
public class ParallelAgentService {

private final ChatClient agentA; // 技术专家
private final ChatClient agentB; // 产品经理
private final ChatClient agentC; // 财务分析

public String research(String topic) {
// 并行调用
String techAnalysis = agentA.prompt()
.user("从技术角度分析:\n" + topic)
.call().content();

String pmAnalysis = agentB.prompt()
.user("从产品角度分析:\n" + topic)
.call().content();

String financeAnalysis = agentC.prompt()
.user("从财务角度分析:\n" + topic)
.call().content();

// 汇总
return "综合分析报告:\n\n" +
"【技术】" + techAnalysis + "\n\n" +
"【产品】" + pmAnalysis + "\n\n" +
"【财务】" + financeAnalysis;
}
}

方案3: 带状态的对话 Agent(ReAct 模式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Service
public class ReActAgent {

private final ChatClient chatClient;
private final ToolExecutor toolExecutor;
private final ChatMemory memory = new InMemoryChatMemory();

public String run(String userTask) {
// 加载历史记忆
List<Message> history = memory.getMessages();
String context = history.stream()
.map(m -> m.getContent() + "\n")
.collect(Collectors.joining());

// ReAct 循环: Thought → Action → Observation
String response = chatClient.prompt()
.messages(history)
.user("任务: " + userTask + "\n请思考并决定是否需要调用工具。")
.tools(myToolSet)
.call()
.content();

// 如果有工具调用,执行并记录
// ... (工具调用逻辑)

// 存入记忆
memory.add(new UserMessage(userTask));
memory.add(new AssistantMessage(response));

return response;
}
}

Agent 间的通信:共享 VectorStore

多个 Agent 共享同一个向量数据库,实现上下文共享:

1
2
3
4
5
6
7
@Configuration
public class SharedVectorStoreConfig {
@Bean
public VectorStore sharedVectorStore(EmbeddingModel embeddingModel) {
return new InMemoryVectorStore(embeddingModel);
}
}

监控与追踪

建议在每个 Agent 的调用前后记录日志:

1
2
3
4
log.info("Agent[{}] 开始处理: {}", agentName, task);
long start = System.currentTimeMillis();
String result = chatClient.prompt().user(task).call().content();
log.info("Agent[{}] 耗时: {}ms", agentName, System.currentTimeMillis() - start);