Semantica ContextGraph and AgentContext Interfaces: Architecture and Usage Guide
The Semantica codebase centers on two primary interfaces—ContextGraph, an in-memory knowledge graph with advanced analytics capabilities, and AgentContext, a high-level façade that unifies memory, retrieval, and decision tracking for AI agents.
The semantica-agi/semantica repository implements a modular knowledge-management layer designed for autonomous agent systems. At its foundation lie two critical interfaces that handle structured knowledge representation and agent-memory coordination: ContextGraph and AgentContext. These components enable hybrid vector-graph retrieval, decision precedent tracking, and causal analysis while remaining configurable through feature flags.
ContextGraph Architecture and Implementation
The ContextGraph interface serves as the core in-memory knowledge graph, storing entities, relationships, and decision records while providing advanced graph analytics capabilities.
Core Structure and Initialization
Defined in [semantica/context/context_graph.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_graph.py#L556-L564), the ContextGraph class initializes with optional knowledge-graph components when KG_AVAILABLE is detected. The constructor configures advanced analytics modules including:
- CentralityCalculator – Computes node importance metrics
- CommunityDetector – Identifies graph clusters
- NodeEmbedder – Generates vector representations of nodes
self.kg_components["centrality_calculator"] = CentralityCalculator()
self.kg_components["community_detector"] = CommunityDetector()
self.kg_components["node_embedder"] = NodeEmbedder()
The graph uses simple Python dictionaries and lists (self.nodes, self.edges) protected by a re-entrant lock (self._lock) for thread-safe operations.
Node and Edge Management
The interface provides validated insertion methods for graph construction. The add_nodes(nodes: List[Dict]) → int method (lines 662-735) handles ID extraction, type coercion, and metadata validation before creating internal ContextNode objects via _add_internal_node. Similarly, add_edges(edges: List[Dict]) → int validates edge payloads connecting source and target nodes.
Decision Recording and Analytics
ContextGraph maintains a comprehensive decision-tracking subsystem. The record_decision(...) method (lines 4321-4670) validates decision fields, normalizes timestamps, and stores records within the graph plus auxiliary indexes for fast retrieval.
For precedent analysis, find_precedents_by_scenario(...) (starting at line 4700) implements hybrid search combining semantic vector similarity with graph-based similarity metrics when a vector store is attached.
Additional capabilities include export/import operations via to_dict(), save_to_file(path), and load_from_file(path) for portable graph persistence.
AgentContext Architecture and Capabilities
The AgentContext interface, defined in [semantica/context/agent_context.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py#L90-L100), provides the high-level façade agents use to interact with memory systems and the ContextGraph.
Component Wiring and Configuration
The constructor (__init__, lines 90-140) wires together three sub-components based on configuration flags stored in self.config (lines 174-184):
- AgentMemory – Wraps the underlying vector store for standard RAG operations (lines 189-196)
- ContextRetriever – Performs hybrid retrieval combining vector similarity with graph expansion when a
knowledge_graphis supplied (lines 199-208) - Decision-tracking stack – Includes
DecisionRecorder,DecisionQuery,CausalChainAnalyzer, andPolicyEngineinstantiated whendecision_tracking=True(lines 231-237)
Feature flags such as advanced_analytics, kg_algorithms, graph_expansion, and decision_tracking provide fine-grained control over component activation.
Storage and Retrieval Operations
The store(content, ...) method auto-detects input types (conversation snippets or documents), extracts entities and relationships via EntityLinker, and persists data to AgentMemory while updating the ContextGraph with extracted knowledge.
For querying, retrieve(query, ...) dispatches to ContextRetriever, which may query the vector store, expand results via graph hops (controlled by max_expansion_hops), and blend scores using the hybrid_alpha parameter for unified ranking.
Decision Lifecycle Management
When record_decision(...) is invoked, the call forwards to the attached DecisionRecorder or directly to ContextGraph.record_decision when operating in graph-backend mode. The find_precedents_advanced(...) method utilizes DecisionQuery.find_precedents with optional KG-driven features enabled by the use_kg_features flag.
State persistence is handled through save(path) and load(path) (lines 308-340), which delegate to each component's serialization methods to preserve the complete agent state including memory, vector embeddings, and graph structure.
Practical Implementation Examples
Building and Querying a ContextGraph
from semantica.context import ContextGraph
# Create a graph with centrality analysis enabled
graph = ContextGraph(
advanced_analytics=True,
centrality_analysis=True,
community_detection=False,
)
# Add entities with properties
graph.add_nodes([
{"id": "Python", "type": "language", "properties": {"popularity": "high"}},
{"id": "Programming", "type": "concept"},
])
# Create relationships
graph.add_edges([
{"source": "Python", "target": "Programming", "type": "related_to"},
])
# Analyze node importance
centrality = graph.get_node_centrality("Python")
print("Python centrality:", centrality)
Referenced implementations: Class definition at lines 556-564, add_nodes at 662-735.
Recording Decisions in the Graph
decision_id = graph.record_decision(
category="loan_approval",
scenario="First-time home-buyer",
reasoning="Credit score 750, low debt-to-income",
outcome="approved",
confidence=0.96,
entities=["customer_123", "property_456"],
decision_maker="loan_officer_01",
)
print("Decision recorded with ID:", decision_id)
Implementation located at: lines 4321-4670.
Using AgentContext for Hybrid RAG
from semantica.context import AgentContext, ContextGraph
# Initialize components
vs = ... # Your vector store instance (e.g., Faiss, Qdrant)
kg = ContextGraph(advanced_analytics=True)
# Create high-level context
ctx = AgentContext(
vector_store=vs,
knowledge_graph=kg,
decision_tracking=True,
advanced_analytics=True,
kg_algorithms=True,
)
# Store conversation with entity extraction
mem_id = ctx.store(
"User asked how to install Python on Ubuntu.",
conversation_id="conv_001",
)
# Hybrid retrieval
results = ctx.retrieve("install Python Ubuntu")
print("Retrieved", len(results), "chunks")
# Track agent decisions
dec_id = ctx.record_decision(
category="installation",
scenario="Python on Ubuntu",
reasoning="Use apt package manager",
outcome="success",
confidence=0.9,
entities=["Ubuntu 22.04", "Python 3.11"],
)
# Find similar historical decisions
precedents = ctx.find_precedents_advanced(
"Install Python",
category="installation",
use_kg_features=True,
)
print("Found", len(precedents), "precedents")
Referenced implementations: AgentContext.__init__ at 90-140, component wiring at 190-250.
Summary
- ContextGraph provides the in-memory knowledge foundation with modular analytics (centrality, community detection, embeddings) and comprehensive decision tracking via
record_decision()andfind_precedents_by_scenario(). - AgentContext abstracts complexity by coordinating
AgentMemory,ContextRetriever, and decision-tracking components behind a unified API with configurable feature flags. - Both interfaces support state persistence through
save()/load()methods and integrate with shared observability infrastructure including logging and progress tracking. - The architecture supports Graph-RAG workflows through hybrid retrieval combining vector similarity with graph expansion hops.
Frequently Asked Questions
How do ContextGraph and AgentContext differ in purpose?
ContextGraph manages the raw knowledge representation—nodes, edges, and decision records—while providing graph analytics capabilities. AgentContext operates at a higher abstraction level, coordinating between the vector store, ContextGraph, and decision-tracking subsystems to provide agents with unified store(), retrieve(), and record_decision() methods.
Can I use AgentContext without enabling the knowledge graph features?
Yes. The AgentContext constructor accepts optional parameters including knowledge_graph, decision_tracking, and advanced_analytics. When knowledge_graph is omitted or advanced_analytics is set to False, the context operates in standard RAG mode using only AgentMemory and the vector store without graph expansion or KG analytics.
What threading guarantees does ContextGraph provide?
ContextGraph protects its internal state (self.nodes, self.edges) using a re-entrant lock (self._lock), ensuring thread-safe operations for concurrent node and edge modifications. However, external vector store interactions and component-level operations depend on the thread-safety guarantees of the underlying stores.
Where are decision records physically stored when using AgentContext?
Decision records persist within the attached ContextGraph instance when decision_tracking=True, specifically through the DecisionRecorder component or direct calls to ContextGraph.record_decision(). The graph maintains auxiliary indexes for fast precedent lookups, enabling find_precedents_advanced() to perform hybrid semantic and structural similarity searches.
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 →