多 Agent 共享上下文的六种实现模式与架构选型

本文为「AI Agent 技术系列」第 7 篇。在 LangChain 工程化(第 4 篇)提到的多智能体协作基础上,深入”多个 Agent 之间如何共享状态”这一架构设计层面。

一、主题定义与背景

为什么多 Agent 需要共享上下文

单个 Agent 的能力有限。当任务复杂时,需要多个专业 Agent 分工协作——就像一个团队需要共享项目文档、任务看板和沟通记录一样,多 Agent 系统也需要共享上下文。

核心难题

难题 说明 影响
一致性 多个 Agent 并发读写同一上下文时如何保证数据一致 数据竞争、结果不确定
性能 共享全部上下文导致 token 消耗爆炸 成本飙升、延迟增加
可观测性 多个 Agent 的交互难以追踪和调试 出问题难以定位

从单 Agent 到多 Agent 的上下文演进

1
2
3
4
单 Agent:上下文 = 用户输入 + Agent 输出(线性)

多 Agent:上下文 = 用户输入 + Agent A 输出 + Agent B 输出 + ... + 元信息
→ 需要设计:谁看到什么?何时看到?如何更新?

多 Agent 系统最新进展

2024-2025 年,多 Agent 系统研究快速推进:

  • AutoGen v0.4(2025.01):微软发布重大架构重构,从对话驱动转向更结构化的跨语言、分布式编排 [1]
  • CrewAI:以角色化协作和低门槛,在团队协作场景快速增长
  • LangGraph:凭借 StateGraph 的显式状态管理,成为多 Agent 编排的生产推荐选择 [2]

二、核心技术原理与架构设计

多 Agent 共享上下文有六种主流实现模式,每种都有其适用场景。

模式 1:共享状态对象(Shared State)

最常见的方式。创建一个可变的上下文对象,在 Agent 调用链中依次传递。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface SharedContext {
messages: string[];
artifacts: Record<string, string>;
metadata: Record<string, unknown>;
}

const sharedContext: SharedContext = {
messages: [],
artifacts: {},
metadata: {},
};

// Agent A 执行
const resultA = await agentA.run(sharedContext);
sharedContext.artifacts["agent_a"] = resultA;

// Agent B 执行(可访问 Agent A 的结果)
const resultB = await agentB.run(sharedContext);
sharedContext.artifacts["agent_b"] = resultB;
优点 缺点
实现简单,延迟低 耦合度高,Agent 间依赖上下文结构
所有 Agent 看到完整上下文 并发下需要加锁或用不可变数据结构

适用场景:线性流水线、Agent 数量少(2-3 个)的简单场景。

模式 2:黑板模式(Blackboard Pattern)

所有 Agent 共享一个”黑板”(中心化存储),各 Agent 自行读写:

graph TB
    A[Agent A] <-->|读写| B[Blackboard<br/>共享存储]
    C[Agent C] <-->|读写| B
    B <-->|读写| D[Agent B]
    B <-->|读写| E[Agent D]

    B --> B1[key/value 存储]
    B --> B2[版本控制]
    B --> B3[读写锁]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Blackboard {
private data = new Map<string, unknown>();
private versions = new Map<string, { agent: string; time: Date }>();

async write(key: string, value: unknown, agent: string): Promise<void> {
this.data.set(key, value);
this.versions.set(key, { agent, time: new Date() });
}

async read<T>(key: string): Promise<T | undefined> {
return this.data.get(key) as T | undefined;
}
}

// Agent 异步读写黑板
const blackboard = new Blackboard();
await blackboard.write("proposal", "初步方案", "proposer");
const critique = await blackboard.read<string>("proposal"); // Critic Agent 读取

这是经典 AI 架构模式,适合多个 Agent 需要异步、并发访问共享数据的场景。通常用 Redis、内存 KV 存储或数据库实现。

模式 3:消息传递 + 对话历史拼接(Message Passing)

每个 Agent 的输出作为消息追加到共享的 messages 数组中,后续 Agent 能看到前面所有 Agent 的”发言”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const messages: Array<{ role: string; name?: string; content: string }> = [
{ role: "user", content: "评估这张照片" },
];

// Agent A(Proposer)执行后,输出追加到 messages
const responseA = await callLLM([
...messages,
{ role: "system", content: agentAPrompt },
]);
messages.push({ role: "assistant", name: "proposer", content: responseA });

// Agent B(Critic)可以看到 Agent A 的输出
const responseB = await callLLM([
...messages,
{ role: "system", content: agentBPrompt },
]);
messages.push({ role: "assistant", name: "critic", content: responseB });

这是 LLM 多 Agent 系统中最常用的方式,如 AutoGen、CrewAI、LangGraph 等框架均采用此模式的变体 [1]。

模式 4:编排器模式(Orchestrator)

由一个中心”编排器”控制所有 Agent 的调度,并负责将上下文在 Agent 间路由:

graph TB
    O[Orchestrator<br/>编排器] -->|context| A[Agent A]
    O -->|context| B[Agent B]
    O -->|context| C[Agent C]
    A -->|result| O
    B -->|result| O
    C -->|result| O

编排器决定:

  • 哪些上下文片段传给哪个 Agent(选择性共享,而非全量共享)
  • Agent 执行的顺序和条件
  • 是否需要多轮迭代(如 Proposer-Critic 循环)

与共享状态对象的关键区别:编排器模式是选择性共享——不是所有 Agent 都需要全部上下文,编排器根据任务需要过滤上下文。

实际案例中,编排器可以将子 Agent 包装为工具,由主 Agent(Supervisor)按需调用:

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
33
34
35
36
37
38
import { createAgent, tool } from "langchain";
import { z } from "zod";

// 将子 Agent 包装为工具——主 Agent 通过工具调用实现"选择性共享"
const scheduleEvent = tool(
async ({ request }) => {
const result = await calendarAgent.invoke({
messages: [{ role: "user", content: request }],
});
return result.messages[result.messages.length - 1]?.content;
},
{
name: "schedule_event",
description: "使用自然语言安排日历事件",
schema: z.object({ request: z.string() }),
}
);

const manageEmail = tool(
async ({ request }) => {
const result = await emailAgent.invoke({
messages: [{ role: "user", content: request }],
});
return result.messages[result.messages.length - 1]?.content;
},
{
name: "manage_email",
description: "使用自然语言发送邮件",
schema: z.object({ request: z.string() }),
}
);

// 主 Agent 作为编排器,按需调用子 Agent
const supervisorAgent = createAgent({
model,
tools: [scheduleEvent, manageEmail],
systemPrompt: "你是一个个人助手,可以安排日历事件和发送邮件。",
});

模式 5:事件驱动 / 发布订阅(Event-Driven)

Agent 通过事件总线通信,每个 Agent 订阅感兴趣的事件类型:

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
class EventBus {
private handlers = new Map<string, Array<(data: unknown) => Promise<void>>>();

on(eventType: string, handler: (data: unknown) => Promise<void>): void {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, []);
}
this.handlers.get(eventType)!.push(handler);
}

async emit(eventType: string, data: unknown): Promise<void> {
const handlers = this.handlers.get(eventType) ?? [];
for (const handler of handlers) {
await handler(data);
}
}
}

const eventBus = new EventBus();

// Critic 订阅 proposal_ready 事件
eventBus.on("proposal_ready", criticAgent.evaluate);
// Arbiter 订阅 critique_ready 事件
eventBus.on("critique_ready", arbiterAgent.decide);

// Proposer 完成后发布事件
async function proposerOnDone(result: unknown): Promise<void> {
await eventBus.emit("proposal_ready", result);
}

适合松耦合、异步的多 Agent 系统,常见于分布式架构。

模式 6:图状态机(Graph-based State)— LangGraph 风格

用一个有类型的状态对象作为图的全局状态,每个节点(Agent)读取并更新这个状态 [2]:

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
33
34
35
36
import { StateGraph, Annotation, END } from "@langchain/langgraph";

// 定义状态类型
const GraphState = Annotation.Root({
input: Annotation<string>,
proposal: Annotation<string>,
critique: Annotation<string>,
finalScore: Annotation<number>,
});

// Proposer 节点
async function proposerNode(state: typeof GraphState.State) {
return { proposal: await llm.invoke(state.input) };
}

// Critic 节点
async function criticNode(state: typeof GraphState.State) {
return { critique: await llm.invoke(state.proposal) };
}

// Arbiter 节点
async function arbiterNode(state: typeof GraphState.State) {
return { finalScore: score(state.proposal, state.critique) };
}

// 构建状态图
const graph = new StateGraph(GraphState)
.addNode("proposer", proposerNode)
.addNode("critic", criticNode)
.addNode("arbiter", arbiterNode)
.addEdge("proposer", "critic")
.addEdge("critic", "arbiter")
.addEdge("arbiter", END)
.setEntryPoint("proposer");

const app = graph.compile();
优点 缺点
状态流转清晰、可回溯 学习曲线较陡
支持条件分支和循环 需要预先定义状态结构
内置检查点和恢复 不适合完全动态的 Agent 拓扑

适用场景:需要精细控制、可追溯的生产级多 Agent 系统。

六种模式对比

模式 耦合度 并发性 复杂度 适用场景 典型实现
共享状态对象 线性流水线 自研
黑板模式 异步并发协作 Redis / KV 存储
消息传递 LLM 多 Agent 对话 AutoGen / CrewAI [1]
编排器 选择性共享 自研 / LangGraph
事件驱动 松耦合分布式 EventBus / 消息队列
图状态机 可追溯生产系统 LangGraph [2]

三、实际应用场景与最佳实践

场景一:Proposer-Critic 评估系统(消息传递模式)

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import OpenAI from "openai";

const client = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
});

async function proposerCriticSystem(inputText: string): Promise<{
proposal: string;
critique: string;
final: string;
}> {
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "user", content: `评估以下内容:${inputText}` },
];

// Proposer 生成初步评估
const proposerResponse = await client.chat.completions.create({
model: "qwen3.6-plus",
messages: [
...messages,
{ role: "system", content: "你是提案者,给出初步评估方案" },
],
});
messages.push({
role: "assistant",
name: "proposer",
content: proposerResponse.choices[0].message.content!,
});

// Critic 可以看到 Proposer 的输出,提出批评
const criticResponse = await client.chat.completions.create({
model: "qwen3.6-plus",
messages: [
...messages,
{ role: "system", content: "你是批评者,审查提案的不足" },
],
});
messages.push({
role: "assistant",
name: "critic",
content: criticResponse.choices[0].message.content!,
});

// Arbiter 综合提案和批评,给出最终评分
const arbiterResponse = await client.chat.completions.create({
model: "qwen3.6-plus",
messages: [
...messages,
{ role: "system", content: "你是仲裁者,综合提案和批评给出最终评分(0-100)" },
],
});

return {
proposal: proposerResponse.choices[0].message.content!,
critique: criticResponse.choices[0].message.content!,
final: arbiterResponse.choices[0].message.content!,
};
}

场景二:企业工作流编排(编排器模式 + LangGraph)

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
33
34
35
36
37
38
39
40
41
42
import { StateGraph, Annotation, END } from "@langchain/langgraph";

const WorkflowState = Annotation.Root({
task: Annotation<string>,
research: Annotation<string>,
draft: Annotation<string>,
review: Annotation<string>,
final: Annotation<string>,
});

// 研究 Agent:只接收 task,产出 research
async function researchAgent(state: typeof WorkflowState.State) {
return { research: await llmResearch(state.task) };
}

// 起草 Agent:接收 task + research,产出 draft
async function draftAgent(state: typeof WorkflowState.State) {
// 选择性共享:只读 task 和 research,不读后续的 review
return { draft: await llmDraft(state.task, state.research) };
}

// 审查 Agent:接收 draft,产出 review
async function reviewAgent(state: typeof WorkflowState.State) {
return { review: await llmReview(state.draft) };
}

// 条件分支:审查不通过则回到起草
function shouldRevise(state: typeof WorkflowState.State): string {
return state.review.includes("需要修改") ? "draft" : "finalize";
}

const graph = new StateGraph(WorkflowState)
.addNode("research", researchAgent)
.addNode("draft", draftAgent)
.addNode("review", reviewAgent)
.setEntryPoint("research")
.addEdge("research", "draft")
.addEdge("draft", "review")
.addConditionalEdges("review", shouldRevise)
.addEdge("finalize", END);

const app = graph.compile();

选型决策框架

你的场景 推荐模式 推荐框架
2-3 个 Agent 线性流水线 共享状态对象 自研(最简单)
多 Agent 异步并发 黑板模式 Redis + 自研
LLM 对话式多 Agent 消息传递 AutoGen / CrewAI [1]
需要选择性共享 编排器模式 LangGraph [2]
松耦合分布式系统 事件驱动 消息队列 + 自研
需要可追溯和恢复 图状态机 LangGraph [2]

四、常见挑战与解决方案

五大实践考量

考量点 说明 解决方案
上下文窗口限制 LLM 有 token 上限,共享全部历史不现实 摘要/裁剪策略,保留关键信息
选择性共享 不是所有 Agent 都需要全部上下文 编排器模式 + 上下文过滤
结构化 vs 自由文本 用 JSON Schema 约束 Agent 输出格式 便于下游 Agent 解析
幂等性 Agent 可能重试,共享状态写入需考虑幂等 操作前检查是否已执行
可观测性 共享上下文应支持 trace/log 每步记录 state 快照 + LangSmith trace

上下文裁剪示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function trimContext(
messages: ChatMessage[],
maxTokens: number = 4000
): ChatMessage[] {
if (countTokens(messages) <= maxTokens) return messages;

// 保留第一条(用户原始请求)和最后 N 条
const first = messages[0];
const lastN = messages.slice(-5);

// 中间消息生成摘要
const middle = messages.slice(1, -5);
const summary = summarizeMessages(middle);

return [
first,
{ role: "system", content: `历史摘要: ${summary}` },
...lastN,
];
}

幂等写入示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function idempotentWrite(
blackboard: Blackboard,
key: string,
value: unknown,
operationId: string
): Promise<unknown> {
// 检查是否已执行
const existing = await blackboard.read<unknown>(`_op_${operationId}`);
if (existing) return existing; // 已执行过,直接返回结果

await blackboard.write(key, value, "system");
await blackboard.write(`_op_${operationId}`, value, "system"); // 记录操作
return value;
}

五、行业趋势与前沿进展

AutoGen v0.4+ 架构变更

2025 年 1 月,微软发布 AutoGen v0.4,进行了重大架构重构 [1]:

维度 v0.3(旧) v0.4+(新)
架构 单进程,对话驱动 跨语言、分布式、事件驱动
上下文管理 全局共享 按需路由 + 事件订阅
扩展性 单机 支持分布式部署
语言 Python 为主 Python + .NET + 多语言

AutoGen v0.4 从对话驱动转向更结构化的编排,实际上融合了消息传递和事件驱动两种模式 [1]。

LangGraph StateGraph 的演进

LangGraph 的 StateGraph 已成为多 Agent 上下文管理的生产推荐方案 [2]:

  • 2025 版本:支持 Zod 模型作为 State(类型安全的状态定义)
  • 检查点增强:支持多种持久化后端(PostgreSQL、SQLite、Redis)
  • 人在回路集成:StateGraph 原生支持 interrupt,可在任意节点暂停等待人工输入

多 Agent 系统最新论文

2024-2025 年,多 Agent 系统研究持续深入:

  • ReMA(2025.09):将推理过程解耦为高层元思考 Agent 和低层执行 Agent,实现分层协作 [3]
  • Agentic RAG(2026.04):将 RAG 与 Agent 结合,Agent 可迭代优化检索结果 [4]
  • Agent 评估:从单 Agent 评估扩展到多 Agent 协作效能评估

上下文工程(Context Engineering)的兴起

“上下文工程”作为概念正在成形——它不仅包括提示词,还涵盖工具集成、记忆管理、多 Agent 间上下文共享。多 Agent 共享上下文是上下文工程中最复杂的部分,涉及一致性、性能、可观测性的综合权衡。


结论

多 Agent 共享上下文没有”唯一正确答案”,关键是根据场景选择:

  1. 简单流水线 → 共享状态对象(最快上手)
  2. LLM 对话式协作 → 消息传递(AutoGen / CrewAI 生态最成熟 [1])
  3. 需要精细控制和可追溯 → 图状态机(LangGraph 生产推荐 [2])
  4. 松耦合分布式 → 事件驱动(最灵活但最复杂)

选型时遵循一个原则:先确定协作模式(线性/并发/分层),再选择对应的上下文共享模式,而非反过来。避免”什么都用消息传递”的盲目选择——当 Agent 数量超过 5 个时,消息传递的 token 成本和调试难度会急剧上升。


参考资料

[1] Microsoft. AutoGen v0.4: Reimagining the Foundation of Agentic AI. 2025-01-14

[2] LangGraph 多智能体文档. 2026

[3] ReMA: Learning to Meta-Think for LLMs with Multi-agent. 2025-09-18

[4] Agentic Retrieval-Augmented Generation: A Survey. 2026-04-02