Context Sharing and Isolation in Multi-Agent Systems: Architecture Patterns from ai-agent-book

Multi-agent systems in the ai-agent-book repository manage context through per-agent isolation of conversation history and explicit sharing via a typed Context class, ensuring state is sandboxed by default and shared only through deliberate, controlled interfaces.

The bojieli/ai-agent-book repository demonstrates practical implementations of context sharing and isolation in multi-agent systems through a hybrid architectural pattern. Each agent maintains strict boundaries around its internal reasoning state while participating in controlled information exchange via structured containers. This approach prevents state leakage between independent agent instances while enabling deliberate collaboration through explicit data passing mechanisms.

Per-Agent Isolation: Sandboxing Conversational State

The foundation of context management in this architecture rests on per-agent isolation, where every agent instance owns its mutable state and resets it between operations.

Isolated Conversation History in WebSearchAgent

In chapter1/web-search-agent/agent.py, the WebSearchAgent class demonstrates strict isolation through instance-specific storage. The agent initializes private lists for conversation_history and trace that are never shared across instances unless explicitly extracted and passed.

class WebSearchAgent:
    def __init__(self, …):
        self.conversation_history = []      # isolated per instance

        self.trace = []                      # local ReAct trace

    def clear_history(self):
        self.conversation_history = []
        logger.info("对话历史已清空")

The search_and_answer method invokes clear_history() at the start of new requests, guaranteeing that previous user interactions cannot leak into subsequent tasks. This pattern ensures request-scoped isolation, preventing "state-bleed" bugs where earlier queries influence current reasoning.

Local Trace Management for ReAct Agents

Each agent maintains a local trace list recording the ReAct loop steps (thought → action → observation → answer). This trace remains internal to the agent that produced it and is not automatically propagated to other agents. When cross-agent visibility is required, developers must explicitly convert the trace to a summary string and inject it into a shared Context object.

Explicit Context Sharing via the Context Class

While isolation provides safety, explicit context sharing enables coordination. The repository implements a typed Context class that acts as a controlled conduit for inter-agent communication.

The Context Object Architecture

Defined in chapter8/gaia-experience/AWorld/core/context/base.py, the Context class provides a structured container with context_info and trajectories mappings. Agents receive Context instances through method signatures such as run_task(self, …, context: Context), ensuring shared data is explicitly declared in function contracts.


# inside self_evolving_agent.py

async def get_history_context(self, user_id, session_id, task_id, user_input):
    task_context = Context()
    task_context.context_info["history"] = build_history_context(history_messages)
    task_context.context_info["user_profiles"] = user_profiles
    task_context.context_info["similar_messages_history"] = similar_messages_history
    return task_context

Only fields written into task_context.context_info become visible to downstream agents. This opt-in sharing model prevents accidental exposure of internal variables.

Controlled Data Flow Between Agents

The code enforces access discipline by interacting with Context solely through its public API (context.context_info.get() and context.context_info.set()). When an agent needs to expose information, it writes to specific keys in context_info. Other agents can read these keys later, but cannot access the source agent's private attributes directly.

Staged System Prompts as a Sharing Mechanism

The repository employs staged system prompts to render shared context into LLM-visible text while keeping raw Python objects isolated from the model.

Rendering Context into LLM-Visible Text

In chapter10/staged-system-prompt/agent.py, prompts are constructed using format_prompt(context=…, **vars), which interpolates selected context fields into the final string. The LLM receives only the rendered text, not the underlying Context object.


# (pseudo-code from chapter10/staged-system-prompt/agent.py)

def build_prompt(context: Context, **extra):
    return f"""You are a helpful assistant.
Task: {extra['task']}.
Context: {context.context_info.get('summary', '')}
"""

This mechanism guarantees that the LLM cannot access raw Python objects or internal data structures—it processes only the specific text the developer chooses to embed.

Tool-Call and Trace Isolation

Beyond conversation history, the architecture isolates tool-call side effects to prevent execution leakage between agents.

When an agent invokes a tool, the result appends to that agent's private conversation_history as a tool message. Other agents never see the raw tool invocation or its output unless the calling agent explicitly extracts the result and forwards it through the Context object. This prevents tool execution side effects from corrupting unrelated agents' state.

For trace sharing, agents can propagate summaries rather than full internal state:


# In an orchestrator (e.g. chapter8/gaia-experience example)

summary = "\n".join(
    f"{t['type']}: {t.get('content','')}" for t in agent_a.get_trace()
)
agent_b.run_task(..., context=Context(context_info={"trace_summary": summary}))

This pattern enables debugging and auditability without coupling agents' internal reasoning steps.

Summary

  • Per-agent isolation is enforced through instance-specific conversation_history and trace lists that reset between requests via clear_history().
  • Explicit context sharing occurs through the typed Context class in chapter8/gaia-experience/AWorld/core/context/base.py, using context_info mappings for controlled data exchange.
  • Staged system prompts render selected context fields into text, ensuring LLMs access only developer-approved information via string interpolation.
  • Tool-call isolation prevents side-effect leakage by keeping tool results in private history unless explicitly forwarded.
  • Trace isolation maintains local reasoning records, with optional sharing through synthesized summaries rather than raw trace objects.

Frequently Asked Questions

How does WebSearchAgent ensure conversation history doesn't leak between requests?

The WebSearchAgent class in chapter1/web-search-agent/agent.py initializes isolated conversation_history and trace lists per instance. At the start of each request, the clear_history() method resets these lists to empty states, ensuring no data persists from previous interactions. This guarantees request-scoped isolation and prevents state-bleed between consecutive queries.

What is the role of the Context class in multi-agent systems?

The Context class, defined in chapter8/gaia-experience/AWorld/core/context/base.py, serves as a typed container for inter-agent data sharing. It provides context_info and trajectories mappings that agents populate and read through explicit method calls. This structure enables controlled information flow while maintaining type safety and preventing direct access to private agent attributes.

Why are staged system prompts important for context isolation?

Staged system prompts, implemented in chapter10/staged-system-prompt/agent.py, function as a security boundary between Python objects and LLM processing. By rendering only selected Context fields into prompt strings via format_prompt(), the system ensures language models receive only text representations of data, not raw object references. This prevents models from accessing or manipulating internal system state directly.

Can agents access another agent's internal trace directly?

No, agent traces remain strictly local to the instance that generated them. The trace list in WebSearchAgent and similar classes is a private attribute. When one agent needs visibility into another's reasoning, the source agent must explicitly convert its trace to a summary string and inject it into a shared Context object's context_info mapping, as demonstrated in the Gaia experience orchestration examples.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →