How to Use AgentContext for Storing and Retrieving Information in Semantica
Call AgentContext.store() to persist text, documents, or decisions to the vector store and memory, then use AgentContext.retrieve() to query them with configurable hybrid (vector + graph) search.
The AgentContext class serves as the primary interface for memory management in the semantica-agi/semantica framework. It abstracts the complexity of vector stores, knowledge graphs, and retrieval algorithms into simple methods for storing and retrieving information. By composing specialized components like AgentMemory and ContextRetriever, the class enables both basic persistence and advanced GraphRAG workflows without exposing underlying implementation details.
Initializing AgentContext
Before storing or retrieving data, instantiate the class with a vector store and optional knowledge graph. Boolean flags activate advanced features such as decision tracking and graph analytics.
from semantica.context import AgentContext
# Basic initialization with only vector storage
ctx = AgentContext(vector_store=my_vector_store)
# Advanced initialization with knowledge graph and decision tracking
ctx = AgentContext(
vector_store=my_vector_store,
knowledge_graph=my_kg,
decision_tracking=True,
kg_algorithms=True,
graph_expansion=True,
hybrid_alpha=0.6 # 60% graph weight, 40% vector weight
)
Storing Information with store()
The store() method in semantica/context/agent_context.py accepts raw text or document objects and automatically detects the content type. It delegates persistence to AgentMemory while extracting entities and relationships when a knowledge graph is present.
# Store a user utterance as a memory entry
mem_id = ctx.store(
"User asked about the benefits of Python decorators",
conversation_id="conv_42",
metadata={"topic": "python", "complexity": "intermediate"}
)
# Store returns a unique identifier for later reference
print(f"Stored with ID: {mem_id}")
For structured decision records, use the dedicated record_decision() method when decision_tracking is enabled. This writes to DecisionRecorder and links the decision to the knowledge graph for provenance tracking.
decision_id = ctx.record_decision(
category="approval",
scenario="Loan application",
reasoning="Applicant has strong credit history",
outcome="approved",
confidence=0.94
)
Retrieving Information with retrieve()
The retrieve() method performs hybrid retrieval, combining semantic similarity from the vector store with structural cues from the knowledge graph. It delegates the actual query execution to ContextRetriever, which blends scores based on the hybrid_alpha parameter (0.0 = pure vector, 1.0 = pure graph).
# Retrieve relevant context for a new query
results = ctx.retrieve(
"Explain how decorators work in Python",
top_k=5,
graph_expansion=True # Follow graph edges to expand context
)
for hit in results:
print(f"Content: {hit['content']}")
print(f"Score: {hit['metadata']['score']}")
Advanced Decision Analytics
When decision_tracking=True, the context exposes additional methods powered by DecisionQuery and CausalChainAnalyzer. These enable governance workflows such as finding precedent decisions and analyzing causal influence chains.
# Find similar past decisions using KG-enhanced features
precedents = ctx.find_precedents_advanced(
query="Loan application",
category="approval",
use_kg_features=True,
top_k=10
)
# Analyze the causal influence of a specific decision
influence = ctx.analyze_decision_influence(decision_id)
print(f"Decision influenced {len(influence['downstream'])} subsequent actions")
Key Source Files
The storing and retrieving pipeline is implemented across the following modules:
- [
semantica/context/agent_context.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py) – Central class exposingstore(),retrieve(), and decision-tracking APIs. - [
semantica/context/agent_memory.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_memory.py) – Implements memory persistence, retention policies, and basic vector-store interactions. - [
semantica/context/context_retriever.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py) – Handles hybrid RAG/GraphRAG queries, graph expansion, and score blending. - [
semantica/context/decision_recorder.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/decision_recorder.py) – Records decisions and metadata into the knowledge graph. - [
semantica/context/decision_query.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/decision_query.py) – Provides enriched search over decisions using knowledge graph algorithms. - [
semantica/context/causal_analyzer.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/causal_analyzer.py) – Analyzes decision causality and influence chains. - [
semantica/context/policy_engine.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/policy_engine.py) – Enforces governance policies on stored decisions.
Summary
- Initialize
AgentContextwith avector_storeand optionalknowledge_graphto enable storage and retrieval. - Store raw text or documents using
store(), which automatically handles content detection and entity extraction. - Retrieve relevant context using
retrieve(), tuning thehybrid_alphaandgraph_expansionparameters to balance vector similarity against graph structure. - Track decisions by setting
decision_tracking=Trueand usingrecord_decision()for full provenance and causal analysis.
Frequently Asked Questions
What is the difference between store() and record_decision() in AgentContext?
The store() method is designed for general text and document persistence, automatically routing data to AgentMemory and the vector store. The record_decision() method is a specialized interface for governance workflows that writes structured decision metadata to DecisionRecorder and links decisions into the knowledge graph for provenance tracking and causal analysis.
How does hybrid retrieval balance vector search and graph traversal?
Hybrid retrieval is implemented in ContextRetriever using the hybrid_alpha parameter. A value of 0.0 weights results purely by vector embedding similarity, while 1.0 weights purely by graph connectivity and centrality. Intermediate values blend both scores to surface contextually relevant information that is both semantically similar and structurally significant within the knowledge graph.
Is a knowledge graph required to use AgentContext?
No. The knowledge_graph parameter is optional. If omitted, AgentContext operates in vector-only mode, using AgentMemory for storage and standard semantic search for retrieval. Knowledge graph features like graph_expansion and kg_algorithms are automatically disabled when no graph is provided.
Which file handles the actual vector storage operations?
Vector storage operations are delegated to AgentMemory in semantica/context/agent_memory.py. This module manages the persistence layer, retention policies, and basic CRUD operations for the vector store backend, while AgentContext provides the high-level orchestration.
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 →