🎯 今日核心问题
- 两个 Agent 之间的「消息」,到底应该带哪些字段?多了会怎样、少了会怎样?
- 上游的上下文,传全文、传摘要、还是传引用?判断依据是什么?
- 并行分支的结果合并时,怎么保证不丢关键信息、也不把 token 撑爆?
📖 精读提纲
【一】消息不是聊天记录,是一条带元数据的任务单
多 Agent 系统里最贵的错误,是把 Agent 间通信写成「把 A 的全部对话历史发给 B」。那是把 A 的噪声原封不动地搬到 B 的上下文里,B 还得自己分辨哪些是有用的。正确的做法是定义一个结构化信封,固定六件事:
- taskId / parentTaskId:整条链路的追踪 ID。没有它,线上出问题你无法还原「这个结论是谁给的」。
- from / to:谁给的、给谁。用于审计与环路检测。
- intent:这次要对方做什么,一句话祈使句。必须写成「产出 X」,不能写成「关于 X」。
- inputs:结构化事实,最好带
source引用(数据库主键、文档 URL),而不是一段散文。 - constraints:字数、格式、禁止事项、必须引用哪些来源。
- expected:产出契约。这是 D1 判据四的落地形式,缺失它整个拆分会退化成口口相传。
一条好的 Agent 消息,长度通常在 300-800 token。如果你的消息动辄 5000 token,说明你在传上下文而不是传任务。
【二】上下文传递的三种方式,各有明确适用面
全文直传:仅当上游产出本身就是要被下游加工的原料(例如 OCR 文本交给摘要 Agent)时用。上限要卡死,超过阈值必须走摘要。结构化摘要:最常用。用固定 schema 抽字段(结论 / 关键数字 / 引用列表 / 未决问题),比让模型「总结一下」稳定得多。引用传递:把大数据塞进共享存储(Redis / 对象存储),消息里只放 key,下游按需取。这是唯一能让上下文不随时间膨胀的方案,也是长任务必用。
一个实用的经验规则:下游需要的信息若能用一次工具调用重新取回,就传引用;取不回(例如上游的推理过程),就传结构化摘要;两者都不行,才传原文。
【三】并行结果的合并:先对齐,再归并
三个并行专家各返回一段结果,直接 String.join 是最常见的错误:顺序不稳定、字段重复、关键分歧被埋在第二段里。正确流程是两步:对齐——把结果映射到同一 schema,缺字段标 MISSING 而不是留空;归并——按字段合并,冲突字段保留全部候选并附来源,不做静默去重。合并后交给 Supervisor 一个「候选 + 来源」的结构,而不是一段混合文本,这样 D5 的仲裁才有输入。
【四】常见坑
- ❌ 让下游 Agent 自己从前文里找上下文。找到的是错的,而且你无法定位。
- ❌ 消息里带完整的
tool_calls历史。下游既无法执行你的工具调用,也理解不了你的中间态。 - ❌ 用自然语言拼接多个并行结果。字段错位是必然的。
- ❌ 不记录消息本身。多 Agent 系统排障的第一现场就是消息日志,请把信封原文落库。
💻 代码示例
消息信封 + 上下文策略 + 并行归并,三段都是纯 Java,可单测。
/** 消息信封:Agent 之间只流通这个对象 */
public record AgentMessage(
String msgId,
String taskId,
String parentTaskId,
String from,
String to,
String intent,
Map<String, Object> inputs, // 结构化事实,值优先放引用 key
List<String> constraints,
OutputContract expected,
Map<String, String> refs, // 大数据引用:key -> 存储地址
int hop) {
public AgentMessage next(String toAgent, String intent, Map<String, Object> in) {
if (hop >= 4) throw new IllegalStateException("传递链过深,疑似环路: " + taskId);
return new AgentMessage(UUID.randomUUID().toString(), taskId, msgId, this.to,
toAgent, intent, in, constraints, expected, refs, hop + 1);
}
}
public record OutputContract(String format, int maxChars, List<String> mustCite) { }
/** 上下文策略:按可用性与体积决定传引用 / 摘要 / 原文 */
@Service
@RequiredArgsConstructor
public class ContextPacker {
private final RedisTemplate<String, String> redis;
private final ChatModel smallModel; // 便宜的模型专做摘要
private static final int INLINE_LIMIT = 1200; // 字符
public Packed pack(String key, String raw) {
if (raw.length() <= INLINE_LIMIT) {
return new Packed(raw, Map.of(), "INLINE");
}
// 可重新取回的资料:传引用,下游需要时自己拉
if (key != null && key.startsWith("doc:") || key != null && key.startsWith("db:")) {
redis.opsForValue().set("ctx:" + key, raw, Duration.ofHours(2));
return new Packed(null, Map.of("ctxKey", key), "REF");
}
// 取不回(如推理过程):结构化摘要,固定 schema
String summary = smallModel.chat("""
把下面内容压成 JSON,字段固定为:
{"conclusion":"","numbers":{},"citations":[],"openQuestions":[]}
不得添加其他字段,不得编造。
""" + raw);
return new Packed(summary, Map.of(), "SUMMARY");
}
public record Packed(String inline, Map<String, String> refs, String mode) { }
}
/** 并行结果归并:先对齐 schema,再按字段合并,冲突不静默丢弃 */
@Component
public class ResultMerger {
private final ObjectMapper om = new ObjectMapper();
public Merged merge(List<SubTaskResult> results) {
Map<String, List<Sourced>> byField = new LinkedHashMap<>();
for (SubTaskResult r : results) {
JsonNode node;
try {
node = om.readTree(r.content());
} catch (Exception e) {
byField.computeIfAbsent("_unparsed", k -> new ArrayList<>())
.add(new Sourced(r.agent(), r.content()));
continue;
}
node.fields().forEachRemaining(e -> byField
.computeIfAbsent(e.getKey(), k -> new ArrayList<>())
.add(new Sourced(r.agent(), e.getValue().asText())));
}
List<Conflict> conflicts = byField.entrySet().stream()
.filter(e -> e.getValue().stream().map(Sourced::value).distinct().count() > 1)
.map(e -> new Conflict(e.getKey(),
e.getValue().stream().map(Sourced::toString).toList()))
.toList();
return new Merged(byField, conflicts);
}
public record Sourced(String agent, String value) { }
public record Conflict(String field, List<String> candidates) { }
public record Merged(Map<String, List<Sourced>> fields, List<Conflict> conflicts) { }
}
注意 ResultMerger 的 conflicts 不是错误,是有价值的信号——它正好是明天仲裁的输入。很多系统在合并时把冲突「取第一个」抹掉,等于把两个 Agent 的分歧当噪声扔了,那辩论和并行就都白做了。
✏️ 今日动手
给 D3 的 Supervisor 换上 AgentMessage 信封,要求:① 每个专家的输入都由 ContextPacker 决定 INLINE / REF / SUMMARY,并在日志里打印 mode 与字符数;② 把一段 8000 字的产品文档塞进 inputs,验证它被切成 REF 而不是硬塞;③ 让两个专家返回同名字段但不同值,确认 ResultMerger.conflicts 能捕获并带上来源。
🔖 明日预告
冲突已经能被捕获了,但它还只是个数据结构。明天讲仲裁:什么时候该让第三个 Agent 判、什么时候该用工具去查、什么时候该直接把这件事故意交给用户决定,以及怎么避免仲裁本身变成新的成本黑洞。