How to Implement Multi-Agent Shared Memory with AgentContext in Semantica
AgentContext acts as a high-level façade that coordinates short-term memory, vector embeddings, and knowledge-graph structures to provide unified shared memory accessible by multiple agents in the same system.
The semantica-agi/semantica repository provides a robust framework for building multi-agent systems with persistent, queryable memory. At the center of this architecture sits AgentContext, a coordination layer that unifies vector storage, graph relationships, and decision tracking into a single interface that any agent instance can share.
Architecture of the Shared Memory System
The shared memory implementation relies on three coordinated components defined in semantica/context/agent_context.py and its dependencies.
AgentMemory: The Core Storage Layer
The AgentMemory class, implemented in semantica/context/agent_memory.py, manages the lifecycle of individual memory items. It maintains a short-term deque for recent context, persists embeddings to a configurable vector store, and optionally pushes extracted entities and relationships to a knowledge graph when one is supplied.
ContextRetriever: Hybrid GraphRAG Retrieval
When a knowledge graph is present, ContextRetriever (located in semantica/mcp/tools/graph.py) performs hybrid GraphRAG retrieval. It first queries the vector store for semantic matches, then expands results over the graph using configurable hop distances. The hybrid_alpha parameter balances vector similarity (weighted toward 0) against graph distance (weighted toward 1) in the final ranking.
AgentContext: The Coordination Facade
AgentContext glues these pieces together. During construction, you provide a required vector store and an optional knowledge graph instance. Boolean flags such as decision_tracking, kg_algorithms, and graph_expansion toggle advanced features including decision provenance and causal-chain analysis.
Implementing the Shared-Memory Workflow
To enable multi-agent shared memory, instantiate a single AgentContext and distribute references across your agent fleet.
Step 1: Initialize Shared Components
First, configure the vector store and optional knowledge graph. The following example uses FAISS for vector storage and a custom ContextGraph for the knowledge base.
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissVectorStore
from semantica.graph import ContextGraph
# Create a persisted vector store
vector_store = FaissVectorStore(dim=768, persist_path="faiss_index")
# Optional: initialize a knowledge graph supporting add_nodes/add_edges
knowledge_graph = ContextGraph()
Step 2: Configure AgentContext
Build the shared context instance that all agents will reference. Enable graph expansion and decision tracking to support advanced multi-agent coordination.
shared_context = AgentContext(
vector_store=vector_store,
knowledge_graph=knowledge_graph,
retention_days=60,
max_memories=20000,
graph_expansion=True,
hybrid_alpha=0.6, # Favor graph signals slightly
decision_tracking=True,
)
Step 3: Store Memories for Multi-Agent Access
The store() method accepts raw text, document lists, or dictionaries with metadata. When storing a single string, the call forwards to AgentMemory.store(), which writes to the short-term buffer, persists the embedding, and updates the KG if present. When storing document batches, the method normalizes entries and optionally builds graph structures.
# Store a single observation visible to all agents
mem_id = shared_context.store(
"User asked how to calibrate a CNC lathe",
conversation_id="conv_42",
metadata={"type": "question", "domain": "manufacturing"},
)
# Store batch documents with entity extraction
docs = [
{"content": "Lathe calibration steps …", "metadata": {"source": "wiki"}},
{"content": "Safety checklist for CNC machines", "metadata": {"source": "internal"}},
]
stats = shared_context.store(
docs,
extract_entities=True,
extract_relationships=True
)
print(f"Stored {stats['stored_count']} documents; graph nodes={stats['graph_nodes']}")
Step 4: Retrieve Context with Hybrid GraphRAG
The retrieve() method automatically detects whether to use pure vector RAG or hybrid GraphRAG. If a knowledge graph is configured and a ContextRetriever exists, it merges vector results with graph proximity data using the hybrid_alpha weighting factor.
results = shared_context.retrieve(
query="What safety measures are required before calibrating a lathe?",
max_results=5,
proximity_weight=0.3, # Blend graph distance into final score
anchor_node="lathe", # Prioritize nodes close to "lathe"
)
for r in results:
print(f"[{r['score']:.2f}] {r['content']} (source={r['source']})")
Step 5: Enable Decision Tracking Across Agents
When decision_tracking=True and a knowledge graph is supplied, AgentContext initializes DecisionRecorder, DecisionQuery, CausalChainAnalyzer, and PolicyEngine from semantica/mcp/tools/decisions.py. Any agent can record decisions and query precedents.
# Record a decision visible to all agents
decision_id = shared_context.record_decision(
category="approval",
scenario="lathe calibration",
reasoning="All safety checks passed",
outcome="approved",
confidence=0.97,
)
# Query precedents from any agent instance
precedents = shared_context.find_precedents_advanced(
"lathe calibration",
category="approval",
use_kg_features=True,
)
Key Configuration Parameters
Understanding these parameters is essential for tuning multi-agent memory performance:
- hybrid_alpha: Float between 0 and 1 that balances vector similarity against graph distance in retrieval ranking. Values closer to 1 prioritize graph structure over semantic similarity.
- graph_expansion: Boolean flag enabling neighborhood expansion up to
max_expansion_hopsduring retrieval. - decision_tracking: Boolean that activates the decision provenance system, enabling causal-chain analysis and policy governance across agents.
Summary
- AgentContext in
semantica/context/agent_context.pyprovides the unified interface for multi-agent shared memory. - The system combines AgentMemory for short-term buffering and vector persistence with ContextRetriever for hybrid GraphRAG.
- Shared instances of the underlying vector store and knowledge graph ensure all agents access identical memory states.
decision_trackingenables cross-agent decision provenance using components fromsemantica/mcp/tools/decisions.py.- Configuration parameters like
hybrid_alphaandgraph_expansioncontrol the trade-off between semantic search and structured graph reasoning.
Frequently Asked Questions
How does AgentContext ensure consistency across multiple agents?
Consistency is achieved by sharing the same underlying AgentMemory and vector store instances among all agents. Because AgentContext acts as a façade to these shared resources, any write operation from one agent immediately becomes visible to others accessing the same context instance.
What is the difference between vector-only and hybrid GraphRAG retrieval?
Vector-only retrieval searches semantic embeddings directly in the configured vector store. Hybrid GraphRAG, enabled when a knowledge graph is present, first retrieves vector matches then expands results over graph relationships using ContextRetriever. The hybrid_alpha parameter controls the weighting between vector similarity scores and graph proximity distances in the final result set.
Can I use AgentContext without a knowledge graph?
Yes. The knowledge graph parameter is optional. Without it, AgentContext defaults to pure vector retrieval via AgentMemory methods, bypassing the ContextRetriever graph expansion logic while maintaining full short-term and long-term memory functionality.
How does decision tracking work in a multi-agent environment?
When decision_tracking=True, AgentContext initializes DecisionRecorder and DecisionQuery components from semantica/mcp/tools/decisions.py. Any agent can call record_decision() to persist reasoning steps and outcomes to the shared graph. Other agents then use find_precedents_advanced() to query historical decisions, enabling causal-chain analysis and consistent policy application across the agent fleet.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →