# Multi-Agent Context Sharing Patterns: Architecture Guide from AI-Agent-Book

> Explore multi-agent context sharing patterns architecture. Understand shared/non-shared context and collaboration topology for effective agent communication and history inheritance.

- Repository: [Bojie Li/ai-agent-book](https://github.com/bojieli/ai-agent-book)
- Tags: architecture
- Published: 2026-08-01

---

**Multi-agent context sharing patterns are defined by two orthogonal dimensions—shared versus non-shared context and collaboration topology—which determine whether agents inherit full conversation history or communicate through explicit IPC channels like `transfer_to_agent`.**

The **bojieli/ai-agent-book** repository provides a systematic taxonomy for building multi-agent LLM systems. Understanding these **multi-agent context sharing patterns** is essential for designing scalable AI workflows that balance information completeness against token limits and modularity.

## The Two Dimensions of Multi-Agent Design

According to [`book-en/chapter10.md`](https://github.com/bojieli/ai-agent-book/blob/main/book-en/chapter10.md), every multi-agent architecture spans two independent axes that shape information flow:

| Dimension | Description | Key Trade-off |
|-----------|-------------|---------------|
| **Shared vs. Non-Shared Context** | Determines if downstream agents inherit full conversation history or isolated snapshots | *Shared* ensures zero information loss but risks token overflow; *Non-shared* requires explicit hand-off mechanisms |
| **Collaboration Topology** | Defines structural routing patterns (peer, manager, or decentralized) | Topology is independent of context sharing, though shared-context systems often collapse to simple role-switch chains while non-shared systems require explicit orchestration |

These dimensions are orthogonal—you can pair a manager topology with shared context, or decentralized topology with non-shared channels—though certain combinations are more common in practice.

## Shared-Context Pattern

In the **shared-context pattern**, each new agent receives the entire trajectory of its predecessor stored in the conversation history.

**Mechanism:** The downstream agent is initialized with `previous_history` containing all prior turns, tokens, and tool outputs.

**Pros:**
- Zero information loss; any agent can audit earlier reasoning steps
- Simple implementation without explicit message-passing logic

**Cons:**
- Token consumption grows linearly with pipeline depth
- Risk of exceeding the model’s context window in multi-stage workflows

**When to use:** Early-stage pipelines where accumulated history stays comfortably under the model’s token limit, or when zero-loss knowledge transfer is a hard correctness requirement.

```python

# shared_context_demo.py

from agent import Agent, tool

@tool
def complete_stage():
    """Mark the current stage as finished."""
    return {"stage_done": True}

# Stage 1 – Requirements Analyst

requirements_agent = Agent(
    system_prompt="You are a Requirements Analyst. Ask clarifying questions.",
    tools=[complete_stage],
)

# Stage 2 – Software Engineer inherits full history

engineer_agent = Agent(
    system_prompt="You are a Software Engineer. Implement the code now.",
    tools=[complete_stage],
)

# Execution flow

req_output = requirements_agent.run()
if req_output["stage_done"]:
    # Shared context: engineer sees the entire requirements conversation

    eng_output = engineer_agent.run(previous_history=requirements_agent.history)

```

## Non-Shared Context Pattern

When agents cannot see each other’s history, information must travel through explicit IPC (inter-process communication) channels. The book outlines three canonical paradigms:

| Method | IPC Analogy | Typical Use-case |
|--------|-------------|------------------|
| **Tool-call parameters** | Synchronous message passing | Structured JSON payload hand-offs |
| **Shared file system** | Shared memory | Large artifacts like code files or datasets |
| **Message bus** | Asynchronous message passing | Decoupled, parallel pipelines |

**Rule of thumb:** According to [`book-en/chapter10.md`](https://github.com/bojieli/ai-agent-book/blob/main/book-en/chapter10.md), switch to a non-shared strategy when the expected cumulative context exceeds approximately **50%** of the model’s window size.

The **`transfer_to_agent`** tool encapsulates the hand-off logic for non-shared workflows. As implemented in [`chapter10/multi-role-transfer/orchestrator.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/orchestrator.py), this tool:

1. Saves the current conversation transcript
2. Loads the target role’s system prompt and tool set from [`chapter10/multi-role-transfer/roles.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/roles.py)
3. Passes a filtered transcript to the new role, preserving continuity without full history bloat

```python

# transfer_demo.py

from agent import Agent, tool

@tool
def transfer_to_agent(target_role: str, reason: str):
    """Save current history and hand control to another role."""
    return {"transfer": {"role": target_role, "reason": reason}}

# Role definitions from roles.py structure

roles = {
    "triage": {"prompt": "You are a triage specialist.", "tools": []},
    "research": {"prompt": "You are an information researcher.", "tools": []},
    "coding": {"prompt": "You are a programmer.", "tools": []},
}

def orchestrator(current_role: str, history):
    """Non-shared context orchestrator."""
    role_cfg = roles[current_role]
    agent = Agent(
        system_prompt=role_cfg["prompt"],
        tools=role_cfg["tools"] + [transfer_to_agent]
    )
    result = agent.run(previous_history=history)
    
    if "transfer" in result:
        next_role = result["transfer"]["role"]
        # Only history up to hand-off point is passed

        return orchestrator(next_role, result["history"])
    return result

# Start pipeline

final_result = orchestrator("triage", history=[])

```

## Collaboration Topologies

The repository defines three structural patterns for routing control and data among agents:

### Peer Collaboration

Two to three agents iterate on the same artifact (e.g., reviewer ↔ writer loops). Suitable for small, tightly coupled tasks where iterative refinement yields higher quality output.

### Manager (Orchestration) Pattern

A central manager schedules sub-agents, each handling specialized sub-tasks (research, coding, analysis). This is the architecture used in **Experiment 10-2** demonstrated in [`chapter10/multi-role-transfer/demo.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/demo.py).

```python

# manager_demo.py

from agent import Agent, tool
import asyncio

@tool
def submit_task(task: dict):
    """Push a task onto the message bus."""
    MESSAGE_BUS.append(task)
    return {"queued": True}

MESSAGE_BUS = []

async def worker(name):
    """Parallel sub-agent consuming from bus."""
    while True:
        if MESSAGE_BUS:
            task = MESSAGE_BUS.pop(0)
            agent = Agent(system_prompt=f"You are {name}.", tools=[])
            await agent.run_async(task)
        await asyncio.sleep(0.1)

async def manager():
    """Manager queues subtasks for parallel execution."""
    mgr = Agent(
        system_prompt="You are the Manager.",
        tools=[submit_task]
    )
    await mgr.run_async({"subtasks": ["code", "test", "review"]})

# Launch manager with parallel workers

asyncio.run(asyncio.gather(
    manager(), 
    worker("coder"), 
    worker("tester"), 
    worker("reviewer")
))

```

### Decentralized Pattern

No central controller; agents communicate peer-to-peer. Suitable for large-scale, fault-tolerant setups where agents may join or leave dynamically.

## Key Implementation Files

The following files contain the concrete implementations of these patterns:

- **[`book-en/chapter10.md`](https://github.com/bojieli/ai-agent-book/blob/main/book-en/chapter10.md)** — Complete classification framework, context-sharing rules, and topology taxonomy
- **[`chapter10/multi-role-transfer/roles.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/roles.py)** — Data model for each role (name, prompt, tool list) and validation of hand-off contracts
- **[`chapter10/multi-role-transfer/orchestrator.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/orchestrator.py)** — Core orchestrator merging role-specific tools with `transfer_to_agent` and driving execution flow
- **[`chapter10/multi-role-transfer/demo.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/demo.py)** — End-to-end demonstration of **Experiment 10-2** (multi-role transfer workflow)
- **[`agentbook/providers/models.py`](https://github.com/bojieli/ai-agent-book/blob/main/agentbook/providers/models.py)** — Provider backend abstraction showing how different LLM implementations can be swapped, reinforcing the non-shared plug-in design

## Summary

- **Multi-agent context sharing patterns** are defined by two orthogonal dimensions: shared versus non-shared context, and collaboration topology.
- **Shared-context** systems pass full conversation history to downstream agents, ensuring zero information loss but risking token overflow.
- **Non-shared-context** systems use explicit IPC channels (tool parameters, file systems, or message buses) and rely on tools like `transfer_to_agent` to hand off state.
- The **50% rule** recommends switching to non-shared patterns when cumulative context exceeds half the model’s window.
- **Collaboration topologies** (peer, manager, decentralized) determine structural routing and are implemented in files like [`orchestrator.py`](https://github.com/bojieli/ai-agent-book/blob/main/orchestrator.py) and [`demo.py`](https://github.com/bojieli/ai-agent-book/blob/main/demo.py).

## Frequently Asked Questions

### When should I use shared context versus non-shared context?

Use **shared context** when your pipeline has fewer than three stages and the cumulative token count stays well below the model’s limit, or when complete auditability of prior reasoning is required. Switch to **non-shared context** when approaching 50% of the context window, working with large artifacts, or requiring strict modularity between agent domains.

### What is the `transfer_to_agent` tool and how does it work?

The **`transfer_to_agent`** tool is a hand-off mechanism implemented in [`chapter10/multi-role-transfer/orchestrator.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter10/multi-role-transfer/orchestrator.py) that enables cross-domain role switching (e.g., triage → research → coding). It saves the current transcript, loads the target role’s configuration from [`roles.py`](https://github.com/bojieli/ai-agent-book/blob/main/roles.py), and passes a filtered history to the new agent, allowing each role to operate with isolated context while maintaining workflow continuity.

### How do I choose between peer, manager, and decentralized topologies?

Choose **peer collaboration** for tightly coupled tasks requiring iterative refinement between 2-3 agents (like writer-reviewer loops). Use the **manager pattern** for projects with clear sub-domain separation where a central orchestrator can dispatch tasks to specialized workers (as shown in Experiment 10-2). Select **decentralized** patterns for large-scale, fault-tolerant systems where agents must join or leave dynamically without central coordination.

### What is the 50% rule of thumb for context windows?

According to [`book-en/chapter10.md`](https://github.com/bojieli/ai-agent-book/blob/main/book-en/chapter10.md), when the expected cumulative conversation history exceeds approximately **50%** of the model’s maximum context window, you should transition from shared-context to non-shared-context patterns. This buffer accommodates token growth during the remaining pipeline stages and prevents mid-workflow truncation errors.