What Is GraphRAG and How Does Semantica Support It? A Complete Technical Guide
GraphRAG extends traditional Retrieval-Augmented Generation by combining vector similarity search with structured knowledge graph traversal, enabling multi-hop reasoning over entities and relationships.
GraphRAG (Retrieval-Augmented Generation) is an advanced retrieval pattern that enhances classic RAG by integrating structured knowledge graphs alongside plain text embeddings. The open-source Semantica framework provides a production-ready implementation with automatic GraphRAG detection, hybrid scoring, and seamless LangChain integration. This guide examines how Semantica's architecture enables sophisticated graph-aware retrieval and reasoning.
How GraphRAG Works: The Core Pattern
Traditional RAG retrieves documents based solely on semantic similarity. GraphRAG adds a second dimension: entity-aware graph traversal that follows relationships across multiple hops.
The workflow proceeds in four stages:
- Query embedding — the user's question is vectorized and searched against a document store.
- Graph traversal — the system expands from query-related entities through the knowledge graph (multi-hop, relationship-aware).
- Hybrid weighting — vector similarity scores and graph-derived relevance scores are normalized and blended.
- LLM generation — the combined context is passed to a language model, which can cite graph-derived facts and perform chain-of-thought reasoning (e.g., "drug → target → disease").
GraphRAG excels in domains where entities and their interconnections are critical — biomedicine, financial networks, legal precedent chains — because answers remain grounded in verifiable graph structures while retaining generative flexibility.
Semantica's GraphRAG Architecture
Semantica implements GraphRAG through a layered stack that auto-detects knowledge graph availability and switches workflows transparently. Key components include:
| Component | GraphRAG Role | Source Location |
|---|---|---|
AgentContext |
High-level API with auto-detection via retrieve() |
agent_context.py:L95-L105 |
ContextRetriever |
Hybrid retrieval: vector + graph + KG algorithms | context_retriever.py:L13-L38 |
HybridSimilarityCalculator |
Score normalization and hybrid_alpha blending |
[hybrid_similarity.py](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/hybrid_similarity.py) |
KG utilities (PathFinder, CentralityCalculator) |
Multi-hop traversal, importance weighting, community detection | [kg/path_finder.py](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/path_finder.py) |
| Entity-aware chunkers | Preserve entity boundaries for clean graph node creation | kg_chunkers.py:L23-L66 |
SemanticaRetriever |
LangChain BaseRetriever wrapper |
integrations/langchain/retriever.py:L2-L98 |
Auto-Detection of GraphRAG Mode
In agent_context.py, the retrieve() method automatically determines whether to use GraphRAG:
def retrieve(..., use_graph: Optional[bool] = None, ...):
# Auto-detect strategy ↴
if use_graph is None:
use_graph = self.knowledge_graph is not None and self._retriever is not None
Source: agent_context.py:L49-L52
When knowledge_graph is supplied, AgentContext delegates to ContextRetriever for hybrid retrieval. Developers can override this with use_graph=False for pure vector retrieval.
Hybrid Retrieval Implementation in Semantica
The ContextRetriever class in context_retriever.py orchestrates the fusion of vector and graph signals.
Core Retrieval Logic
def retrieve(self, query, max_results=5, use_graph_expansion=True,
min_relevance_score=0.0, **options):
# Vector part ↴
vec_results = self.vector_store.search(query, top_k=...)
# Graph part ↴
if self.use_graph_expansion:
graph_nodes = self.path_finder.expand(query, hops=self.max_expansion_hops)
# Hybrid weighting ↴
combined = self.hybrid_calculator.combine(vec_results, graph_nodes,
alpha=self.hybrid_alpha)
Source: context_retriever.py:L82-L100
The hybrid weighting is controlled by hybrid_alpha (0.0 = pure vector, 1.0 = pure graph), with optional boosts for graph-rich results (see lines 30-34).
Graph Expansion and KG Algorithms
Graph traversal in Semantica leverages several analytical techniques:
- Path finding —
PathFinder.expand()traverses up tomax_expansion_hops(default: 2) from query-matched entities. - Centrality analysis —
CentralityCalculatorweights nodes by importance (PageRank-style metrics). - Community detection — identifies dense subgraphs that may represent functional modules.
- Temporal queries — enabled when the graph supports time-aware edges (flagged by
_TEMPORAL_AVAILABLE).
These utilities are initialized in ContextRetriever.__init__ (lines 62-68).
Entity-Aware Document Processing
GraphRAG quality depends on clean entity-to-node mapping. Semantica's chunking system preserves entity boundaries when splitting documents:
In kg_chunkers.py, the entity-aware chunker ensures that:
- Named entities are not split across chunks
- Each chunk maps to at most one primary graph node
- Relationship context is retained in chunk metadata
Source: kg_chunkers.py:L23-L66
When AgentContext.store() processes documents, extracted entities automatically seed the knowledge graph, creating the foundation for later traversal.
LangChain Integration for GraphRAG
Semantica exposes GraphRAG through a standard LangChain interface via SemanticaRetriever:
from semantica.integrations.langchain import SemanticaRetriever
retriever = SemanticaRetriever(vector_store=vs, knowledge_graph=kg)
docs = retriever.get_relevant_documents("What drugs treat hypertension?")
for d in docs:
print(d.page_content)
Source: integrations/langchain/retriever.py:L2-L98
The SemanticaRetriever class inherits from LangChain's BaseRetriever, ensuring compatibility with existing chains, agents, and tooling.
Practical GraphRAG Examples with Semantica
Basic GraphRAG Retrieval with Auto-Detection
from semantica.context import AgentContext
from semantica.vector_store.sqlite_vec_store import SQLiteVectorStore
from semantica.kg.context_graph import ContextGraph # any KG implementation
vs = SQLiteVectorStore(path="my_vec.db")
kg = ContextGraph() # initialise your graph here
ctx = AgentContext(vector_store=vs, knowledge_graph=kg)
# Store documents (entities extracted automatically)
ctx.store([
{"content": "Aspirin inhibits COX-1 and COX-2.", "metadata": {"source": "paper1"}},
{"content": "Ibuprofen is a non-steroidal anti-inflammatory drug.", "metadata": {"source": "paper2"}},
])
# Graph-aware retrieval — auto-detected via knowledge_graph presence
results = ctx.retrieve(
query="Which drugs target COX enzymes?",
max_results=5,
proximity_weight=0.3 # boost results near graph anchor
)
for r in results:
print(r["content"], "Score:", r["combined_score"])
Force Vector-Only Retrieval
results = ctx.retrieve("Which drugs target COX enzymes?", use_graph=False)
Multi-Hop Reasoning with LLM Integration
from semantica.llms import Groq
llm = Groq(model="llama-3.1-8b-instant")
answer = ctx.query_with_reasoning(
query="Show the chain from drug → target → disease for aspirin",
llm_provider=llm,
max_hops=2
)
print(answer["response"])
print("Reasoning path:", answer["reasoning_path"])
Source: AgentContext.query_with_reasoning (lines 96-104)
Key Implementation Files in Semantica
| File | Purpose |
|---|---|
semantica/context/agent_context.py |
Public API; orchestrates storage, retrieval, and GraphRAG auto-selection |
semantica/context/context_retriever.py |
Core hybrid engine; vector + graph fusion, expansion, scoring |
semantica/kg/path_finder.py |
Multi-hop graph traversal logic |
semantica/kg/centrality_calculator.py |
Node importance scoring |
semantica/split/kg_chunkers.py |
Entity-aware chunking for clean graph node creation |
semantica/integrations/langchain/retriever.py |
LangChain-compatible retriever wrapper |
semantica/vector_store/hybrid_similarity.py |
Score normalization and combination |
All file references correspond to the main branch of semantica-agi/semantica.
Summary
- GraphRAG combines vector similarity with structured knowledge graph traversal for entity-rich retrieval and multi-hop reasoning.
- Semantica's
AgentContextauto-detects GraphRAG capability when aknowledge_graphis provided, requiring no configuration changes. ContextRetrieverimplements hybrid scoring viahybrid_alpha, blending vector and graph signals with boost factors for centrality and community structure.- Entity-aware chunking in
kg_chunkers.pyensures clean entity-to-node mapping for reliable graph traversal. - LangChain integration through
SemanticaRetrieverenables drop-in GraphRAG for existing pipelines. - Tuning parameters include
hybrid_alpha(blend ratio),max_expansion_hops(traversal depth), andproximity_weight(graph anchor boosting).
Frequently Asked Questions
What is the difference between RAG and GraphRAG?
Standard RAG retrieves documents based solely on vector similarity between query and text embeddings. GraphRAG adds knowledge graph traversal: it identifies entities in the query, expands through relationships (multi-hop), and hybrid-scores results using both semantic similarity and graph-derived relevance (centrality, path length, community membership). This yields answers grounded in verifiable entity relationships rather than just text proximity.
How does Semantica decide when to use GraphRAG?
Semantica's AgentContext.retrieve() method auto-detects GraphRAG by checking use_graph is None and then evaluating whether self.knowledge_graph is not None and self._retriever is not None (agent_context.py:L49-L52). If both conditions are true, it delegates to ContextRetriever for hybrid retrieval. Developers can override with use_graph=True or use_graph=False for explicit control.
Can I adjust how much weight the graph receives versus vector similarity?
Yes. The hybrid_alpha parameter controls the blend: 0.0 is pure vector retrieval, 1.0 is pure graph retrieval, and intermediate values mix the two. Additional tuning options include proximity_weight (boosts results near graph anchors) and max_expansion_hops (limits traversal depth, default 2). These are configured in ContextRetriever initialization or per-call in retrieve().
Does Semantica require a specific knowledge graph database?
No. Semantica's ContextGraph is an abstract interface; the implementation can be swapped. The repository includes reference implementations, but any graph backend supporting entity nodes, typed relationships, and traversal queries can integrate via the knowledge_graph parameter in AgentContext or SemanticaRetriever.
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 →