16.4 Multi-agent Collaboration
Multiple agents can divide work and provide separate review contexts. Role prompts alone do not create expertise or independent errors. Agents sharing models and evidence can repeat the same mistake, and reading each other’s answers can induce false consensus. First establish that decomposition is worth its communication cost.
1. Choose a communication structure
AutoGen, MetaGPT and debate research explore different collaboration patterns. [1] [2] [3] This table summarizes design tradeoffs, not a performance ranking.
| Structure | Potential fit | Failure to investigate |
|---|---|---|
| Sequential pipeline | Clear dependent stages | Error propagation; routes for downstream correction |
| Manager–worker | Decomposable research or implementation | Manager bottlenecks, information loss, duplicate work |
| Independent review and debate | Candidate evaluation with inspectable evidence | Correlated errors, conformity, repeated cost |
Sequential execution does not make model outputs deterministic. Consensus can be a stopping rule without certifying correctness. Compare a single agent, independent sampling and collaboration under equal total token/time/tool budgets, reporting error and latency distributions.
2. Blackboard state and conflict handling
A blackboard stores structured artifacts for selective reading. It can reduce repeated transcript transfer, but summaries can also discard essential evidence. MetaGPT’s SOPs illustrate explicit roles and workflows; they do not guarantee correct outputs. [2]
Attach task/version IDs, evidence, ownership, completion state and dependencies. Concurrent edits need a conflict policy such as compare-and-swap or locking. Side-effecting tools need idempotency keys, permission boundaries and retry/recovery rules.
Embedding distance is not a contradiction detector. Similar statements can disagree, and dissimilar statements can both be true. Preserve conflicting claims with source, time and scope, then resolve them through checkers, further evidence or accountable adjudication. Averaging vectors is not factual arbitration.
3. Conditions for latent-state communication
Passing latent states instead of text can be studied when representations and trained interfaces are compatible. Equal vector width does not imply a shared semantic space. KV caches depend on layers, positions, checkpoints, tensor layouts and execution state; they are not interchangeable messages between arbitrary hosted models.
Untrained tensor-operation example. Cross-attention over random vectors demonstrates shapes only, not agent collaboration or a speed/quality improvement. A real system needs representation alignment, communication objectives, compatible checkpoints, training/evaluation data, masking/position/device/dtype contracts and recovery. A true entry in the padding mask excludes that worker token.
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiAgentAttentionRouter(nn.Module):
"""
A neural router for latent-space multi-agent communication.
Allows a Manager agent to query the hidden states of multiple Worker agents
using Cross-Attention, aggregating insights without decoding to text.
"""
def __init__(self, hidden_dim: int = 1024, num_heads: int = 8):
super().__init__()
self.hidden_dim = hidden_dim
# Cross-Attention: Manager queries, Workers provide Keys and Values
self.cross_attention = nn.MultiheadAttention(
embed_dim=hidden_dim,
num_heads=num_heads,
batch_first=True
)
# Feed-forward network to process the aggregated latent state
self.ffn = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim * 4),
nn.GELU(),
nn.Linear(hidden_dim * 4, hidden_dim)
)
self.layer_norm1 = nn.LayerNorm(hidden_dim)
self.layer_norm2 = nn.LayerNorm(hidden_dim)
def forward(self, manager_query: torch.Tensor, worker_states: torch.Tensor, worker_padding_mask=None):
"""
Args:
manager_query: Tensor of shape (Batch, Seq_Len_M, Hidden_Dim)
The current latent state of the Manager agent.
worker_states: Tensor of shape (Batch, Num_Workers * Seq_Len_W, Hidden_Dim)
The concatenated latent states of all Worker agents.
Returns:
aggregated_state: Tensor of shape (Batch, Seq_Len_M, Hidden_Dim)
The updated Manager state infused with Worker insights.
"""
if worker_padding_mask is not None and worker_padding_mask.all(dim=1).any():
raise ValueError("each example needs at least one unmasked worker token")
# Manager queries the workers' states
attn_output, attn_weights = self.cross_attention(
query=manager_query,
key=worker_states,
value=worker_states,
key_padding_mask=worker_padding_mask
)
# Residual connection and LayerNorm
x = self.layer_norm1(manager_query + attn_output)
# FFN with residual connection
ffn_output = self.ffn(x)
aggregated_state = self.layer_norm2(x + ffn_output)
return aggregated_state, attn_weights
# --- Execution Example ---
if __name__ == "__main__":
batch_size = 2
hidden_dim = 64
manager_seq_len = 16 # e.g., Manager's current thought vector length
worker_seq_len = 64 # e.g., Each worker's latent scratchpad length
num_workers = 3 # e.g., Coder, Searcher, QA
# Initialize the Router
router = MultiAgentAttentionRouter(hidden_dim=hidden_dim, num_heads=8)
# Simulate Manager's current latent state
manager_query = torch.randn(batch_size, manager_seq_len, hidden_dim)
# Simulate latent states from 3 different workers
worker_1_state = torch.randn(batch_size, worker_seq_len, hidden_dim)
worker_2_state = torch.randn(batch_size, worker_seq_len, hidden_dim)
worker_3_state = torch.randn(batch_size, worker_seq_len, hidden_dim)
# Concatenate worker states along the sequence dimension to form the Key/Value pool
combined_worker_states = torch.cat([worker_1_state, worker_2_state, worker_3_state], dim=1)
# Shape: (2, 192, 64)
# Route and aggregate
updated_manager_state, attention_map = router(manager_query, combined_worker_states)
print(f"Manager Query Shape: {manager_query.shape}")
print(f"Combined Worker States Shape: {combined_worker_states.shape}")
print(f"Updated Manager State Shape: {updated_manager_state.shape}")
print(f"Attention Map Shape: {attention_map.shape}")
# Attention Map Shape: (Batch, Manager_Seq, Total_Worker_Seq)
4. Inspect communication paths
The diagram illustrates message paths in sequential, hierarchical and debate structures. It does not measure throughput or error recovery.
Coordination and failure paths
1 → 2 → 3
Later stages consume earlier artifacts. Clear handoffs help diagnosis, but an early mistaken requirement can propagate. Add explicit feedback when needed.5. Practical takeaway
Independent review, evidence quality and recoverable state can matter more than agent count. Bound the total work budget and stopping conditions, and verify artifacts. The next section considers provenance, update and deletion contracts when artifacts become long-term memory.
Quizzes
Quiz 1: Do different roles guarantee independent errors?
No. Shared models, data and evidence can produce common errors, and debate can reinforce conformity. Compare against independent sampling at equal budget.
Quiz 2: What cost does a blackboard reduce, and what risk does it add?
It can reduce redundant transcript transfer, but introduces summary loss, stale versions and concurrent-update conflicts. Preserve evidence, versions and dependencies.
Quiz 3: Can equal-width latent vectors be exchanged directly?
No. Semantic spaces, trained interfaces and position/layer/checkpoint contracts must be compatible. Random cross-attention does not provide that compatibility.
Quiz 4: Why do SOPs not guarantee correctness?
SOPs define workflow and artifact contracts, but claims and code at each stage can be wrong. Evidence checks, tests and correction paths remain necessary.
Quiz 5: Can embedding distance and averaging resolve factual conflicts?
Distance alone does not establish contradiction, and an average vector cannot adjudicate truth. Compare provenance, time and scope, and explicitly retain unresolved conflicts.
References
- Wu, Q., et al. (2023). AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation. arXiv:2308.08155
- Hong, S., et al. (2023). MetaGPT: Meta Programming for A Multi-Agent Collaborative Framework. arXiv:2308.00352
- Du, Y., et al. (2023). Improving Factuality and Reasoning in Language Models through Multiagent Debate. arXiv:2305.14325
- Qian, C., et al. (2023). Communicative Agents for Software Development (ChatDev). arXiv:2307.07924