Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Update notebooks for local embeddings and interactive multi-hop queries, fix FalkorDB integration, and add docker-compose

KaifAhmad1fcd61772b26f
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 84212d5c..2c5cf80b 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -2,482 +2,299 @@
"cells": [
{
"cell_type": "markdown",
+ "id": "9570d208",
"metadata": {},
"source": [
- "# GraphRAG\n",
+ "# πŸ§ͺ GraphRAG: Skincare Intelligence System\n",
"## πŸ“– Overview\n",
"\n",
- "This notebook demonstrates the construction of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain. Unlike standard RAG, which treats documents as flat text, **GraphRAG** models the complex web of relationships between ingredients, skin types, conditions, and scientific mechanisms.\n",
+ "This notebook demonstrates the construction and querying of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain. \n",
"\n",
"### πŸ—οΈ Pipeline Architecture\n",
- "\n",
- "We implement a professional 7-phase pipeline:\n",
- "\n",
- "1. **Phase 0: Foundation**: Environment setup and \"Ground Truth\" seeding with **Groq LLM**.\n",
- "2. **Phase 1: Multi-Source Ingestion**: Aggregating knowledge from Expert RSS Feeds and Medical Portals.\n",
- "3. **Phase 1.5: Local Expert Ingestion**: Integrating structured clinical guides from local storage.\n",
- "4. **Phase 2: Processing**: High-fidelity normalization and **Entity-Aware Semantic Chunking**.\n",
- "5. **Phase 3: Semantic Extraction**: Deep extraction using `semantica.semantic_extract` (NER, Relations) via **Llama 3.1 8B**.\n",
- "6. **Phase 4: Refinement**: Autonomous deduplication, conflict resolution, and graph validation.\n",
- "7. **Phase 5: Analytics & Reasoning**: Graph-theoretic insights and advanced reasoning for QA.\n",
+ "1. **Phase 0: Foundation**: Environment setup and \"Ground Truth\" seeding.\n",
+ "2. **Phase 1: Multi-Source Ingestion**: Aggregating knowledge from Expert RSS Feeds and clinical guides.\n",
+ "3. **Phase 2: Semantic Extraction**: Deep extraction using `semantica.semantic_extract` via **Llama 3.1 8B**.\n",
+ "4. **Phase 3: Refinement**: Autonomous deduplication and conflict resolution.\n",
+ "5. **Phase 4: Multi-Hop Question Answering**: Interactive user queries using **Graph-Enhanced Retrieval**.\n",
"\n",
"---"
]
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
+ "id": "aa672d39",
"metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
+ "# Install dependencies\n",
"!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq"
]
},
{
"cell_type": "markdown",
+ "id": "b7a767b5",
"metadata": {},
"source": [
"## πŸ› οΈ Phase 0: Environment & Foundation\n",
- "\n",
- "Establishing a reliable baseline is critical. We configure **Groq** as our high-speed LLM provider and seed the system with verified \"Ground Truth\" data."
+ "We configure **Groq** as our primary LLM provider and seed the system with verified \"Ground Truth\" data."
]
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
+ "id": "6840539f",
"metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div style='font-family: monospace;'><h4>🧠 Semantica - πŸ“Š Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>πŸ”„</td><td>Semantica is building</td><td>🧠 kg</td><td>EntityResolver</td><td>-</td><td>10.76s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.60s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.01s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>EntityMerger</td><td>-</td><td>0.05s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.01s</td></tr><tr><td>βœ…</td><td>Semantica is resolving</td><td>⚠️ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>βœ…</td><td>Semantica is building</td><td>🧠 kg</td><td>CentralityCalculator</td><td>-</td><td>0.00s</td></tr><tr><td>βœ…</td><td>Semantica is building</td><td>🧠 kg</td><td>CommunityDetector</td><td>-</td><td>0.00s</td></tr><tr><td>❌</td><td>Semantica is reasoning</td><td>πŸ€” reasoning</td><td>GraphReasoner</td><td>-</td><td>1.09s</td></tr><tr><td>βœ…</td><td>Semantica is visualizing</td><td>πŸ“ˆ visualization</td><td>KGVisualizer</td><td>-</td><td>0.11s</td></tr></table></div>"
- ],
- "text/plain": [
- "<IPython.core.display.HTML object>"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 0 Complete. Seeded 4 primary nodes with Groq backend.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"import os\n",
"import json\n",
"import pandas as pd\n",
"from semantica.core import Semantica, ConfigManager\n",
"from semantica.seed import SeedDataManager\n",
+ "from semantica.vector_store import VectorStore\n",
"\n",
- "# 1. Groq & Advanced Configuration\n",
+ "# 1. Groq Configuration\n",
"os.environ[\"GROQ_API_KEY\"] = \"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\"\n",
"\n",
"config_dict = {\n",
- " \"project_name\": \"Skincare_Graph_IQ\",\n",
+ " \"project_name\": \"Skincare_Intelligence\",\n",
" \"embedding\": {\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"}, \n",
" \"extraction\": {\n",
" \"provider\": \"groq\", \n",
" \"model\": \"llama-3.1-8b-instant\", \n",
" \"temperature\": 0.0\n",
" },\n",
+ " \"inference\": {\n",
+ " \"provider\": \"groq\",\n",
+ " \"model\": \"llama-3.1-70b-versatile\"\n",
+ " },\n",
" \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 1536},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"merge_entities\": True, \"resolution_strategy\": \"fuzzy\"}\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"merge_entities\": True}\n",
"}\n",
"\n",
"config = ConfigManager().load_from_dict(config_dict)\n",
"core = Semantica(config=config)\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",
"\n",
- "# 2. Seeding Ground Truth (The \"Anchor\" for our Graph)\n",
+ "# 2. Seeding Ground Truth\n",
"foundation_data = {\n",
" \"entities\": [\n",
" {\"id\": \"hyaluronic_acid\", \"name\": \"Hyaluronic Acid\", \"type\": \"Ingredient\", \"properties\": {\"role\": \"Humectant\"}},\n",
" {\"id\": \"retinol\", \"name\": \"Retinol\", \"type\": \"Ingredient\", \"properties\": {\"role\": \"Anti-aging actives\"}},\n",
- " {\"id\": \"niacinamide\", \"name\": \"Niacinamide\", \"type\": \"Ingredient\", \"properties\": {\"role\": \"Barrier repair\"}},\n",
- " {\"id\": \"collagen\", \"name\": \"Collagen\", \"type\": \"Protein\", \"properties\": {\"location\": \"Dermal Matrix\"}}\n",
+ " {\"id\": \"niacinamide\", \"name\": \"Niacinamide\", \"type\": \"Ingredient\", \"properties\": {\"role\": \"Barrier repair\"}}\n",
" ],\n",
" \"relationships\": [\n",
- " {\"source\": \"retinol\", \"target\": \"collagen\", \"type\": \"STIMULATES\", \"properties\": {\"level\": \"High\"}},\n",
" {\"source\": \"hyaluronic_acid\", \"target\": \"niacinamide\", \"type\": \"COMPLEMENTS\", \"properties\": {\"benefit\": \"Hydration + Barrier\"}}\n",
" ]\n",
"}\n",
"\n",
"with open(\"skincare_base.json\", \"w\") as f: json.dump(foundation_data, f)\n",
- "\n",
"seed_manager = SeedDataManager()\n",
"seed_manager.register_source(\"core_ontology\", \"json\", \"skincare_base.json\")\n",
"foundation_graph = seed_manager.create_foundation_graph()\n",
"\n",
- "print(f\"βœ… Phase 0 Complete. Seeded {len(foundation_data['entities'])} primary nodes with Groq backend.\")"
+ "print(f\"βœ… Phase 0 Complete. Seeded {len(foundation_data['entities'])} primary nodes.\")"
]
},
{
"cell_type": "markdown",
+ "id": "9f2ce49c",
"metadata": {},
"source": [
- "## πŸ“₯ Phase 1: Multi-Source Web Ingestion\n",
- "\n",
- "We pull real-world knowledge from reliable, high-stability RSS feeds and medical portals. Using verified paths ensures we bypass restricted medical endpoints."
+ "## πŸ“₯ Phase 1: Ingestion & Processing\n",
+ "We pull real-world knowledge from expert feeds and clinical guides, then split them into semantic chunks."
]
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
+ "id": "879f9fd9",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Successfully ingested feed: https://makeupandbeautyblog.com/feed\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Failed to fetch feed https://www.thebeautylookbook.com/feed: 403 Client Error: Forbidden for url: https://thebeautylookbook.com/feed\n",
- "Failed to ingest feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://thebeautylookbook.com/feed\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Feed Error https://www.thebeautylookbook.com/feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://thebeautylookbook.com/feed\n",
- "Successfully ingested feed: https://stylecaster.com/c/beauty/skin-care/feed/\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Failed to fetch URL https://www.niams.nih.gov/health-topics/all-health-topics: 404 Client Error: Not Found for url: https://www.niams.nih.gov/health-topics/all-health-topics\n",
- "Failed to ingest web: Failed to fetch URL: 404 Client Error: Not Found for url: https://www.niams.nih.gov/health-topics/all-health-topics\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Web Error https://www.niams.nih.gov/health-topics/all-health-topics: Failed to fetch URL: 404 Client Error: Not Found for url: https://www.niams.nih.gov/health-topics/all-health-topics\n",
- "Successfully ingested web: https://dermnetnz.org/topics/emollients-and-moisturisers\n",
- "βœ… Phase 1 Complete. Ingested 7 total web records.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
- "from semantica.ingest import ingest_web, ingest_feed\n",
+ "from semantica.ingest import ingest_feed, ingest_file\n",
+ "from semantica.split import EntityAwareChunker\n",
+ "from semantica.normalize import TextNormalizer\n",
"\n",
"sources = []\n",
"\n",
- "# 1. High-Stability RSS Feeds (Expert Blogs)\n",
- "feeds = [\n",
- " \"https://makeupandbeautyblog.com/feed\",\n",
- " \"https://www.thebeautylookbook.com/feed\",\n",
- " \"https://stylecaster.com/c/beauty/skin-care/feed/\"\n",
- "]\n",
- "\n",
- "for feed_url in feeds:\n",
- " try:\n",
- " feed_data = ingest_feed(feed_url, method=\"rss\")\n",
- " sources.extend([item.content or item.description for item in feed_data.items[:3]])\n",
- " print(f\"Successfully ingested feed: {feed_url}\")\n",
- " except Exception as e: print(f\"Feed Error {feed_url}: {e}\")\n",
- "\n",
- "# 2. Targeted Web Ingestion (Clinical Summary Pages)\n",
- "web_urls = [\n",
- " \"https://www.niams.nih.gov/health-topics/all-health-topics\", \n",
- " \"https://dermnetnz.org/topics/emollients-and-moisturisers\"\n",
- "]\n",
- "\n",
- "for url in web_urls:\n",
- " try:\n",
- " content = ingest_web(url, method=\"url\")\n",
- " sources.append(content.text)\n",
- " print(f\"Successfully ingested web: {url}\")\n",
- " except Exception as e: print(f\"Web Error {url}: {e}\")\n",
- "\n",
- "print(f\"βœ… Phase 1 Complete. Ingested {len(sources)} total web records.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## πŸ“‚ Phase 1.5: Local Expert Knowledge Ingestion\n",
- "\n",
- "A professional GraphRAG system should never rely solely on ephemeral web sources. Here we demonstrate ingesting structured local expertise (e.g., Clinical Guidelines or Ingredient Whitepapers)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Local expert document ingested successfully.\n"
- ]
- }
- ],
- "source": [
- "from semantica.ingest import ingest_file\n",
+ "# 1. RSS Ingestion\n",
+ "feed_url = \"https://makeupandbeautyblog.com/feed\"\n",
+ "try:\n",
+ " feed_data = ingest_feed(feed_url, method=\"rss\")\n",
+ " sources.extend([item.content or item.description for item in feed_data.items[:5]])\n",
+ "except Exception: pass\n",
"\n",
- "# Creating a mock expert document for demonstration\n",
+ "# 2. Local Expert Guide\n",
"expert_content = \"\"\"\n",
- "RETINOL CLINICAL GUIDE v2.1\n",
- "Mechanism: Binds to retinoic acid receptors (RAR) to increase cellular turnover.\n",
+ "RETINOL CLINICAL GUIDE\n",
+ "Mechanism: Binds to retinoic acid receptors to increase cellular turnover.\n",
"Precautions: Should not be used with high-concentration AHA/BHA exfoliants.\n",
"Synergy: Highly effective when paired with Niacinamide to offset potential erythema.\n",
- "Target: Stratum corneum thickening and dermal collagen synthesis.\n",
"\"\"\"\n",
- "with open(\"expert_skincare_guide.txt\", \"w\") as f: f.write(expert_content)\n",
+ "with open(\"expert_guide.txt\", \"w\") as f: f.write(expert_content)\n",
+ "sources.append(expert_content)\n",
"\n",
- "try:\n",
- " local_data = ingest_file(\"expert_skincare_guide.txt\")\n",
- " # FileObject content is binary, so we decode it for text processing\n",
- " expert_text = local_data.content.decode('utf-8') if local_data.content else \"\"\n",
- " sources.append(expert_text)\n",
- " print(\"βœ… Local expert document ingested successfully.\")\n",
- "except Exception as e: print(f\"Local Ingest Error: {e}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## πŸ”§ Phase 2: High-Fidelity Processing\n",
- "\n",
- "Before extraction, we clean the data and perform **Entity-Aware Chunking** to preserve complex ingredient descriptions."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
- " from tqdm.autonotebook import tqdm, trange\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 2 Complete. Generated 16 semantic chunks.\n"
- ]
- }
- ],
- "source": [
- "from semantica.normalize import TextNormalizer, DataCleaner\n",
- "from semantica.split import EntityAwareChunker\n",
- "\n",
- "# 1. Normalization & Cleaning\n",
+ "# 3. Chunking & Normalization\n",
"normalizer = TextNormalizer()\n",
- "cleaner = DataCleaner()\n",
- "\n",
- "cleaned_docs = []\n",
+ "chunker = EntityAwareChunker(chunk_size=1000, chunk_overlap=200)\n",
+ "all_chunks = []\n",
"for text in sources:\n",
" if not text: continue\n",
" norm_text = normalizer.normalize(text)\n",
- " cleaned_docs.append({\"text\": norm_text})\n",
+ " all_chunks.extend(chunker.chunk(norm_text))\n",
"\n",
- "final_dataset = cleaner.clean_data(cleaned_docs, remove_duplicates=True)\n",
- "\n",
- "# 2. Sophisticated Chunking\n",
- "chunker = EntityAwareChunker(chunk_size=1000, chunk_overlap=200)\n",
- "all_chunks = []\n",
- "for doc in final_dataset:\n",
- " all_chunks.extend(chunker.chunk(doc['text']))\n",
- "\n",
- "print(f\"βœ… Phase 2 Complete. Generated {len(all_chunks)} semantic chunks.\")"
+ "print(f\"βœ… Phase 1 Complete. Generated {len(all_chunks)} semantic chunks.\")"
]
},
{
"cell_type": "markdown",
+ "id": "86a699bc",
"metadata": {},
"source": [
- "## 🧠 Phase 3: Detailed Semantic Extraction (Powered by Llama 3.1 via Groq)\n",
- "\n",
- "We use **Groq's Llama 3.1 8B** for high-speed, high-precision semantic extraction."
+ "## 🧠 Phase 2: Semantic Extraction\n",
+ "Using **Groq (Llama 3.1 8B)** to extract entities and relationships."
]
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": null,
+ "id": "54fa8fad",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Extracting nodes and edges using Groq (Llama 3.1 8B)...\n",
- "βœ… Phase 3 Complete. Extracted 11 entities using Groq.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"from semantica.semantic_extract import NERExtractor, RelationExtractor\n",
"\n",
- "# 1. Named Entity Recognition via Groq\n",
"ner = NERExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "\n",
- "# 2. Relation Extraction via Groq\n",
"rel_ext = RelationExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
"\n",
"combined_results = {\"entities\": [], \"relationships\": []}\n",
"\n",
- "# Process a subset for demonstration\n",
- "sample_chunks = all_chunks[:5]\n",
- "print(\"Extracting nodes and edges using Groq (Llama 3.1 8B)...\")\n",
- "\n",
- "for chunk in sample_chunks:\n",
+ "print(\"Extracting intelligence from chunks...\")\n",
+ "for chunk in all_chunks[:5]:\n",
" txt = str(chunk.text)\n",
- " # Extract Entities\n",
" entities = ner.extract(txt)\n",
" combined_results[\"entities\"].extend([{\"name\": e.text, \"type\": e.label, \"id\": e.text.lower().replace(' ', '_')} for e in entities])\n",
- " \n",
- " # Extract Relations based on detected entities\n",
" relations = rel_ext.extract(txt, entities=entities)\n",
" combined_results[\"relationships\"].extend([{\"source\": r.subject, \"target\": r.object, \"type\": r.predicate} for r in relations])\n",
"\n",
- "print(f\"βœ… Phase 3 Complete. Extracted {len(combined_results['entities'])} entities using Groq.\")"
+ "print(f\"βœ… Phase 2 Complete. Extracted {len(combined_results['entities'])} entities.\")"
]
},
{
"cell_type": "markdown",
+ "id": "19a78219",
"metadata": {},
"source": [
- "## ✨ Phase 4: Graph Refinement & Resolution\n",
- "\n",
- "Merging fragments and resolving conflicts using `semantica.kg` and `semantica.conflicts`."
+ "## ✨ Phase 3: Graph Refinement\n",
+ "Merging fragments and building the final Knowledge Graph."
]
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": null,
+ "id": "97a63461",
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 4 Complete. Graph Integrity: Issues Addressed\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
- "from semantica.kg import GraphBuilder, GraphValidator\n",
+ "from semantica.kg import GraphBuilder\n",
"from semantica.deduplication import DuplicateDetector, EntityMerger\n",
- "from semantica.conflicts import ConflictDetector, ConflictResolver\n",
"\n",
- "# 1. Unified Graph Construction\n",
- "gb = GraphBuilder(merge_entities=True, entity_resolution_strategy=\"fuzzy\")\n",
+ "# 1. Build & Vectorize\n",
+ "gb = GraphBuilder(merge_entities=True)\n",
"kg = gb.build([combined_results])\n",
"\n",
- "# 2. Autonomous Deduplication\n",
- "detector = DuplicateDetector(similarity_threshold=0.85)\n",
+ "# 2. Deduplicate\n",
+ "detector = DuplicateDetector(threshold=0.85)\n",
"duplicates = detector.detect_duplicates(kg['entities'])\n",
- "if duplicates:\n",
- " kg = EntityMerger().merge_duplicates(kg, duplicates)\n",
- " print(f\"- Merged {len(duplicates)} duplicate entities.\")\n",
+ "kg_final = EntityMerger().merge_entities(kg, duplicates)\n",
"\n",
- "# 3. Conflict Resolution\n",
- "conflicts = ConflictDetector().detect_conflicts(kg)\n",
- "if conflicts:\n",
- " kg = ConflictResolver().resolve_conflicts(kg, conflicts, strategy=\"consensus\")\n",
- " print(f\"- Resolved {len(conflicts)} knowledge conflicts.\")\n",
+ "# 3. Populate Vector Store for retrieval\n",
+ "texts = [str(c.text) for c in all_chunks]\n",
+ "embeddings = core.embedding_generator.generate_embeddings(texts)\n",
+ "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": t} for t in texts])\n",
"\n",
- "# 4. Quality Validation\n",
- "validation = GraphValidator().validate(kg)\n",
- "print(f\"βœ… Phase 4 Complete. Graph Integrity: {'Passed' if validation.is_valid else 'Issues Addressed'}\")"
+ "print(f\"βœ… Phase 3 Complete. Graph contains {len(kg_final['entities'])} resolved entities.\")"
]
},
{
"cell_type": "markdown",
+ "id": "b1d1ffb3",
"metadata": {},
"source": [
- "## πŸ“Š Phase 5: Analytics, Reasoning & Visualization\n",
- "\n",
- "Applying graph theory and **Groq-powered reasoning** to the skincare knowledge base."
+ "## πŸ’¬ Phase 4: Interactive GraphRAG Question Answering\n",
+ "Enter a skincare query to see the **multi-hop retrieval** and **final answer**."
]
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": null,
+ "id": "4edf258c",
"metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Reasoning failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************bt8A. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 5 Complete.\n",
- "Top Ingredients: ['Makeup and Beauty Blog | Makeup Reviews, Swatches and How-To Makeup', 'Makeup and Beauty Blog']\n",
- "Reasoning Output: Error during reasoning: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************bt8A. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}\n"
- ]
- }
- ],
+ "outputs": [],
+ "source": [
+ "from semantica.context import ContextRetriever\n",
+ "from semantica.inference import InferenceEngine\n",
+ "\n",
+ "# 1. Initialize Retriever & Engine\n",
+ "retriever = ContextRetriever(\n",
+ " vector_store=vs, \n",
+ " knowledge_graph=kg_final, \n",
+ " use_graph_expansion=True,\n",
+ " max_expansion_hops=2\n",
+ ")\n",
+ "\n",
+ "engine = InferenceEngine(provider=\"groq\", model=\"llama-3.1-70b-versatile\")\n",
+ "\n",
+ "# 2. Interactive Query Loop\n",
+ "user_query = input(\"Enter your skincare query: \") or \"What ingredients synergize with Retinol to prevent irritation?\"\n",
+ "\n",
+ "print(f\"\\nπŸ” Processing Multi-Hop Query: {user_query}\")\n",
+ "\n",
+ "# Retrieve multi-hop context\n",
+ "context_results = retriever.retrieve(user_query, max_results=2)\n",
+ "\n",
+ "if context_results:\n",
+ " # Show the reasoning path (Connected Entities)\n",
+ " if context_results[0].related_entities:\n",
+ " print(\"\\n--- 🧠 MULTI-HOP CONTEXT DISCOVERED ---\")\n",
+ " for ent in context_results[0].related_entities[:5]:\n",
+ " print(f\"- {ent['content']} ({ent['type']}) via {ent['relationship']}\")\n",
+ "\n",
+ " # Generate Final Answer\n",
+ " context_text = \" \".join([r.content for r in context_results])\n",
+ " prompt = f\"Based on the following context, answer the user query accurately.\\nContext: {context_text}\\nQuery: {user_query}\"\n",
+ " final_answer = engine.generate(prompt)\n",
+ "\n",
+ " print(\"\\n--- ✨ FINAL GRAPHRAG ANSWER ---\")\n",
+ " print(final_answer)\n",
+ "else:\n",
+ " print(\"\\n❌ No relevant context found in the knowledge graph.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e7c15dd7",
+ "metadata": {},
+ "source": [
+ "## πŸ“Š Visualizing the Intelligence\n",
+ "A final look at the relationships we've built."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4b52490d",
+ "metadata": {},
+ "outputs": [],
"source": [
- "from semantica.kg import CentralityCalculator, CommunityDetector\n",
- "from semantica.reasoning import GraphReasoner\n",
"from semantica.visualization import KGVisualizer\n",
"import matplotlib.pyplot as plt\n",
"\n",
- "# 1. Key Node Analysis\n",
- "centrality = CentralityCalculator().calculate_degree_centrality(kg)\n",
- "rankings = centrality.get(\"rankings\", [])[:3]\n",
- "\n",
- "# 2. Component Analysis\n",
- "communities = CommunityDetector().detect_communities(kg, algorithm=\"louvain\")\n",
- "num_communities = len(communities.get(\"communities\", []))\n",
- "\n",
- "# 3. Advanced Reasoning using Groq\n",
- "reasoner = GraphReasoner(core=core, provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "query = \"What ingredients should be avoided with Retinol based on the graph?\"\n",
- "answer = reasoner.reason(kg, query)\n",
- "\n",
- "# 4. Visualization\n",
"viz = KGVisualizer()\n",
- "viz.visualize_network(kg, layout=\"spring\", title=\"Skincare Ingredient Intelligence Graph (Groq Enhanced)\")\n",
- "plt.show()\n",
- "\n",
- "print(f\"βœ… Phase 5 Complete.\")\n",
- "print(f\"Top Ingredients: {[r['node'] for r in rankings]}\")\n",
- "print(f\"Reasoning Output: {answer}\")"
+ "viz.visualize_network(kg_final, layout=\"spring\", title=\"Skincare Ingredient Intelligence Graph\")\n",
+ "plt.show()"
]
}
],
@@ -501,5 +318,5 @@
}
},
"nbformat": 4,
- "nbformat_minor": 2
+ "nbformat_minor": 5
}
diff --git a/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb b/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb
index f917bf83..da56a712 100644
--- a/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb
+++ b/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb
@@ -5,18 +5,15 @@
"id": "de0a7591",
"metadata": {},
"source": [
- "# RAG vs. GraphRAG: Investigative Intelligence Comparison\n",
+ "# RAG vs. GraphRAG: Final Answer Comparison\n",
"\n",
- "## Overview\n",
- "This notebook provides a rigorous, side-by-side comparison of **Standard RAG (Vector-based)** and **GraphRAG (Graph-based)**, focusing on the Global Intelligence and Security domain.\n",
+ "This notebook demonstrates the difference in final answers generated by **Standard Vector RAG** and **Semantica GraphRAG** for a complex multi-hop query. We use **FalkorDB** as our high-performance graph backend.\n",
"\n",
- "### The Challenge: Navigating Fragmentation\n",
- "In intelligence work, facts are scattered across reports. Vector search often fails to bridge \"semantic gaps\"β€”logical connections between entities that are not physically co-located in text. \n",
- "\n",
- "We will demonstrate how GraphRAG creates a **\"Chain of Evidence\"** that Vector RAG cannot see.\n",
- "\n",
- "### Framework: Semantica\n",
- "We use the [Semantica](https://github.com/Hawksight-AI/semantica) framework to orchestrate common intelligence tasks like entity resolution, conflict detection, and graph-based reasoning."
+ "### FalkorDB Setup\n",
+ "To use the persistent graph store, you can start a FalkorDB instance using the provided Docker Compose file:\n",
+ "```bash\n",
+ "docker compose up -d\n",
+ "```"
]
},
{
@@ -26,7 +23,7 @@
"metadata": {},
"outputs": [],
"source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu falkordb"
]
},
{
@@ -34,201 +31,201 @@
"id": "889e971d",
"metadata": {},
"source": [
- "## 1. Domain Acquisition: Real-World Intelligence gathering\n",
- "We ingest from high-signal feeds to build our knowledge base."
+ "## 1. Environment & Store Initialization\n",
+ "We set up our **Vector Store** for semantic search and **FalkorDB** for persistent graph storage."
]
},
{
"cell_type": "code",
"execution_count": null,
- "id": "b332d1ab",
+ "id": "init_stores",
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import WebIngestor, FeedIngestor\n",
+ "from semantica.core import Semantica\n",
+ "from semantica.vector_store import VectorStore\n",
+ "from semantica.graph_store import GraphStore\n",
+ "from semantica.kg import GraphBuilder\n",
+ "from semantica.split import TextSplitter\n",
"from semantica.normalize import TextNormalizer\n",
"\n",
- "normalizer = TextNormalizer()\n",
- "all_content = []\n",
+ "# 1. Core Semantica & Vector Store\n",
+ "v_core = Semantica()\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",
+ "\n",
+ "# 2. FalkorDB Persistent Graph Store\n",
+ "graph_store = GraphStore(\n",
+ " backend=\"falkordb\",\n",
+ " host=\"localhost\",\n",
+ " port=6379,\n",
+ " graph_name=\"intelligence_graph\"\n",
+ ")\n",
"\n",
- "# 1. Global News Feeds (RSS) - Using more robust and accessible feeds\n",
- "feeds = [\n",
- " \"http://feeds.bbci.co.uk/news/world/rss.xml\",\n",
- " \"https://www.aljazeera.com/xml/rss/all.xml\",\n",
- " \"https://news.google.com/rss/search?q=site%3Areuters.com&hl=en-US&gl=US&ceid=US%3Aen\" # Reuters workaround\n",
- "]\n",
- "feed_ingestor = FeedIngestor()\n",
- "for f in feeds:\n",
- " try:\n",
- " data = feed_ingestor.ingest_feed(f)\n",
- " items = data.items[:10]\n",
- " for item in items:\n",
- " # Fallback chain: content -> description -> title\n",
- " text = item.content or item.description or item.title\n",
- " if text:\n",
- " all_content.append(text)\n",
- " except Exception as e:\n",
- " print(f\"Warning: Failed to ingest feed {f}: {e}\")\n",
- "\n",
- "# 2. Strategic Overviews (Web) - Using pages with more permissive robots.txt\n",
- "web_urls = [\n",
- " \"https://www.cia.gov/the-world-factbook/\",\n",
- " \"https://www.cfr.org/backgrounders\" \n",
- "]\n",
- "web_ingestor = WebIngestor()\n",
- "for url in web_urls:\n",
- " try:\n",
- " content = web_ingestor.ingest_url(url)\n",
- " if content.text:\n",
- " all_content.append(content.text)\n",
- " except Exception as e:\n",
- " print(f\"Warning: Failed to ingest URL {url}: {e}\")\n",
- "\n",
- "# Clean and normalize\n",
- "clean_docs = [normalizer.normalize(text) for text in all_content if len(text) > 100] # Increased threshold for higher quality\n",
- "print(f\"Intelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")"
+ "try:\n",
+ " graph_store.connect()\n",
+ " print(\"Successfully connected to FalkorDB backend.\")\n",
+ " use_persistent = True\n",
+ "except Exception as e:\n",
+ " print(f\"FalkorDB connection failed: {e}. Falling back to in-memory mode.\")\n",
+ " use_persistent = False\n",
+ "\n",
+ "# 3. Graph Builder with Persistence Support\n",
+ "gb = GraphBuilder(merge_entities=True, graph_store=graph_store if use_persistent else None)\n",
+ "splitter = TextSplitter(method=\"recursive\", chunk_size=800, chunk_overlap=100)\n",
+ "normalizer = TextNormalizer()"
]
},
{
"cell_type": "markdown",
- "id": "1ba35952",
+ "id": "ingestion_section",
"metadata": {},
"source": [
- "## 2. Standard Vector RAG Pipeline\n",
- "Linear retrieval via semantic embedding overlap."
+ "## 2. Real-Time Intelligence Ingestion\n",
+ "We pull live data from global news feeds to build our knowledge base."
]
},
{
"cell_type": "code",
"execution_count": null,
- "id": "aedbf41c",
+ "id": "ingest_data",
"metadata": {},
"outputs": [],
"source": [
- "from semantica.core import Semantica\n",
- "from semantica.split import TextSplitter\n",
- "from semantica.vector_store import VectorStore\n",
+ "from semantica.ingest import FeedIngestor\n",
"\n",
- "# v_core = Semantica(embedding={\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"})\n",
- "# Using framework defaults which utilize the core.config\n",
- "v_core = Semantica()\n",
+ "all_content = []\n",
+ "feeds = [\n",
+ " \"http://feeds.bbci.co.uk/news/world/rss.xml\",\n",
+ " \"https://www.aljazeera.com/xml/rss/all.xml\"\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "for f in feeds:\n",
+ " try:\n",
+ " data = feed_ingestor.ingest_feed(f)\n",
+ " for item in data.items[:15]:\n",
+ " text = item.content or item.description or item.title\n",
+ " if text: all_content.append(text)\n",
+ " except Exception: continue\n",
"\n",
- "splitter = TextSplitter(method=\"recursive\", chunk_size=600, chunk_overlap=50)\n",
+ "clean_docs = [normalizer.normalize(text) for text in all_content if len(text) > 100]\n",
"chunks = []\n",
- "for doc in clean_docs[:10]:\n",
+ "for doc in clean_docs:\n",
" chunks.extend(splitter.split(doc))\n",
"\n",
- "# Initialize Vector Store\n",
- "vs = VectorStore(backend=\"faiss\", dimension=1536) \n",
- "embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks[:15]])\n",
- "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks[:15]])\n",
+ "# Populate Stores\n",
+ "print(f\"Processing {len(chunks)} chunks...\")\n",
+ "embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks])\n",
+ "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks])\n",
+ "\n",
+ "# Build Knowledge Graph (Automatically persists to FalkorDB if connected)\n",
+ "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:30]])\n",
"\n",
- "print(f\"Vector RAG ready with {len(chunks[:15])} encoded fragments.\")"
+ "query = \"Analyze the intersection of current regional conflicts and global energy infrastructure vulnerability.\"\n",
+ "print(f\"\\nSetup complete. Query: {query}\")"
]
},
{
"cell_type": "markdown",
- "id": "92d1b0cf",
+ "id": "refinement_intro",
"metadata": {},
"source": [
- "## 3. High-Fidelity GraphRAG Pipeline\n",
- "Synthesizing entities and relationships from fragmented reports."
+ "## 3. Knowledge Refinement\n",
+ "Deduplicating entities and resolving conflicting information for higher accuracy."
]
},
{
"cell_type": "code",
"execution_count": null,
- "id": "c66212ed",
+ "id": "refinement_code",
"metadata": {},
"outputs": [],
"source": [
- "from semantica.kg import GraphBuilder\n",
- "from semantica.deduplication import DuplicateDetector\n",
- "\n",
- "gb = GraphBuilder(merge_entities=True)\n",
- "# We process a subset for demonstration\n",
- "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:10]])\n",
- "\n",
- "print(f\"GraphRAG Synthesis Complete: {len(kg.get('entities', []))} entities, {len(kg.get('relationships', []))} relationships.\")"
+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",
+ "from semantica.conflicts import ConflictDetector, ConflictResolver\n",
+ "\n",
+ "# 1. Entity Resolution\n",
+ "detector = DuplicateDetector(threshold=0.85)\n",
+ "merger = EntityMerger()\n",
+ "duplicates = detector.detect_duplicates(kg['entities'])\n",
+ "kg_refined = merger.merge_entities(kg, duplicates)\n",
+ "\n",
+ "# 2. Conflict Resolution\n",
+ "conflict_detector = ConflictDetector()\n",
+ "conflicts = conflict_detector.detect_conflicts(kg_refined['entities'])\n",
+ "if conflicts:\n",
+ " resolver = ConflictResolver()\n",
+ " for conflict in conflicts:\n",
+ " kg_refined = resolver.resolve_conflict(conflict, strategy=\"credibility_weighted\")\n",
+ "\n",
+ "print(\"Knowledge Graph Refined.\")"
]
},
{
"cell_type": "markdown",
- "id": "7b97e797",
+ "id": "rag_section",
"metadata": {},
"source": [
- "## 4. The Intelligence Challenge: Multi-Hop Inference\n",
- "Standard RAG finds fragments *about* a topic. GraphRAG finds *connections between* topics.\n",
- "\n",
- "Query: **\"Identify high-risk security escalations and their regional implications.\"**"
+ "## 4. Standard Vector RAG Answer\n",
+ "Standard RAG retrieves isolated chunks based on semantic similarity."
]
},
{
"cell_type": "code",
"execution_count": null,
- "id": "0b9fcae5",
+ "id": "rag_code",
"metadata": {},
"outputs": [],
"source": [
- "from semantica.reasoning import InferenceEngine\n",
- "\n",
- "print(\"--- Standard Vector Recall ---\")\n",
- "q_vec = v_core.embedding_generator.generate_embeddings(\"security risks and regional conflict\")\n",
- "v_res = vs.search_vectors(q_vec, k=3)\n",
- "for r in v_res:\n",
- " print(f\"Recall: {r['metadata']['text'][:120]}...\")\n",
- "\n",
- "print(\"\\n--- Graph Intelligence Reasoning ---\")\n",
- "engine = InferenceEngine(strategy=\"forward\")\n",
- "\n",
- "# Prefix Rule: IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)\n",
- "engine.add_rule(\"IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)\")\n",
- "\n",
- "# Add facts from extracted KG\n",
- "for rel in kg.get('relationships', []):\n",
- " source = rel.get('source', '')\n",
- " target = rel.get('target', '')\n",
- " rtype = rel.get('type', '').lower()\n",
- " \n",
- " if 'locate' in rtype or 'in' in rtype:\n",
- " engine.add_fact(f\"LocatedIn({source}, {target})\")\n",
- "\n",
- "# Simulated High-Priority Facts for demonstration\n",
- "engine.add_fact(\"Conflict(Political_Internal_Unrest)\")\n",
- "engine.add_fact(\"LocatedIn(Political_Internal_Unrest, Strategic_Region_A)\")\n",
- "\n",
- "# Perform Inference\n",
- "results = engine.forward_chain()\n",
- "for res in results:\n",
- " print(f\"Inferred: {res.conclusion}\")"
+ "q_vec = v_core.embedding_generator.generate_embeddings(query)\n",
+ "v_res = vs.search_vectors(q_vec, k=1)\n",
+ "\n",
+ "print(\"--- VECTOR RAG FINAL ANSWER ---\")\n",
+ "if v_res:\n",
+ " print(v_res[0]['metadata']['text'])\n",
+ "else:\n",
+ " print(\"No relevant context found.\")"
]
},
{
"cell_type": "markdown",
- "id": "5928355c",
+ "id": "graphrag_section",
"metadata": {},
"source": [
- "## 5. Visualizing the Intelligence Landscape\n",
- "Seeing the 'Bridges' between disconnected events."
+ "## 5. Semantica GraphRAG Answer\n",
+ "GraphRAG uses multi-hop traversal via **FalkorDB** to synthesize a connected answer."
]
},
{
"cell_type": "code",
"execution_count": null,
- "id": "b209720f",
+ "id": "graphrag_code",
"metadata": {},
"outputs": [],
"source": [
- "from semantica.visualization import KGVisualizer\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "viz = KGVisualizer()\n",
- "viz.visualize_network(\n",
- " kg,\n",
- " output=\"static\",\n",
- " title=\"Intelligence Connectivity Map\"\n",
+ "from semantica.context import ContextRetriever\n",
+ "\n",
+ "# Use the persistent GraphStore if available, otherwise fallback to the in-memory dict\n",
+ "kg_backend = graph_store if use_persistent else kg_refined\n",
+ "\n",
+ "retriever = ContextRetriever(\n",
+ " vector_store=vs, \n",
+ " knowledge_graph=kg_backend, \n",
+ " use_graph_expansion=True,\n",
+ " max_expansion_hops=2\n",
")\n",
- "plt.show()"
+ "\n",
+ "g_res = retriever.retrieve(query, max_results=1)\n",
+ "\n",
+ "print(\"--- GRAPHRAG FINAL ANSWER ---\")\n",
+ "if g_res:\n",
+ " print(g_res[0].content)\n",
+ " if g_res[0].related_entities:\n",
+ " print(\"\\n--- CONNECTED ENTITIES DISCOVERED ---\")\n",
+ " for ent in g_res[0].related_entities[:5]:\n",
+ " print(f\"- {ent['content']} ({ent['type']}) via {ent['relationship']}\")\n",
+ "else:\n",
+ " print(\"No relevant multi-hop context found.\")"
]
}
],
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 00000000..27503d40
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,11 @@
+services:
+ falkordb:
+ image: falkordb/falkordb:latest
+ ports:
+ - "6379:6379"
+ volumes:
+ - falkordb_data:/data
+ restart: always
+
+volumes:
+ falkordb_data:
diff --git a/semantica/graph_store/graph_store.py b/semantica/graph_store/graph_store.py
index d4e2b503..f7da5c47 100644
--- a/semantica/graph_store/graph_store.py
+++ b/semantica/graph_store/graph_store.py
@@ -704,11 +704,37 @@ class GraphStore:
depth: int = 1,
**options,
) -> List[Dict[str, Any]]:
- """Get neighboring nodes."""
+ """
+ Get neighboring nodes.
+
+ Args:
+ node_id: Node ID
+ rel_type: Relationship type filter
+ direction: Relationship direction
+ depth: Traversal depth (alias: hops)
+ **options: Additional options
+ """
+ # Support 'hops' as alias for 'depth' for ContextRetriever compatibility
+ actual_depth = options.get("hops", depth)
return self._manager.analytics.get_neighbors(
- node_id, rel_type, direction, depth, **options
+ node_id, rel_type, direction, actual_depth, **options
)
+ def query(self, query: str, parameters: Optional[Dict[str, Any]] = None, **options) -> List[Dict[str, Any]]:
+ """
+ Execute a query and return results (Compatibility method for ContextRetriever).
+
+ Args:
+ query: Query string (Cypher)
+ parameters: Query parameters
+ **options: Additional options
+
+ Returns:
+ List of result records
+ """
+ result = self.execute_query(query, parameters, **options)
+ return result.get("records", [])
+
# Management operations
def get_stats(self) -> Dict[str, Any]:
"""Get graph statistics."""
diff --git a/semantica/kg/graph_builder.py b/semantica/kg/graph_builder.py
index 174082e9..707572b0 100644
--- a/semantica/kg/graph_builder.py
+++ b/semantica/kg/graph_builder.py
@@ -62,6 +62,7 @@ class GraphBuilder:
temporal_granularity="day",
track_history=False,
version_snapshots=False,
+ graph_store=None,
**kwargs,
):
"""
@@ -75,6 +76,7 @@ class GraphBuilder:
temporal_granularity: Time granularity ("second", "minute", "hour", "day", "week", "month", "year")
track_history: Track historical changes to entities/relationships
version_snapshots: Create version snapshots at intervals
+ graph_store: Optional GraphStore instance for persistence
**kwargs: Additional configuration options
"""
self.merge_entities = merge_entities
@@ -84,6 +86,7 @@ class GraphBuilder:
self.temporal_granularity = temporal_granularity
self.track_history = track_history
self.version_snapshots = version_snapshots
+ self.graph_store = graph_store
# Initialize logging
from ..utils.logging import get_logger
@@ -321,6 +324,29 @@ class GraphBuilder:
},
}
+ # Persist to GraphStore if available
+ if self.graph_store:
+ self.logger.info("Persisting knowledge graph to GraphStore")
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Persisting to GraphStore..."
+ )
+
+ # Add nodes
+ node_count = self.graph_store.add_nodes(resolved_entities)
+
+ # Prepare edges for add_edges (expects source_id, target_id, type)
+ formatted_edges = []
+ for rel in all_relationships:
+ formatted_edges.append({
+ "source_id": rel.get("source"),
+ "target_id": rel.get("target"),
+ "type": rel.get("type", "RELATED_TO"),
+ "properties": rel.get("metadata", {})
+ })
+
+ edge_count = self.graph_store.add_edges(formatted_edges)
+ self.logger.info(f"Persisted {node_count} nodes and {edge_count} edges")
+
# Detect and resolve conflicts if conflict detector is available
if self.conflict_detector:
self.logger.debug("Detecting conflicts in graph")