How to Use the AgentContext Class for AI Agents: A Complete Guide
The AgentContext class provides a unified interface for managing AI agent memory, retrieval, and decision tracking by orchestrating vector stores, knowledge graphs, and causal analysis components.
The AgentContext class in the semantica-agi/semantica repository eliminates the complexity of integrating disparate memory systems into AI agents. By abstracting vector storage, GraphRAG retrieval, and decision provenance into a single flag-driven API, it enables developers to implement sophisticated memory architectures without managing low-level component wiring. This guide examines the implementation details found in semantica/context/agent_context.py and demonstrates how to leverage its full capabilities.
Core Architecture and Components
The AgentContext class acts as an orchestration layer that lazily initializes internal components based on constructor flags. Understanding these underlying elements is essential for optimizing agent performance.
Required Vector Store Backend
Every AgentContext instance requires a vector store implementation passed as the vector_store argument. This component handles embedding storage and similarity search operations. The class accepts any compatible vector store backend from the semantica/vector_store/ directory, such as FaissStore or QdrantStore.
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissStore
vector_store = FaissStore(dim=768)
ctx = AgentContext(vector_store=vector_store)
Optional Knowledge Graph Integration
When a knowledge_graph parameter is provided (typically a ContextGraph instance), AgentContext instantiates a ContextRetriever for hybrid retrieval and exposes graph analytics methods. Without this parameter, the context operates in pure vector search mode.
from semantica.graph.context_graph import ContextGraph
knowledge_graph = ContextGraph()
ctx = AgentContext(
vector_store=vector_store,
knowledge_graph=knowledge_graph,
graph_expansion=True
)
Decision Tracking Infrastructure
Setting decision_tracking=True activates a specialized subsystem that includes DecisionRecorder, DecisionQuery, CausalChainAnalyzer, and PolicyEngine. These components, implemented across semantica/context/decision_recorder.py and semantica/context/causal_analyzer.py, enable full provenance tracking and causal chain analysis for agent decisions.
Initializing the AgentContext
The constructor follows a flag-driven design pattern, enabling advanced features through boolean parameters without requiring architectural code changes. All components are lazily created to minimize runtime footprint when features are unused.
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissStore
from semantica.graph.context_graph import ContextGraph
ctx = AgentContext(
vector_store=FaissStore(dim=768),
knowledge_graph=ContextGraph(),
decision_tracking=True,
advanced_analytics=True,
graph_expansion=True,
hybrid_alpha=0.7
)
Key initialization parameters:
vector_store(required): The embedding storage backend used for similarity search.knowledge_graph(optional): Enables GraphRAG retrieval and graph-based analytics.decision_tracking(optional): Activates decision lifecycle management and causal analysis.advanced_analytics(optional): Enables knowledge graph analytics including centrality and community detection.graph_expansion(optional): Allows multi-hop graph expansion during retrieval operations.
Storing Memories and Documents
The store() method in semantica/context/agent_context.py automatically inspects input types to distinguish between single memories (strings) and document batches (lists). It additionally supports automatic entity and relationship extraction when a knowledge graph is present.
# Store a single memory with metadata
mem_id = ctx.store(
"User asked about loan eligibility",
conversation_id="conv_42",
user_id="alice"
)
# Store documents with automatic entity extraction
doc_stats = ctx.store(
["Doc about cybersecurity", "Doc about network topology"],
extract_entities=True,
extract_relationships=True
)
When extract_entities=True and a knowledge graph is configured, the method extracts entities and relationships from the content before storage, enriching the graph structure for future retrieval operations.
Retrieving Context with Hybrid Search
The retrieve() method automatically selects between pure vector search and hybrid GraphRAG based on the presence of a knowledge graph. Developers can override this behavior using the use_graph=False parameter to force vector-only retrieval.
Pure Vector Retrieval
Without graph expansion, the method queries the underlying AgentMemory instance (managed internally in semantica/context/agent_memory.py) for semantically similar content.
results = ctx.retrieve(
"What credit score is needed for a mortgage?",
max_results=5,
use_graph=False
)
Hybrid Graph-Augmented Retrieval
When knowledge_graph is present and expand_graph=True, the method employs the ContextRetriever class from semantica/context/context_retriever.py to perform hybrid retrieval combining vector similarity with graph traversal.
results = ctx.retrieve(
"What are the common attack vectors?",
max_results=5,
expand_graph=True,
anchor_node="attack_vectors",
proximity_weight=0.4
)
Proximity metadata: When supplying an anchor_node, results include hop distance from the anchor, confidence decay metrics, and a combined score blending vector relevance with graph proximity. The proximity_weight parameter (0.0-1.0) controls the blend ratio between semantic similarity and graph proximity.
Tracking Decisions and Causal Chains
With decision_tracking=True, the AgentContext exposes methods for recording decisions, finding precedents, and analyzing causal influence through the knowledge graph.
Recording Decisions
The record_decision() method persists decisions to the graph with full provenance metadata:
decision_id = ctx.record_decision(
category="approval",
scenario="Mortgage Application",
reasoning="Applicant has 750 credit score, stable income",
outcome="approved",
confidence=0.96
)
Finding Precedents
The find_precedents_advanced() method performs knowledge graph-enhanced similarity searches to locate historically similar decisions:
precedents = ctx.find_precedents_advanced(
query="Mortgage Application",
category="approval",
use_kg_features=True
)
Analyzing Causal Influence
The analyze_decision_influence() method, implemented through semantica/context/causal_analyzer.py, traces causal chains through the knowledge graph to identify influencing factors:
influence_chain = ctx.analyze_decision_influence(decision_id)
Configuration Flags and Performance Tuning
The AgentContext class uses boolean flags to enable sophisticated features without API changes:
graph_expansion: Enables multi-hop traversal during retrieval, expanding context beyond immediate vector matches.hybrid_alpha: Controls the weighting between vector similarity and graph connectivity scores (range 0.0-1.0).advanced_analytics: Activates graph algorithms including centrality calculations and community detection on the knowledge graph.decision_tracking: Requires both this flag and a validknowledge_graphto instantiate the decision management subsystem.
Complete Working Example
The following implementation demonstrates a fully configured agent context with memory storage, hybrid retrieval, and decision tracking:
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissStore
from semantica.graph.context_graph import ContextGraph
# Initialize components
vector_store = FaissStore(dim=768)
knowledge_graph = ContextGraph()
# Create configured context
ctx = AgentContext(
vector_store=vector_store,
knowledge_graph=knowledge_graph,
decision_tracking=True,
advanced_analytics=True,
graph_expansion=True
)
# Store contextual data
ctx.store(["Document about AI safety guidelines"], extract_entities=True)
# Retrieve with graph enhancement
results = ctx.retrieve("Safety protocols", expand_graph=True)
# Record and analyze a decision
dec_id = ctx.record_decision(
category=" Risk Assessment",
scenario="AI Deployment",
reasoning="Model passes safety benchmarks",
outcome="proceed",
confidence=0.95
)
# Analyze influence
influence = ctx.analyze_decision_influence(dec_id)
# Persist entire context
ctx.save("/tmp/agent_context_snapshot")
Summary
- The
AgentContextclass insemantica/context/agent_context.pyunifies vector storage, knowledge graphs, and decision tracking into a single orchestration layer. - Flag-driven initialization enables advanced features like GraphRAG and causal analysis through simple boolean parameters.
- Automatic input detection in the
store()method handles both single memories and document batches, with optional entity extraction. - Hybrid retrieval automatically combines vector similarity with graph traversal when a knowledge graph is provided, controlled by
expand_graphandproximity_weightparameters. - Decision tracking requires both
decision_tracking=Trueand aknowledge_graphinstance, leveragingdecision_recorder.pyandcausal_analyzer.pyfor provenance management. - Lazy component initialization ensures minimal runtime overhead when advanced features are disabled.
Frequently Asked Questions
What is the difference between AgentMemory and AgentContext?
AgentMemory (defined in semantica/context/agent_memory.py) provides low-level CRUD operations for raw text storage and metadata management. AgentContext is the high-level orchestration class that wraps AgentMemory alongside ContextRetriever, knowledge graph interfaces, and decision tracking components, offering a unified API for complex agent architectures.
Can I use AgentContext without a knowledge graph?
Yes. The knowledge_graph parameter is optional. When omitted, AgentContext operates in pure vector retrieval mode using only the required vector_store. Advanced features like GraphRAG, entity linking, and decision tracking require a knowledge graph instance to function.
How does decision tracking work in AgentContext?
When initialized with decision_tracking=True and a valid knowledge graph, the class instantiates DecisionRecorder and CausalChainAnalyzer components. The record_decision() method persists decision metadata to the graph as structured nodes, while find_precedents_advanced() and analyze_decision_influence() query these structures to establish provenance chains and identify causal factors through graph traversal.
What file contains the main AgentContext implementation?
The primary implementation resides in semantica/context/agent_context.py. Supporting modules include semantica/context/agent_memory.py for low-level storage, semantica/context/context_retriever.py for hybrid retrieval logic, and semantica/context/decision_recorder.py for decision persistence. The public API exports these through semantica/context/__init__.py.
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 →