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
  • DecisionRecorder — Records decisions with causal chains and confidence scores
    • Temporal validity windows (valid_from / valid_until)
    • Cross-system context capture on every decision
  • 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_alpha and 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

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

Set retention_days to avoid memory bloat. The default of 30 prunes automatically. Compliance-critical agents may need retention_days=None with explicit archival via export().
Persist your context between runs. VectorStore does not auto-persist — passing index_path= to its constructor is a no-op. Call context.save("agent_state/") to write memory, the vector index, and the graph to disk, and context.load("agent_state/") on the next process to restore them. See the “Persist & Restore” tab under Real-World Patterns below.

Memory Methods

retrieve() uses max_results=, not top_k=. The parameter is max_results (default 5). Pass use_graph=True to force GraphRAG or use_graph=False to force vector-only retrieval regardless of whether a knowledge_graph is configured.

Conversation Methods

Multi-Hop GraphRAG

Requires knowledge_graph to be set at construction: enables query_with_reasoning() for LLM-grounded multi-hop traversal:

Decision Methods

decision_tracking=True requires knowledge_graph to also be set. Without it, record_decision() raises RuntimeError.
Use find_precedents() before every significant decision. This is how the context module prevents agents from making contradictory choices across runs. Surface precedents to the LLM as context: “we chose X for similar reasons before.”

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

Pass include_distance_metadata=True to get_neighbors() to receive distance band, confidence decay, and path information alongside every neighbor:

Proximity-Blended Retrieval

Set proximity_weight on AgentContext to blend graph proximity into every retrieve() and find_precedents() call:
proximity_weight=0.0 disables proximity blending entirely (pure semantic). proximity_weight=1.0 returns results ranked purely by graph proximity to the query anchor. Values between 0.20.4 work well for most production use cases.

Cross-Graph Navigation

Link multiple independent ContextGraph 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:
The required frontmatter fields are 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 symbolic links and uses atomic file replacement. 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.

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:
EntityLinker.link_entities() links two entity IDs, not a list. Call link_entities(entity1_id, entity2_id, link_type) to create a typed edge between two known IDs. For linking entities extracted from text, use link(text, entities=[...]) instead.
LinkedEntity fields returned by link():

ContextRetriever

Hybrid retrieval combining vector similarity, graph traversal, and memory:

Data Structures

Real-World Patterns