How to Implement RAG with ContextGraph Using AgentContext for Agent Memory in Semantica
To implement RAG with ContextGraph in Semantica, instantiate AgentContext with a vector store and optional ContextGraph, then use store() to index memories and retrieve() to execute hybrid vector-graph retrieval with configurable hop expansion.
The semantica-agi/semantica framework provides a sophisticated context management system that enables Retrieval-Augmented Generation (RAG) through graph-aware memory structures. By combining vector storage with an in-memory knowledge graph, you can implement advanced RAG patterns that go beyond simple similarity search. This guide demonstrates how to implement RAG with ContextGraph using AgentContext for agent memory in Semantica, leveraging the framework's hybrid retrieval capabilities according to the actual source implementation.
Core Architecture Components
AgentMemory
Located in semantica/context/agent_memory.py, AgentMemory serves as the vector storage interface that indexes raw text fragments. It handles the persistence of memories and their vector embeddings, acting as the foundation for semantic search. This component is instantiated inside AgentContext.__init__ (lines 86-96 in semantica/context/agent_context.py) when you initialize the high-level façade.
ContextGraph
The ContextGraph class in semantica/context/context_graph.py (lines 4-30) manages an in-memory graph store containing nodes, edges, and temporal validity windows. It provides graph analytics including centrality calculations and community detection, enabling relationship-aware retrieval. The graph structure supports neighbor discovery via get_neighbors and cross-graph linking for modular agent architectures.
ContextRetriever
ContextRetriever executes the hybrid retrieval strategy that distinguishes Semantica from basic RAG implementations. Imported and constructed in AgentContext.__init__ (lines 98-108 in semantica/context/agent_context.py), it bridges vector similarity search with graph traversal, implementing the Graph-RAG logic that expands retrieval results through relationship walking.
How the RAG Pipeline Works
Storing Memories and Documents
When you call AgentContext.store(), the method automatically detects the content type and routing logic. For single string memories, it forwards the payload directly to AgentMemory.store (lines 28-45 in semantica/context/agent_context.py), which writes text to the vector store while recording any supplied entities and relationships.
For document lists, the system first stores each document via AgentMemory, then builds a ContextGraph from extracted entities and relationships if a knowledge_graph is supplied (lines 73-84 in semantica/context/agent_context.py). This dual-storage approach ensures both semantic searchability and relationship preservation.
Hybrid Retrieval with Graph Expansion
Calling AgentContext.retrieve() triggers auto-detection of the retrieval strategy. When a knowledge graph is present, the method delegates to ContextRetriever.retrieve (lines 48-58 in semantica/context/agent_context.py), which executes a three-step pipeline:
- Vector search — Queries the vector store via
AgentMemory.retrieveto obtain the top-k most similar memory vectors. - Graph expansion — For each hit, walks the
ContextGraphup tomax_expansion_hops(default 2) using BFS over neighbor edges viaContextGraph.get_neighbors(lines 78-86 insemantica/context/context_graph.py), optionally applying edge-weight thresholds. - Score blending — Re-scores the result set by blending vector similarity (
score) with proximity scores derived from hop distance (proximity_score), using the configurableproximity_weightparameter (default 0).
The method returns a list of dictionaries containing the retrieved content, sources, combined scores, and optional graph metadata including hop distance and confidence decay (lines 112-124 in semantica/context/agent_context.py).
Multi-hop Reasoning
For complex reasoning tasks, AgentContext.query_with_reasoning() invokes ContextRetriever.query_with_reasoning, which builds reasoning paths across the graph using ContextGraph.get_neighbor_distances. It assembles the retrieved context and hands it to an LLM provider (such as semantica.llms.Groq) to generate natural-language answers (lines 35-44 in semantica/context/agent_context.py).
Cross-Graph Linking for Modular Agents
The ContextGraph supports cross-graph links through the link_graph method, creating bridge nodes that enable traversal between separate graph instances. The cross_graph_path method facilitates "dream-within-a-dream" style navigation across modular agent contexts (lines 61-85 in semantica/context/context_graph.py), allowing agents to maintain separate knowledge domains while enabling inter-domain reasoning.
Complete Implementation Example
from semantica.context import AgentContext
# 1️⃣ Initialise vector store and optional knowledge graph
vector_store = MyVectorStore() # any Semantica‑compatible store
knowledge_graph = ContextGraph(advanced_analytics=True)
# 2️⃣ Build the high‑level AgentContext
ctx = AgentContext(
vector_store=vector_store,
knowledge_graph=knowledge_graph,
decision_tracking=False, # not needed for basic RAG
graph_expansion=True,
max_expansion_hops=2,
hybrid_alpha=0.5,
)
# 3️⃣ Store some memories and documents
ctx.store("User: I love Python.", conversation_id="conv1")
ctx.store(
["Document about Python data classes.", "Doc about asyncio."],
extract_entities=True,
extract_relationships=True,
)
# 4️⃣ Retrieve with hybrid RAG (graph expansion enabled)
results = ctx.retrieve(
"Explain how Python handles async IO",
max_results=5,
proximity_weight=0.3, # blend graph proximity into final score
)
for r in results:
print(f"▸ {r['content']}\n score={r['combined_score']:.2f} hop={r.get('hop_distance')}")
# 5️⃣ Optional reasoning + LLM generation
from semantica.llms import Groq
llm = Groq(model="llama-3.1-8b-instant")
answer = ctx.query_with_reasoning(
"What are the best practices for async programming in Python?",
llm_provider=llm,
max_hops=3,
)
print("\nLLM answer:", answer["response"])
Key implementation details:
- Step 2:
AgentContext.__init__creates anAgentMemoryinstance, aContextRetriever(only ifknowledge_graphis supplied), and stores configuration flags (lines 24-40 insemantica/context/agent_context.py). - Step 3:
ctx.storedetects the first payload as a memory (single string) →AgentMemory.store→ vector indexing. The second call receives a list → each doc is stored, thenContextGraph.build_from_conversationsbuilds nodes/edges from extracted entities (lines 46-60 insemantica/context/agent_context.py). - Step 4:
ctx.retrieveauto-detects that a graph is present, callsContextRetriever.retrieve, which runs a vector query, expands viaContextGraph.get_neighbors, and merges scores (lines 48-58 insemantica/context/agent_context.py). - Step 5:
query_with_reasoningroutes the request toContextRetriever.query_with_reasoning, which assembles a multi-hop reasoning trace and hands it to the LLM (lines 35-44 insemantica/context/agent_context.py).
Summary
- AgentContext in
semantica/context/agent_context.pyserves as the high-level façade that orchestrates vector storage, graph management, and hybrid retrieval. - ContextGraph enables graph-RAG capabilities through BFS expansion up to
max_expansion_hopsand cross-graph linking for multi-hop reasoning. - The retrieval pipeline automatically blends vector similarity with graph proximity scores using the configurable
proximity_weightparameter. - AgentMemory handles the vector store interface while ContextRetriever manages the hybrid retrieval logic that powers the Graph-RAG workflow.
Frequently Asked Questions
What is the difference between AgentMemory and ContextGraph in Semantica?
AgentMemory manages vector embeddings and semantic similarity search within the vector store, while ContextGraph maintains relationship structures and enables graph traversal for multi-hop retrieval. AgentMemory handles the "what" (content similarity), whereas ContextGraph handles the "how" (relationship proximity) according to the implementation in semantica/context/agent_context.py.
How does the proximity_weight parameter affect retrieval results?
The proximity_weight parameter (default 0) controls the blending ratio between vector similarity scores and graph proximity scores in the final ranking. A value of 0 prioritizes pure semantic similarity, while higher values increase the influence of graph distance (hop count) when ranking retrieved contexts, allowing you to surface related information that might not be semantically identical but is relationally close.
Can I use AgentContext without enabling the ContextGraph?
Yes, AgentContext functions as a standard RAG system using only AgentMemory for vector retrieval when initialized without a knowledge_graph parameter. In this configuration, the ContextRetriever is not instantiated, and retrieve() calls execute pure vector similarity search without graph expansion, falling back to traditional RAG patterns.
What vector stores are compatible with AgentContext?
Any Semantica-compatible vector store can be integrated via the vector_store parameter, including FAISS, Pinecone, and PGVector. The framework abstracts storage specifics through the AgentMemory interface, allowing you to plug in compliant implementations without modifying the retrieval logic in semantica/context/agent_context.py.
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 →