How to Use Semantica for GraphRAG: Implementing Graph-Grounded Retrieval
Semantica enables GraphRAG by combining dense vector search with knowledge graph traversal through the AgentContext.retrieve() method, which automatically detects graph configurations and performs multi-hop reasoning across entity relationships.
Semantica is an open-source framework for building retrieval-augmented generation (RAG) systems with native graph support. The semantica-agi/semantica repository implements GraphRAG as a hybrid retrieval approach that merges vector similarity scores with graph-based entity proximity to improve retrieval accuracy. This guide explains the architecture, core components, and implementation patterns for enabling graph-grounded retrieval in your applications.
How GraphRAG Works in Semantica
Semantica’s GraphRAG implementation operates through three logical layers that coordinate between vector stores and knowledge graphs.
The Three-Layer Architecture
- Ingestion Layer: Parses documents using entity-aware chunking to preserve semantic boundaries. The
KGChunkerclass insemantica/split/kg_chunkers.pycreates chunks that align with entity metadata, enabling later graph joins. - Hybrid Retrieval Layer: Executes multi-factor scoring through
ContextRetrieverinsemantica/context/context_retriever.py. This engine retrieves candidates from the vector store, then expands or re-ranks results using multi-hop graph traversals. - Agent API Layer: Provides the high-level
AgentContextclass insemantica/context/agent_context.py, which exposes a singleretrieve()call that auto-detects graph configurations and switches between pure RAG and GraphRAG.
Internal Retrieval Pipeline
When you invoke retrieval, Semantica executes a five-stage pipeline:
- Entity-Aware Chunking:
KGChunkerprocesses raw text into chunks that maintain entity boundaries, storing metadata for graph alignment. - Vector Indexing: Chunks are embedded via models like OpenAI or Sentence-Transformers and stored in vector databases (FAISS, Pinecone, Qdrant) through the generic interface in
semantica/vector_store/*.py. - Graph Construction: The
ContextGraphclass (referenced byContextRetriever) manages triples representing entities and relationships, supporting external stores like Amazon Neptune. - Hybrid Scoring:
ContextRetrievercalculates multi-factor scores combining vector similarity (dense embeddings), graph proximity (hop distance between query and candidate entities), and optional LLM-based re-ranking. - Result Aggregation: Final ranked chunks are returned; if no knowledge graph is supplied, the system falls back to vector-only retrieval.
Implementing GraphRAG Step by Step
Step 1: Ingest Documents with Entity-Aware Chunking
Initialize your vector store and process documents using KGChunker to ensure chunks preserve entity relationships for graph alignment.
from semantica.vector_store import FaissVectorStore
from semantica.split import KGChunker
from semantica.embeddings import OpenAIEmbeddingModel
# Initialize 1536-dimensional vector store (OpenAI-compatible)
vec_store = FaissVectorStore(dim=1536)
# Entity-aware chunker preserves boundaries for graph joins
chunker = KGChunker()
embedder = OpenAIEmbeddingModel(model="text-embedding-ada-002")
# Ingest and index documents
documents = ["Your long text document here..."]
for doc in documents:
chunks = chunker.split(doc)
vectors = embedder.embed([c.text for c in chunks])
vec_store.add(vectors, metadata=[c.metadata for c in chunks])
Step 2: Build or Connect a Knowledge Graph
Construct a ContextGraph instance containing entity triples, or connect to external graph databases like Neo4j or Amazon Neptune.
from semantica.context import ContextGraph
# Initialize graph structure
graph = ContextGraph()
# Add entity relationships (triples)
graph.add_triple("Paris", "capital_of", "France")
graph.add_triple("Eiffel Tower", "located_in", "Paris")
# Load from external stores via adapters if needed
Step 3: Execute Hybrid Retrieval
Use AgentContext to perform GraphRAG retrieval. The system automatically detects the knowledge graph and activates hybrid scoring.
from semantica.context import AgentContext
# Configure agent with both vector store and knowledge graph
agent = AgentContext(
vector_store=vec_store,
knowledge_graph=graph, # Enables GraphRAG mode
top_k=5 # Candidates to retrieve
)
# Query triggers hybrid retrieval (vector + graph)
results = agent.retrieve("Where is the Eiffel Tower located?")
for result in results:
print(result.text) # Returns chunks enriched by graph context
Framework Integrations
LangChain Integration
Semantica provides SemanticaRetriever in integrations/langchain/retriever.py, implementing LangChain’s BaseRetriever interface for drop-in compatibility.
from semantica.integrations.langchain import SemanticaRetriever
# Wrap Semantica as a LangChain retriever
retriever = SemanticaRetriever(
vector_store=vec_store,
knowledge_graph=graph,
top_k=4
)
# Use in a LangChain pipeline
chain = (
{"question": lambda x: x["question"]}
| retriever
# ... additional processing
)
Agno Relational Knowledge Graphs
For relational knowledge bases, use AgnoKnowledgeGraph from integrations/agno/knowledge_graph.py. This wrapper enables multi-hop GraphRAG search against relational backends, extending the hybrid retrieval capabilities to structured enterprise data.
Summary
- GraphRAG in Semantica combines dense vector retrieval with knowledge graph traversal through the
ContextRetrieverclass. - Entity-aware chunking via
KGChunkerensures semantic units align with graph entities for accurate multi-hop joins. - Automatic mode switching:
AgentContext.retrieve()detects graph presence and transparently selects between pure RAG and GraphRAG. - Production integrations include LangChain-compatible retrievers and support for external graph stores like Amazon Neptune.
- Core files:
semantica/context/agent_context.py(high-level API),semantica/context/context_retriever.py(hybrid engine), andsemantica/split/kg_chunkers.py(ingestion).
Frequently Asked Questions
What is the difference between standard RAG and GraphRAG in Semantica?
Standard RAG retrieves chunks based solely on vector similarity between queries and document embeddings. GraphRAG adds a graph proximity layer: ContextRetriever scores candidates by how many edges separate query entities from document entities, surfacing relevant information that might not be vector-similar but is relationally connected through multi-hop paths.
How does Semantica handle multi-hop graph traversal during retrieval?
Semantica’s ContextRetriever performs multi-factor scoring that includes graph proximity calculations. When processing a query, it identifies entities in the query text, then traverses the ContextGraph to calculate hop distances between query entities and candidate chunk entities. These distances feed into the final ranking score alongside vector similarity.
Can I use external graph databases like Neo4j or Amazon Neptune with Semantica?
Yes. While Semantica includes the ContextGraph class for in-memory or basic graph storage, the architecture supports external graph databases through adapter patterns. The integrations/agno/knowledge_graph.py file demonstrates how to wrap relational knowledge bases, and you can extend ContextGraph to query Neo4j, Amazon Neptune, or other graph stores while maintaining the same AgentContext interface.
What chunking strategy should I use for GraphRAG?
Use KGChunker from semantica/split/kg_chunkers.py for GraphRAG implementations. Unlike standard text splitters, this chunker preserves entity boundaries during segmentation, ensuring that entities remain intact within chunks. This alignment is critical for the graph join operations that occur during hybrid retrieval, as it allows ContextRetriever to accurately map vector chunks to graph nodes.
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 →