Agent Memory Workflows Using AgentContext in Semantica: A Complete Technical Guide
AgentContext is the high-level façade that unifies vector storage, GraphRAG retrieval, knowledge graph integration, and decision tracking into a single ergonomic API for managing agent memory in the Semantica framework.
Agent memory workflows using AgentContext in Semantica provide a unified interface for orchestrating long-term memory, context retrieval, and explainable decision-making. As implemented in the semantica-agi/semantica repository, this central component abstracts the complexity of vector stores, knowledge graphs, and causal analysis behind a single Python class. Whether building conversational agents or complex reasoning systems, understanding AgentContext is essential for implementing production-grade memory management.
Core Architecture of AgentContext
The AgentContext class in semantica/context/agent_context.py serves as the central orchestrator, instantiating four specialized subsystems during initialization:
| Component | Role | Initialization Location |
|---|---|---|
| AgentMemory | Handles raw memory storage, vector embeddings, CRUD operations, and simple vector-only retrieval. | Lines 24-31 via __init__ |
| ContextRetriever | Implements GraphRAG—hybrid retrieval fusing vector similarity with knowledge-graph expansion. | Lines 97-104 when knowledge_graph is provided |
| Knowledge Graph | Optional storage for entities, relationships, and conversation-derived graph structures enabling entity linking and analytics. | Lines 70-76 via __init__ |
| Decision-Tracking Stack | Records decisions, searches precedents, and performs causal-chain analysis when decision_tracking=True. |
Lines 122-144 conditionally |
These components are exposed through a unified API that automatically selects the optimal retrieval strategy at runtime.
Initializing the Context
The constructor validates required dependencies and wires internal objects. A vector store is mandatory, while a knowledge graph enables advanced GraphRAG capabilities.
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissStore
from semantica.kg.context_graph import ContextGraph
# Required: vector store with embedding function
vs = FaissStore(embedding_fn=my_embedder)
# Optional: knowledge graph for hybrid retrieval
kg = ContextGraph()
context = AgentContext(
vector_store=vs,
knowledge_graph=kg,
retention_days=30,
max_memories=10000,
decision_tracking=True,
advanced_analytics=True,
)
As shown in lines 62-66 of agent_context.py, the constructor validates the vector store before proceeding to instantiate internal components.
Storing Content: Memories vs. Documents
The store() method handles heterogeneous input types, delegating to specialized processing paths:
- Single strings are treated as raw memories and passed directly to
AgentMemory.store(lines 28-34). - Lists of strings or dictionaries are normalized via
_normalize_documents(lines 148-175) before vector storage. - When a knowledge graph is present and
extract_entities=True, the method invokes_build_graph_from_documents(lines 176-184) to populate graph nodes and edges.
# Store a single memory
mem_id = context.store(
"User asked how to unzip a file in Linux",
conversation_id="conv_42",
user_id="alice"
)
# Store structured documents with automatic KG extraction
docs = [
{"content": "Python list comprehensions create new lists.", "metadata": {"topic": "python"}},
{"content": "FAISS enables fast similarity search.", "metadata": {"topic": "vectors"}}
]
stats = context.store(docs, extract_entities=True, link_entities=True)
# Returns: {'stored_count': 2, 'node_count': ..., 'edge_count': ...}
Hybrid Retrieval with GraphRAG
The retrieve() method implements automatic strategy selection. If a knowledge_graph and ContextRetriever exist, it executes GraphRAG; otherwise, it falls back to vector-only search via AgentMemory.retrieve (lines 49-51).
Results are transformed into plain dictionaries using _context_to_dict (lines 216-224) and optionally enriched with proximity metadata via _apply_proximity_metadata (lines 236-260) when graph features are enabled.
results = context.retrieve(
"How can I efficiently search for similar Python snippets?",
max_results=5,
include_entities=True
)
for result in results:
print(f"Content: {result['content']}, Score: {result['score']}")
Managing Conversation History and Forgetting
The context provides fine-grained lifecycle management for temporal data. The forget() method removes memories by ID, conversation, user, or age (lines 54-71), while conversation() returns chronologically ordered slices of specific dialogue threads (lines 77-84).
# Remove memories older than 7 days for a specific user
context.forget(older_than_days=7, user_id="alice")
# Retrieve full history of a conversation
history = context.conversation(conversation_id="conv_42", max_results=50)
Entity Linking and Graph Building
When a knowledge graph is configured, AgentContext exposes direct graph manipulation capabilities. The link() method wraps EntityLinker (lines 81-88) to match text spans against KG entities using configurable similarity thresholds.
The build_graph() method forwards to the graph's construction methods (lines 100-108), enabling programmatic graph population from extracted entities and relationships.
# Link entities in free-form text
linked_entities = context.link(
"I used pandas to read a CSV and plotted with matplotlib.",
similarity_threshold=0.85
)
# Build graph from structured data
context.build_graph(
entities=[{"id": "e1", "type": "Library", "name": "pandas"}],
relationships=[{"source": "e1", "target": "e2", "type": "uses"}]
)
Decision Tracking and Causal Analysis
When initialized with decision_tracking=True, the context activates a full decision-intelligence pipeline. This subsystem includes DecisionRecorder, DecisionQuery, CausalChainAnalyzer, and PolicyEngine (lines 122-144).
record_decision()persists structured decisions with full contextual metadata.find_precedents()andfind_precedents_advanced()query the KG-augmented vector store for similar historical decisions.analyze_decision_influence()traces upstream and downstream causal effects usingCausalChainAnalyzer.
# Record a decision
decision_id = context.record_decision(
category="approval",
scenario="Loan application",
reasoning="High credit score",
outcome="approved",
confidence=0.97
)
# Find similar precedents using KG features
precedents = context.find_precedents_advanced(
query="Loan application",
category="approval",
use_kg_features=True
)
Persistence and State Management
The save() and load() methods serialize the complete agent state—including vector store contents, knowledge graph structure, and decision history—to disk. This enables checkpointing and restoration of long-running agent sessions.
# Save complete state
context.save("./agent_snapshot")
# Later: restore exact state
context.load("./agent_snapshot")
Summary
- AgentContext in
semantica/context/agent_context.pyprovides a unified façade for all memory operations in the Semantica framework. - The class automatically selects between vector-only retrieval (via
AgentMemory) and GraphRAG (viaContextRetriever) based on initialization parameters. - Knowledge graph integration is optional but enables entity linking, graph expansion, and enhanced proximity metadata during retrieval.
- Decision tracking adds explainability through structured recording, precedent search, and causal chain analysis when enabled via constructor flags.
- All subsystems support full serialization through
save()andload()methods for production deployment.
Frequently Asked Questions
What is the difference between AgentMemory and ContextRetriever in Semantica?
AgentMemory provides low-level storage and vector-similarity retrieval for raw text memories, handling CRUD operations and basic statistics. ContextRetriever implements GraphRAG—hybrid retrieval that combines vector similarity with knowledge-graph expansion for multi-hop reasoning. According to the source code in semantica/context/agent_context.py, the retrieve() method automatically delegates to ContextRetriever when a knowledge graph exists (lines 49-51), otherwise falling back to AgentMemory.
How does AgentContext handle knowledge graph integration during document storage?
When storing documents with extract_entities=True, AgentContext normalizes inputs via _normalize_documents (lines 148-175) and then invokes _build_graph_from_documents (lines 176-184) to extract entities and relationships. These are persisted to the knowledge graph instance provided during initialization, updating node and edge counts returned in the storage statistics payload.
Can AgentContext track decisions without a knowledge graph?
Yes, but with limited functionality. The decision-tracking stack (DecisionRecorder, DecisionQuery, CausalChainAnalyzer) is initialized when decision_tracking=True (lines 122-144), but advanced features like find_precedents_advanced() and graph-based causal analysis require the knowledge graph to be present. Basic decision recording and simple precedent queries function with vector storage alone.
How do I persist and restore an agent's complete memory state?
Use the save() method to serialize the vector store, knowledge graph, and decision history to a specified directory. The load() method restores the exact state, allowing you to resume agent operations with full memory intact. This is implemented in semantica/context/agent_context.py and enables production workflows requiring session continuity across restarts.
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 →