How to Set Up Semantica for RAG with Knowledge Graphs: A Complete Implementation Guide
Semantica provides a unified GraphRAG stack that combines vector similarity search with multi-hop knowledge graph traversal through the AgentContext and ContextRetriever classes, automatically routing queries to hybrid retrieval when a knowledge graph is configured.
The semantica-agi/semantica repository offers a production-ready framework for implementing Retrieval-Augmented Generation (RAG) augmented with structured Knowledge Graph capabilities. When you set up Semantica for RAG with Knowledge Graphs, you enable GraphRAG—a hybrid approach that traverses entity relationships alongside semantic vector search to retrieve richer, multi-hop contextual answers.
Core Architecture Components
Setting up GraphRAG requires understanding three primary classes that handle ingestion, orchestration, and retrieval.
AgentContext: High-Level Orchestrator
The AgentContext class in semantica/context/agent_context.py serves as the main entry point for all RAG operations. It stores memories, manages the vector store, and critically, detects whether a knowledge graph is present to determine retrieval strategy.
When you call AgentContext.retrieve(query), the implementation checks self.knowledge_graph. If a graph exists, it instantiates a ContextRetriever for hybrid GraphRAG; otherwise, it falls back to AgentMemory for pure vector search. This automatic routing eliminates manual mode switching.
ContextRetriever: Hybrid Retrieval Engine
The ContextRetriever class in semantica/context/context_retriever.py implements the core GraphRAG logic. According to the Semantica source code, its retrieve() method executes three parallel search strategies:
- Vector search (
_retrieve_from_vector) for semantic embedding similarity - Graph search (
_retrieve_from_graph) for entity/relationship matching with optional multi-hop expansion - Memory search (
_retrieve_from_memory) for recent conversational context
The retriever normalizes scores from each source, applies the hybrid_alpha weighting parameter to balance vector versus graph relevance, deduplicates results, and returns a list of RetrievedContext objects containing content, combined scores, and linked entities.
AgnoKnowledgeGraph: Graph Construction and Integration
For applications using the Agno framework, AgnoKnowledgeGraph in integrations/agno/knowledge_graph.py provides a complete pipeline for building knowledge graphs from raw documents. It handles Named Entity Recognition (NER), relation extraction, and graph population, exposing a search() method compatible with Agno's agent architecture while supplying fallback keyword search capabilities.
Step-by-Step Setup Guide
Follow these implementation steps to configure a working GraphRAG system.
1. Initialize Vector and Graph Stores
First, instantiate a vector store backend and a graph store. Semantica supports FAISS, Pinecone, PostgreSQL-pgvector, and other backends through the VectorStore interface, while graph options include in-memory, Neo4j, or Falkordb via ContextGraph.
from semantica.vector_store import VectorStore
from semantica.context import ContextGraph
# Initialize FAISS vector store
vs = VectorStore(backend="faiss")
# Initialize in-memory graph store (use Neo4j or Falkordb for production)
kg = ContextGraph() # Default backend is inmemory
2. Configure AgentContext with Graph Support
Create an AgentContext instance that wires both stores together. The hybrid_alpha parameter (0.0-1.0) controls the weighting between graph and vector scores—0.6 means 60% graph influence. Enable graph_expansion with max_expansion_hops to allow multi-hop traversal.
from semantica.context import AgentContext
ctx = AgentContext(
vector_store=vs,
knowledge_graph=kg,
hybrid_alpha=0.6, # 60% graph weight, 40% vector
graph_expansion=True,
max_expansion_hops=2, # Traverse up to 2 relationships deep
)
3. Ingest Documents and Build the Knowledge Graph
Use batch_store() to ingest documents. This method automatically populates both the vector store (for semantic search) and constructs the knowledge graph (for relationship traversal).
documents = [
"Aspirin inhibits COX-1 and COX-2 enzymes, reducing inflammation.",
"Lisinopril blocks the renin-angiotensin system, lowering blood pressure."
]
# Stores in vector index and extracts entities/relations for the graph
ctx.batch_store(documents)
For Agno-specific implementations, use AgnoKnowledgeGraph.load() to handle ingestion with framework-specific optimizations.
4. Execute RAG Queries
The system automatically uses GraphRAG when knowledge_graph is present. You can force specific modes using parameters like use_graph and proximity_weight.
# Simple query (auto-detects GraphRAG capability)
results = ctx.retrieve("What drugs treat inflammation?")
print(results[0]["content"])
# Explicit hybrid retrieval with graph proximity scoring
graph_results = ctx.retrieve(
"Which medications target COX enzymes?",
use_graph=True,
max_results=5,
proximity_weight=0.3 # Blend graph distance into final ranking
)
for r in graph_results:
print(f"Content: {r['content']}")
print(f"Score: {r['combined_score']}")
print(f"Entities: {r['related_entities']}")
How Hybrid Retrieval Works
Understanding the retrieval pipeline helps optimize your setup. According to semantica/context/context_retriever.py, the retrieve() method executes the following sequence:
- Parallel retrieval runs vector similarity search, graph entity matching, and memory lookup simultaneously
- Graph expansion (if enabled) traverses relationships up to
max_hopsto capture neighboring entities - Score fusion applies
hybrid_alphato weight graph scores against vector similarity, producing a combined relevance metric - Deduplication and ranking merges results from all sources and re-ranks by the fused score
The final output includes not just text snippets but structured metadata about related_entities and related_relationships, enabling LLM prompts that leverage graph structure.
Summary
Setting up Semantica for RAG with Knowledge Graphs requires these key steps:
- Initialize both a
VectorStore(FAISS, Pinecone, etc.) and aContextGraph(in-memory, Neo4j, or Falkordb) backend - Configure
AgentContextwithknowledge_graphandhybrid_alphaparameters to enable automatic GraphRAG routing - Ingest documents via
batch_store()orAgnoKnowledgeGraph.load()to populate both vector embeddings and graph structures - Execute queries through
AgentContext.retrieve()to receive hybrid results containing vector matches and multi-hop graph traversals - Tune retrieval behavior using
graph_expansion,max_expansion_hops, andproximity_weightparameters
Frequently Asked Questions
What is the difference between simple RAG and GraphRAG in Semantica?
Simple RAG in Semantica uses only vector similarity search against stored document embeddings through AgentMemory. GraphRAG, triggered when AgentContext detects a knowledge_graph instance, uses ContextRetriever to combine vector results with graph traversals, enabling multi-hop reasoning across entity relationships that pure vector search cannot capture.
How does the hybrid_alpha parameter affect retrieval results?
The hybrid_alpha parameter in AgentContext controls the weighting between graph-based and vector-based relevance scores during fusion. A value of 0.6 means graph scores contribute 60% to the final ranking while vector similarity contributes 40%. Setting this to 1.0 prioritizes graph structure exclusively, while 0.0 reverts to pure vector search.
Which graph backends are supported by Semantica?
Semantica supports multiple graph backends through the ContextGraph abstraction in semantica/context/graph.py. The default is an in-memory graph suitable for development, while production deployments can use Neo4j or Falkordb for persistent, scalable graph storage.
Can I use Semantica with the Agno framework?
Yes. The integrations/agno/knowledge_graph.py file provides AgnoKnowledgeGraph, a complete integration that builds knowledge graphs from raw documents and exposes a search() method compatible with Agno agents. This class handles entity extraction, graph construction, and provides fallback keyword search for hybrid RAG pipelines within the Agno ecosystem.
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 →