semantica.context is the memory and decision layer for AI agents:
- Stores facts with provenance and embedding-backed retrieval
- Records decisions as first-class graph objects with full causal chains
- Lets agents search their own history to stay consistent across runs
- Answers complex queries via multi-hop GraphRAG traversal
- Enforces versioned policies and tracks compliance exceptions
Exported Classes
What You Get
- AgentContext: memory, decision tracking, and graph-backed retrieval behind one API
- Conversation history and checkpoint diffing
- Persist and restore full context state to disk
- ContextGraph: thread-safe in-memory knowledge graph
- PageRank, centrality, community detection, temporal validity
- Cross-graph navigation and link traversal
- AgentMemory: embedding-backed memory with retention policy
- LRU eviction at configurable
max_memory_size - Per-conversation history isolation
- LRU eviction at configurable
- DecisionRecorder: records decisions with causal chains and confidence scores
- Temporal validity windows (
valid_from/valid_until) - Cross-system context capture on every decision
- Temporal validity windows (
- PolicyEngine: versioned policy storage in the knowledge graph
- Compliance checking against recorded decisions
- Policy exception tracking with approver audit trail
- EntityLinker: maps entity text to stable URIs
- Creates typed links between entity IDs
- Prevents “Apple”, “Apple Inc.”, “AAPL” becoming separate nodes
- ContextRetriever: fuses vector similarity, graph traversal, and agent memory
- Richer context than pure vector search
- Configurable
hybrid_alphaand expansion hops
- CausalChainAnalyzer: traces upstream causes and downstream effects of any decision
- Explainability paths with relationship types
- Configurable depth and direction
Quick Start
1
Initialize the agent context
2
Store facts and retrieve by semantic similarity
3
Record decisions with full provenance
4
Find precedents and trace causal chains
Usage Patterns
- Vector Memory Only
- Full Agent Context
- GraphRAG Query
- Policy Enforcement
Fastest setup: no knowledge graph. Best for agents that need semantic search over facts without graph traversal overhead.
Swap
backend="faiss" to backend="inmemory" for zero-dependency local development.AgentContext
AgentContext is the main entry point. Wraps memory, graph, and decision tracking behind a single unified API.
Constructor Parameters
Memory Methods
Conversation Methods
Multi-Hop GraphRAG
Requiresknowledge_graph to be set at construction: enables query_with_reasoning() for LLM-grounded multi-hop traversal:
Decision Methods
Checkpoint Methods
Ideal for auditing reasoning loops: take a snapshot before and after a pass to see exactly what changed:ContextGraph
ContextGraph is the knowledge graph backing AgentContext. Can also be used standalone for relationship modelling without the full context layer.
Constructor Options
ContextGraph: Full Method Reference
Distance Intelligence (v0.5.0)
ContextGraph exposes a full Distance Intelligence API for exploring semantic neighborhoods and blending proximity into retrieval.
Full Distance Intelligence reference (distance matrices, API endpoints, embedding cache, Explorer UI) is covered in the dedicated Distance Intelligence page. This section documents the context-layer API.
Neighbors with Distance Metadata
Passinclude_distance_metadata=True to get_neighbors() to receive distance band, confidence decay, and path information alongside every neighbor:
Proximity-Blended Retrieval
Setproximity_weight on AgentContext to blend graph proximity into every retrieve() and find_precedents() call:
Cross-Graph Navigation
Link multiple independentContextGraph instances so agents can traverse across problem spaces:
AgentMemory
For fine-grained control over memory storage and retrieval:Markdown Round Trips
AgentMemory can export human-editable Markdown and import the edited files back.
Each file contains one memory item, with required metadata in YAML frontmatter and
the memory content in the Markdown body:
id, created_at, updated_at, and either
type or kind. Optional metadata can be edited at the top level. Imports reject
malformed or duplicate fields before changing memory, and re-importing unchanged
files is idempotent. Memory-local entities and relationships are preserved as
provenance but are not applied to ContextGraph by Markdown import. Use a dedicated
export directory: matching files are overwritten, but unrelated or stale Markdown
files are not deleted automatically. Export refuses to overwrite filesystem links and
uses atomic file replacement; import also refuses symlinks, Windows directory
junctions, and other Windows reparse points.
Timestamp offsets are preserved in Markdown and
normalized to UTC only for comparisons, so aware and local-naive records can be
queried together safely. Vector-store writes are deferred until the in-memory import
commits; adapter synchronization remains best-effort and logs failures.
ErasureCoordinator
ContextGraph.purge_node() is scoped to one graph: the node is removed and a
tombstone is written, but the same content can still be live as an AgentMemory
item and as an embedding in the vector store. ErasureCoordinator drives the
cascade across every bound store and returns an ErasureReceipt recording what
each one reported.
Constructor Parameters
At least one store is required; a store that is not supplied reports
not_configured rather than being silently skipped.
Methods
Store Statuses
ErasureReceipt
failed and the remaining stores are still erased. Erasing the same entity
twice returns a receipt saying there was nothing left to do rather than raising.
PolicyEngine
PolicyEngine manages versioned policies stored in the knowledge graph. Policies are stored as nodes and can be linked to decisions:
EntityLinker
Maps entity text to URIs and creates typed links between entity IDs:LinkedEntity fields returned by link():
ContextRetriever
Hybrid retrieval combining vector similarity, graph traversal, and memory:Support-Aware Retrieval (truth_filter)
Cached vector or memory content can outlive the evidence that originally
supported it. ContextRetriever.retrieve(..., truth_filter=...) accepts an
opt-in TruthMaintenanceContextFilter that removes candidates whose declared
dependencies are no longer supported, before ranking, while the stored
records themselves are never modified.
The example below runs standalone with no model, database, or network —
only semantica itself:
Manual annotation semantics
The filter only validates what the application explicitly wrote into store metadata. It never infers dependencies, and it never annotates records on your behalf:- Each candidate must carry
metadata["truth_maintenance"]with exactly four keys:schema_version(currently1),session_id(must equal the filter’ssession_id),required_facts, andrequired_support_ids. At least one fact or support ID must be declared. - A candidate is kept only if every entry of
required_factsis in the snapshot’sfactsand every entry ofrequired_support_idsis in the snapshot’s active supports. Unannotated candidates and candidates with malformed annotations are removed whole — a record ID or node ID is never a trust signal.
Source-specific citations
Two records may assert the same conclusion but cite different sources.required_support_ids binds each record to the evidence it actually used, so
withdrawing one support invalidates only the records citing it, while records
backed by an alternative derivation or an explicit support are kept.
Graph bundles
For candidates retrieved from aContextGraph, the root record and every
member of related_entities / related_relationships must carry the same
annotation shape on their own metadata. If the root or any attachment is
unsupported, the entire candidate is excluded — a result never keeps its prose
while silently dropping a stale attachment.
Behavior details
- Filtering happens before ranking and before the legacy merge: a high-scoring stale record cannot crowd out valid lower-scoring records, and dependency metadata survives merging.
- Survivors are returned as deep copies stamped with
metadata["truth_maintenance_validation"](session_id,version). Original candidates and stored records are never modified. - Each call validates against one immutable snapshot; if the session commits
a new version while retrieval is in flight,
retrieveraisesProcessingErrorinstead of returning mixed-version results. - Vector, memory, and graph sources are filtered in the same pass: construct
the retriever with
memory_store=orknowledge_graph=and passtruth_filter=toretrieve, or to thesearch,vector_search, andgraph_searchdelegates (they forward toretrieve).memory_searchbypassesretrieveand does not apply the filter — useretrievewhen memory results must be grounded.
Unsupported entry points
The filter is supported only byContextRetriever.retrieve(mode="local", ...)
(the default mode) and delegates that use that path. Passing truth_filter to
retrieve with mode="global", "drift", or "hybrid" raises ValidationError
before retrieval starts. Those modes and direct retrieve_global /
retrieve_drift calls are outside the dependency-validation guarantee.
truth_filter is intentionally not accepted on AgentContext.retrieve,
AgentContext.query_with_reasoning, or ContextRetriever.query_with_reasoning
— passing it there raises ValidationError immediately. Assemble the
verified context yourself with ContextRetriever.retrieve(..., truth_filter=...) and feed it to the model.
See Truth Maintenance for the session model
behind the filter.
Data Structures
Decision
Decision
Precedent
Precedent
Policy
Policy
PolicyException
PolicyException
ApprovalChain
ApprovalChain
LinkedEntity
LinkedEntity
Real-World Patterns
- Healthcare: Treatment Decisions
- Finance: Loan Decisions
- Persist & Restore
- Vector Store: embedding storage backend for memory retrieval.
- Knowledge Graph: graph algorithms and analytics used inside ContextGraph.
- Reasoning: logical inference layered on top of context.
- Provenance: W3C PROV-O lineage for every stored fact.
- Context Module: memory and decision tracking · Intermediate
- Advanced Context Engineering: production FAISS + Neo4j setup · Advanced
