# How to Implement AgentContext for Agent Memory Workflows in Semantica

> Implement AgentContext for agent memory workflows in Semantica. Store, retrieve, and track decisions with vector stores and knowledge graphs for robust AI memory.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-20

---

**Implement `AgentContext` by instantiating it with a `vector_store` and an optional knowledge graph, then call `store()` to persist memories, `retrieve()` for auto-detected GraphRAG or simple vector search, and enable `decision_tracking=True` for full provenance and checkpointing.**

The `AgentContext` class in the `semantica-agi/semantica` repository is the high-level façade that coordinates memory storage, hybrid retrieval, decision provenance, and graph versioning for AI agents. Whether you are building a conversational assistant or an autonomous reasoning system, this single class exposes an ergonomic API that hides the complexity of vector databases, knowledge graphs, and temporal checkpointing. Learning how to implement `AgentContext` for agent memory workflows is the fastest way to production-grade RAG and GraphRAG in the Semantica framework.

## Core Architecture of AgentContext

In [`semantica/context/agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py), the `AgentContext` class glues together several specialized subsystems. It does not store data itself; instead, it delegates to layered components that each handle a distinct concern.

### Vector Store and Memory Layer

Any compatible vector store (e.g., FAISS, PGVector) passed as `vector_store` is exposed through `self.vector_store` and consumed by `AgentMemory` for plain RAG. `AgentMemory` (defined in [`semantica/context/agent_memory.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_memory.py)) is initialized as `self._memory` inside `AgentContext.__init__`. All `store`, `retrieve`, `forget`, and `conversation` calls delegate to this layer.

### Knowledge Graph and ContextRetriever

When you supply a graph implementing the `ContextGraph` API (e.g., Neo4j or in-memory), `AgentContext` creates a `ContextRetriever` at `self._retriever` and a graph builder at `self._graph_builder`. The `ContextRetriever` (in [`semantica/context/context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py)) chooses between pure vector retrieval and hybrid GraphRAG. The `retrieve` method auto-detects strategy via a `use_graph` flag and returns normalized dictionaries through `_context_to_dict` and `_memory_to_dict`.

### Decision Tracking and Checkpointing

If `decision_tracking=True` and a graph is present, `AgentContext` initializes `DecisionRecorder`, `DecisionQuery`, `CausalChainAnalyzer`, and `PolicyEngine`. Internal methods `checkpoint`, `diff_checkpoints`, and `flush_checkpoint` (around line 1890 of [`agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/agent_context.py)) capture graph snapshots and persist them through `TemporalVersionManager` in [`semantica/change_management/temporal_version_manager.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/change_management/temporal_version_manager.py).

## Instantiating AgentContext

Create an `AgentContext` by providing at minimum a vector store. Pass a `knowledge_graph` to enable GraphRAG, and set feature flags such as `decision_tracking` to activate specific subsystems.

```python
from semantica.context import AgentContext
from semantica.vector_store.faiss_store import FaissVectorStore
from semantica.graph.context_graph import ContextGraph

vector_store = FaissVectorStore(dim=768)
knowledge_graph = ContextGraph()

ctx = AgentContext(
    vector_store=vector_store,
    knowledge_graph=knowledge_graph,
    retention_days=60,
    decision_tracking=True,
)

```

## Storing Data in Agent Memory Workflows

The `store()` method auto-detects whether the payload is a single memory string or a list of documents. For memories, it forwards to `AgentMemory.store`. For document batches, it also triggers graph construction through `_build_graph_from_documents`.

### Storing a Single Memory

```python
mem_id = ctx.store(
    "User asked about the weather in Paris",
    conversation_id="conv-42",
    user_id="alice",
)

```

### Storing Document Batches with Graph Extraction

```python
doc_stats = ctx.store(
    [
        {"content": "Paris is the capital of France.", "metadata": {"source": "wiki"}},
        {"content": "The weather in Paris is typically mild.", "metadata": {"source": "weather.com"}},
    ],
    extract_entities=True,
    extract_relationships=True,
)
print(doc_stats)  # → {'stored_count': 2, 'graph_nodes': 4, 'graph_edges': 3, …}

```

## Retrieving Context with Auto-Detected GraphRAG

The `retrieve()` method decides at runtime whether to use GraphRAG or simple vector search. If a graph is available, it calls `self._retriever.retrieve` from `ContextRetriever`, which performs hybrid vector plus graph expansion and returns `RetrievedContext` objects. Otherwise, it falls back to `self._memory.retrieve`.

```python
results = ctx.retrieve(
    "What is the typical weather in the French capital?",
    max_results=5,
    include_entities=True,
)
for r in results:
    print(r["content"], r["score"])

```

## Tracking Decisions and Policy Enforcement

When `decision_tracking` is enabled, `AgentContext` exposes the full decision lifecycle. You can record outcomes, query precedents, and analyze causal chains without interacting with the underlying graph directly.

```python

# Record a decision

dec_id = ctx.record_decision(
    category="approval",
    scenario="Loan application #12345",
    reasoning="Credit score > 700 and stable income",
    outcome="approved",
    confidence=0.93,
)

# Find similar past decisions using enhanced KG search

precedents = ctx.find_precedents_advanced(
    "Loan application",
    category="approval",
    use_kg_features=True,
)

# Analyse causal influence

causal_chain = ctx.get_causal_chain(dec_id, direction="upstream")

```

## Checkpointing and Versioning Graph State

Use `checkpoint(label)` to capture a snapshot of the current graph state, `diff_checkpoints` to compute structural deltas, and `flush_checkpoint` to persist the snapshot through `TemporalVersionManager`.

```python

# Capture a snapshot

ctx.checkpoint("pre-policy-update")

# ... make changes to the graph ...

# Compute diff

diff = ctx.diff_checkpoints("pre-policy-update", "post-policy-update")
print(diff["decisions_added"])

# Persist the snapshot

ctx.flush_checkpoint("pre-policy-update")

```

## Utility Operations for Memory Management

`AgentContext` also provides helpers for listing, deleting, and clearing stale memories.

```python

# List recent memories

recent = ctx.list(conversation_id="conv-42", limit=10)

# Delete a memory

ctx.delete(mem_id)

# Clear all memories older than 90 days

ctx.clear(days_old=90)

```

## Summary

- **AgentContext** ([`semantica/context/agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py)) is the central façade that coordinates memory, retrieval, decision tracking, and checkpointing.
- **AgentMemory** ([`semantica/context/agent_memory.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_memory.py)) handles raw vector storage, while **ContextRetriever** ([`semantica/context/context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py)) enables hybrid GraphRAG when a knowledge graph is supplied.
- `store()` auto-detects strings versus document lists and can trigger entity and relationship extraction via `_build_graph_from_documents`.
- `retrieve()` automatically selects between simple RAG and GraphRAG based on graph availability and the internal `use_graph` flag.
- Decision tracking requires `decision_tracking=True` and a graph backend; it surfaces methods such as `record_decision`, `find_precedents_advanced`, and `get_causal_chain`.
- Checkpoints use `checkpoint`, `diff_checkpoints`, and `flush_checkpoint` to snapshot, compare, and persist graph state through `TemporalVersionManager`.

## Frequently Asked Questions

### What is the difference between AgentMemory and AgentContext?

`AgentMemory` (in [`semantica/context/agent_memory.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_memory.py)) is the low-level storage layer for raw memories and vector embeddings. `AgentContext` is the high-level façade that wraps `AgentMemory`, a `ContextRetriever`, optional decision trackers, and checkpointing logic into a single ergonomic API.

### When should I enable decision_tracking in AgentContext?

Enable `decision_tracking=True` when you need to record agent decisions, query historical precedents, analyze causal chains, or enforce policies over outcomes. This subsystem initializes `DecisionRecorder`, `DecisionQuery`, `CausalChainAnalyzer`, and `PolicyEngine`, but it requires a knowledge graph to be present.

### How does AgentContext choose between GraphRAG and simple vector retrieval?

The `retrieve()` method checks whether a knowledge graph and retriever exist. If so, it calls `self._retriever.retrieve` from `ContextRetriever` for hybrid graph expansion; otherwise it delegates to `self._memory.retrieve` for pure vector similarity. You can influence this behavior via flags such as `include_entities`.

### What storage backends work with AgentContext?

For the vector layer, you can pass any compatible store such as `FaissVectorStore` or `PGVector`. For the optional knowledge graph, use any implementation of the `ContextGraph` API, including Neo4j or the in-memory `ContextGraph`. Checkpointing requires `TemporalVersionManager` from [`semantica/change_management/temporal_version_manager.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/change_management/temporal_version_manager.py).