Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Expand GraphRAG notebooks with more cells, less dense code, and improved markdown documentation

KaifAhmad107bd371e7dcf
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 6008f171..61474bce 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -1,891 +1,1967 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "id": "31d1a12c",
- "metadata": {},
- "source": [
-<<<<<<< HEAD
-<<<<<<< Updated upstream
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)\n",
- "\n",
- "# GraphRAG Complete - End-to-End Pipeline\n",
-=======
- "# \ud83e\uddea GraphRAG: Skincare Intelligence System\n",
- "## \ud83d\udcd6 Overview\n",
- "This notebook demonstrates the construction and querying of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain using the Semantica framework.\n",
- "\n",
- "### \ud83c\udfd7\ufe0f Pipeline Architecture\n",
-=======
- "# πŸ§ͺ GraphRAG: Skincare Intelligence System\n",
- "## πŸ“– Overview\n",
- "This notebook demonstrates the construction and querying of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain using the Semantica framework.\n",
- "\n",
- "### πŸ—οΈ Pipeline Architecture\n",
->>>>>>> main
- "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 of entities and relationships using Llama 3.1.\n",
- "4. **Phase 3: Refinement**: Autonomous deduplication and conflict resolution.\n",
- "5. **Phase 4: Multi-Hop Question Answering**: Interactive user queries using **AgentContext (Hybrid Retrieval)**."
-<<<<<<< HEAD
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "id": "fdef52b8",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Note: you may need to restart the kernel to use updated packages.\n"
- ]
- },
- {
- "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"
- ]
- }
- ],
- "source": [
- "# Install dependencies\n",
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "id": "508c1ce5",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u2705 Phase 0 Complete. Seeded 3 primary nodes.\n"
- ]
- }
- ],
- "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",
->>>>>>> Stashed changes
- "\n",
- "## Overview\n",
- "\n",
-<<<<<<< Updated upstream
- "This notebook demonstrates a **complete end-to-end GraphRAG (Graph-based Retrieval Augmented Generation) system** using Semantica framework. It showcases how to build a production-ready GraphRAG system that combines vector search with knowledge graph traversal for enhanced retrieval and question answering.\n",
-=======
- "config_dict = {\n",
- " \"project_name\": \"Skincare_Intelligence\",\n",
- " \"embedding\": {\"provider\": \"sentence_transformers\", \"model\": \"all-MiniLM-L6-v2\"}, \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\": 384},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"merge_entities\": True}\n",
- "}\n",
->>>>>>> Stashed changes
- "\n",
- "**Key Features:**\n",
- "\n",
- "- **Real-World Data**: Uses actual data sources via MCP servers, web scraping, and RSS feeds (NO mock data)\n",
- "- **Complete Pipeline**: From data ingestion to LLM-powered question answering\n",
- "- **Hybrid Retrieval**: Combines vector similarity search with knowledge graph traversal\n",
- "- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",
- "- **20+ Semantica Modules**: Demonstrates comprehensive use of the framework\n",
- "\n",
- "**Documentation**: [API Reference](https://semantica.readthedocs.io/concepts/) β€’ [GraphRAG Guide](https://semantica.readthedocs.io/concepts/)\n",
- "\n",
-<<<<<<< Updated upstream
- "### What You'll Learn\n",
- "\n",
- "- How to ingest real-world data from multiple sources (MCP, web, feeds)\n",
- "- How to build knowledge graphs from unstructured text\n",
- "- How to implement hybrid search combining vectors and graphs\n",
- "- How to use ContextRetriever for intelligent context expansion\n",
- "- How to integrate LLMs with GraphRAG for question answering\n",
- "- How to visualize and export knowledge graphs\n",
- "\n",
- "### Pipeline Overview\n",
- "\n",
- "**Real-World Data Sources (MCP/Web/Feeds) β†’ Parse β†’ Extract Entities & Relationships β†’ Build Knowledge Graph β†’ Generate Embeddings β†’ Vector Store β†’ Hybrid Search β†’ Context Retrieval β†’ GraphRAG Query System β†’ LLM Integration β†’ Answer Generation**\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n",
- "\n",
- "Install Semantica from PyPI:\n",
- "\n",
- "```bash\n",
- "pip install semantica\n",
- "\n",
- "# Or with all optional dependencies:\n",
- "pip install semantica[all]\n",
- "```\n",
- "\n",
- "### Additional Dependencies\n",
- "\n",
- "```bash\n",
- "pip install openai anthropic # For LLM integration\n",
- "pip install jupyter # For running this notebook\n",
- "```\n"
-=======
- "print(f\"\u2705 Phase 0 Complete. Seeded {len(foundation_data['entities'])} primary nodes.\")"
->>>>>>> Stashed changes
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
-<<<<<<< Updated upstream
- "## Step 1: Setup and Import Semantica Modules\n",
- "\n",
- "Import all necessary Semantica modules for the complete GraphRAG pipeline. This includes modules for ingestion, parsing, extraction, graph building, embeddings, vector storage, context retrieval, and more.\n",
- "\n"
-=======
->>>>>>> main
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "id": "fdef52b8",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Note: you may need to restart the kernel to use updated packages.\n"
- ]
- },
- {
- "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"
- ]
- }
- ],
- "source": [
- "# Install dependencies\n",
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "id": "508c1ce5",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 0 Complete. Seeded 3 primary nodes.\n"
- ]
- }
- ],
- "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 Configuration\n",
- "os.environ[\"GROQ_API_KEY\"] = \"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\"\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Skincare_Intelligence\",\n",
- " \"embedding\": {\"provider\": \"sentence_transformers\", \"model\": \"all-MiniLM-L6-v2\"}, \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\": 384},\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=384)\n",
- "\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",
- " ],\n",
- " \"relationships\": [\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",
- "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.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0b1a2ebc",
- "metadata": {},
- "source": [
- "## πŸ“₯ 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": 9,
- "id": "52f20118",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Ingesting from: https://makeupandbeautyblog.com/feed\n",
- "Ingesting from: https://www.drbaileyskincare.com/blogs/blog.atom\n",
- "βœ… Phase 1 Complete. Generated 74 semantic chunks.\n"
- ]
- }
- ],
- "source": [
- "from semantica.ingest import FeedIngestor\n",
- "from semantica.split import EntityAwareChunker\n",
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "sources = []\n",
- "feed_ingestor = FeedIngestor()\n",
- "\n",
- "# 1. RSS Ingestion\n",
- "feed_urls = [\n",
- " \"https://makeupandbeautyblog.com/feed\",\n",
- " \"https://www.drbaileyskincare.com/blogs/blog.atom\"\n",
- "]\n",
- "\n",
- "for url in feed_urls:\n",
- " try:\n",
- " print(f\"Ingesting from: {url}\")\n",
- " feed_data = feed_ingestor.ingest_feed(url)\n",
- " sources.extend([item.content or item.description for item in feed_data.items[:3]])\n",
- " except Exception as e:\n",
- " print(f\"Failed to ingest {url}: {e}\")\n",
- "\n",
- "# 2. Local Expert Guide\n",
- "expert_content = \"\"\"\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",
- "\"\"\"\n",
- "sources.append(expert_content)\n",
- "\n",
- "# 3. Chunking & Normalization\n",
- "normalizer = TextNormalizer()\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",
- " all_chunks.extend(chunker.chunk(norm_text))\n",
- "\n",
- "print(f\"βœ… Phase 1 Complete. Generated {len(all_chunks)} semantic chunks.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "de3c9cc0",
- "metadata": {},
- "source": [
- "## 🧠 Phase 2: Semantic Extraction\n",
- "Using **Groq (Llama 3.1 8B)** to extract entities and relationships."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "id": "10be6143",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Extracting intelligence from chunks...\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "LLM relation extraction failed: Failed to parse JSON from Groq response: No JSON structure found in response\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 2 Complete. Extracted 29 entities.\n"
- ]
- }
- ],
- "source": [
- "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",
- "\n",
- "ner = NERExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "rel_ext = RelationExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "\n",
- "combined_results = {\"entities\": [], \"relationships\": []}\n",
- "\n",
- "print(\"Extracting intelligence from chunks...\")\n",
- "for chunk in all_chunks[:5]:\n",
- " txt = str(chunk.text)\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",
- " 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 2 Complete. Extracted {len(combined_results['entities'])} entities.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0ef80273",
- "metadata": {},
- "source": [
- "## ✨ Phase 3: Graph Refinement\n",
- "Merging fragments and building the final Knowledge Graph."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "id": "c836e86f",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ… Phase 3 Complete. Graph contains 10 resolved entities.\n"
- ]
- }
- ],
- "source": [
- "from semantica.kg import GraphBuilder, EntityResolver\n",
- "\n",
- "# 1. Build & Vectorize\n",
- "gb = GraphBuilder(merge_entities=True)\n",
- "kg = gb.build(sources=[combined_results])\n",
- "\n",
- "# 2. Deduplicate\n",
- "resolver = EntityResolver(similarity_threshold=0.85)\n",
- "kg_final = {**kg, 'entities': resolver.resolve_entities(kg['entities'])}\n",
- "\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",
- "print(f\"βœ… Phase 3 Complete. Graph contains {len(kg_final['entities'])} resolved entities.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "76cbe42a",
- "metadata": {},
- "source": [
- "## πŸ’¬ Phase 4: Interactive GraphRAG Question Answering\n",
- "Using **AgentContext** for unified hybrid retrieval."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "id": "29d04181",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "πŸ” Processing Multi-Hop Query: What ingredients synergize with Retinol to prevent irritation?\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\numpy\\linalg\\linalg.py:2582: RuntimeWarning:\n",
- "\n",
- "overflow encountered in multiply\n",
- "\n",
- "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:498: RuntimeWarning:\n",
- "\n",
- "invalid value encountered in divide\n",
- "\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "❌ No relevant context found.\n"
- ]
- }
- ],
- "source": [
- "from semantica.context import AgentContext\n",
- "from semantica.reasoning import InferenceEngine\n",
- "\n",
- "# 1. Initialize AgentContext (Hybrid Retrieval)\n",
- "ctx = AgentContext(\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 = \"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 using AgentContext\n",
- "context_results = ctx.retrieve(user_query, max_results=2)\n",
- "\n",
- "if context_results:\n",
- " print(\"\\n--- 🧠 MULTI-HOP CONTEXT DISCOVERED ---\")\n",
- " for res in context_results:\n",
- " print(f\"Recall: {res['content'][:120]}...\")\n",
- " if res.get('related_entities'):\n",
- " print(f\" πŸ”— Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\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",
- " \n",
- " try:\n",
- " final_answer = engine.generate(prompt)\n",
- " print(\"\\n--- ✨ FINAL GRAPHRAG ANSWER ---\")\n",
- " print(final_answer)\n",
- " except Exception as e:\n",
- " print(f\"\\n(LLM synthesis skipped: {e})\")\n",
- "else:\n",
- " print(\"\\n❌ No relevant context found.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "5c478f11",
- "metadata": {},
- "source": [
- "## πŸ“Š Visualizing the Intelligence\n",
- "A final look at the relationships we've built."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "id": "851383de",
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "viz = KGVisualizer()\n",
- "viz.visualize_network(kg_final, layout=\"spring\", title=\"Skincare Ingredient Intelligence Graph\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "a45000b6",
- "metadata": {},
- "outputs": [],
- "source": []
-=======
- "## \ud83d\udce5 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": 9,
- "id": "52f20118",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Ingesting from: https://makeupandbeautyblog.com/feed\n",
- "Ingesting from: https://www.drbaileyskincare.com/blogs/blog.atom\n",
- "\u2705 Phase 1 Complete. Generated 74 semantic chunks.\n"
- ]
- }
- ],
- "source": [
- "from semantica.ingest import FeedIngestor\n",
- "from semantica.split import EntityAwareChunker\n",
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "sources = []\n",
- "feed_ingestor = FeedIngestor()\n",
- "\n",
- "# 1. RSS Ingestion\n",
- "feed_urls = [\n",
- " \"https://makeupandbeautyblog.com/feed\",\n",
- " \"https://www.drbaileyskincare.com/blogs/blog.atom\"\n",
- "]\n",
- "\n",
- "for url in feed_urls:\n",
- " try:\n",
- " print(f\"Ingesting from: {url}\")\n",
- " feed_data = feed_ingestor.ingest_feed(url)\n",
- " sources.extend([item.content or item.description for item in feed_data.items[:3]])\n",
- " except Exception as e:\n",
- " print(f\"Failed to ingest {url}: {e}\")\n",
- "\n",
- "# 2. Local Expert Guide\n",
- "expert_content = \"\"\"\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",
- "\"\"\"\n",
- "sources.append(expert_content)\n",
- "\n",
- "# 3. Chunking & Normalization\n",
- "normalizer = TextNormalizer()\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",
- " all_chunks.extend(chunker.chunk(norm_text))\n",
- "\n",
- "print(f\"\u2705 Phase 1 Complete. Generated {len(all_chunks)} semantic chunks.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "de3c9cc0",
- "metadata": {},
- "source": [
- "## \ud83e\udde0 Phase 2: Semantic Extraction\n",
- "Using **Groq (Llama 3.1 8B)** to extract entities and relationships."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "id": "10be6143",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Extracting intelligence from chunks...\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "LLM relation extraction failed: Failed to parse JSON from Groq response: No JSON structure found in response\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u2705 Phase 2 Complete. Extracted 29 entities.\n"
- ]
- }
- ],
- "source": [
- "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",
- "\n",
- "ner = NERExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "rel_ext = RelationExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
- "\n",
- "combined_results = {\"entities\": [], \"relationships\": []}\n",
- "\n",
- "print(\"Extracting intelligence from chunks...\")\n",
- "for chunk in all_chunks[:5]:\n",
- " txt = str(chunk.text)\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",
- " 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\"\u2705 Phase 2 Complete. Extracted {len(combined_results['entities'])} entities.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0ef80273",
- "metadata": {},
- "source": [
- "## \u2728 Phase 3: Graph Refinement\n",
- "Merging fragments and building the final Knowledge Graph."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "id": "c836e86f",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u2705 Phase 3 Complete. Graph contains 10 resolved entities.\n"
- ]
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)\n",
+ "\n",
+ "# GraphRAG Complete - End-to-End Pipeline\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates a **complete end-to-end GraphRAG (Graph-based Retrieval Augmented Generation) system** using the Semantica framework. \n",
+ "\n",
+ "GraphRAG combines the power of:\n",
+ "- **Vector Search**: Semantic similarity matching for finding relevant text chunks\n",
+ "- **Knowledge Graphs**: Structured representation of entities and their relationships\n",
+ "- **Graph Traversal**: Multi-hop reasoning across entity connections\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Real-World Data**: Uses actual data sources via RSS feeds, web scraping, and local files (NO mock data)\n",
+ "- **Complete Pipeline**: From data ingestion to LLM-powered question answering\n",
+ "- **Hybrid Retrieval**: Combines vector similarity search with knowledge graph traversal\n",
+ "- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",
+ "- **20+ Semantica Modules**: Demonstrates comprehensive use of the framework\n",
+ "\n",
+ "### What You'll Learn\n",
+ "\n",
+ "- How to ingest real-world data from multiple sources (RSS feeds, web, local files)\n",
+ "- How to build knowledge graphs from unstructured text\n",
+ "- How to implement hybrid search combining vectors and graphs\n",
+ "- How to use ContextRetriever for intelligent context expansion\n",
+ "- How to integrate LLMs with GraphRAG for question answering\n",
+ "- How to visualize and export knowledge graphs\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "The complete GraphRAG pipeline consists of 7 phases:\n",
+ "\n",
+ "1. **Phase 0**: Setup & Foundation Seeding\n",
+ "2. **Phase 1**: Multi-Source Ingestion\n",
+ "3. **Phase 2**: Document Processing & Chunking\n",
+ "4. **Phase 3**: Comprehensive Semantic Extraction\n",
+ "5. **Phase 4**: Knowledge Graph Construction & Refinement\n",
+ "6. **Phase 5**: Vector Store Population\n",
+ "7. **Phase 6**: GraphRAG Query System\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n",
+ "\n",
+ "Install Semantica and required dependencies:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Install Semantica and all required dependencies\n",
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n",
+ "\n",
+ "In this phase, we configure Semantica with all necessary components for the GraphRAG pipeline.\n",
+ "\n",
+ "### Configuration Components\n",
+ "\n",
+ "- **Embedding Provider**: Sentence Transformers for generating text embeddings\n",
+ "- **Extraction Provider**: Groq LLM for entity and relationship extraction\n",
+ "- **Inference Provider**: Groq LLM for answer generation\n",
+ "- **Vector Store**: FAISS for efficient vector similarity search\n",
+ "- **Knowledge Graph**: NetworkX backend for graph operations\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import required modules\n",
+ "import os\n",
+ "import json\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.seed import SeedDataManager\n",
+ "from semantica.vector_store import VectorStore\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.1: Set API Keys\n",
+ "\n",
+ "Configure API keys for LLM providers. In production, use environment variables.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Set up API keys\n",
+ "# Note: In production, use environment variables: export GROQ_API_KEY=\"your-key\"\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-groq-api-key-here\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.2: Configure Semantica\n",
+ "\n",
+ "Create a comprehensive configuration dictionary that specifies:\n",
+ "- Embedding model and provider\n",
+ "- Extraction model and provider \n",
+ "- Inference model and provider\n",
+ "- Vector store backend and dimensions\n",
+ "- Knowledge graph backend and settings\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create configuration dictionary\n",
+ "config_dict = {\n",
+ " \"project_name\": \"GraphRAG_Complete\",\n",
+ " \n",
+ " # Embedding configuration\n",
+ " \"embedding\": {\n",
+ " \"provider\": \"sentence_transformers\", \n",
+ " \"model\": \"all-MiniLM-L6-v2\" # 384-dimensional embeddings\n",
+ " }, \n",
+ " \n",
+ " # Extraction configuration (for NER and relation extraction)\n",
+ " \"extraction\": {\n",
+ " \"provider\": \"groq\", \n",
+ " \"model\": \"llama-3.1-8b-instant\", \n",
+ " \"temperature\": 0.0 # Deterministic extraction\n",
+ " },\n",
+ " \n",
+ " # Inference configuration (for answer generation)\n",
+ " \"inference\": {\n",
+ " \"provider\": \"groq\",\n",
+ " \"model\": \"llama-3.1-70b-versatile\"\n",
+ " },\n",
+ " \n",
+ " # Vector store configuration\n",
+ " \"vector_store\": {\n",
+ " \"provider\": \"faiss\", \n",
+ " \"dimension\": 384 # Must match embedding dimension\n",
+ " },\n",
+ " \n",
+ " # Knowledge graph configuration\n",
+ " \"knowledge_graph\": {\n",
+ " \"backend\": \"networkx\", \n",
+ " \"merge_entities\": True # Automatically merge duplicate entities\n",
+ " }\n",
+ "}\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.3: Initialize Core Components\n",
+ "\n",
+ "Initialize the main Semantica core and vector store using the configuration.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load configuration and initialize Semantica core\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "\n",
+ "# Initialize vector store with matching dimension\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "\n",
+ "print(\"Configuration complete. Semantica initialized.\")\n",
+ "print(f\" - Embedding dimension: 384\")\n",
+ "print(f\" - Vector store backend: FAISS\")\n",
+ "print(f\" - Knowledge graph backend: NetworkX\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0.1: Foundation Seeding\n",
+ "\n",
+ "Seed the knowledge graph with verified ground truth data. This provides a foundation of known facts that the system can build upon.\n",
+ "\n",
+ "### Why Foundation Seeding?\n",
+ "\n",
+ "- **Quality Assurance**: Start with verified, accurate knowledge\n",
+ "- **Domain Expertise**: Incorporate expert knowledge into the graph\n",
+ "- **Better Extraction**: Guide entity extraction with known entities\n",
+ "- **Conflict Resolution**: Use seed data as reference for resolving conflicts\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define foundation data (ground truth)\n",
+ "foundation_data = {\n",
+ " \"entities\": [\n",
+ " {\n",
+ " \"id\": \"hyaluronic_acid\", \n",
+ " \"name\": \"Hyaluronic Acid\", \n",
+ " \"type\": \"Ingredient\", \n",
+ " \"properties\": {\"role\": \"Humectant\"}\n",
+ " },\n",
+ " {\n",
+ " \"id\": \"retinol\", \n",
+ " \"name\": \"Retinol\", \n",
+ " \"type\": \"Ingredient\", \n",
+ " \"properties\": {\"role\": \"Anti-aging actives\"}\n",
+ " },\n",
+ " {\n",
+ " \"id\": \"niacinamide\", \n",
+ " \"name\": \"Niacinamide\", \n",
+ " \"type\": \"Ingredient\", \n",
+ " \"properties\": {\"role\": \"Barrier repair\"}\n",
+ " }\n",
+ " ],\n",
+ " \"relationships\": [\n",
+ " {\n",
+ " \"source\": \"hyaluronic_acid\", \n",
+ " \"target\": \"niacinamide\", \n",
+ " \"type\": \"COMPLEMENTS\", \n",
+ " \"properties\": {\"benefit\": \"Hydration + Barrier\"}\n",
+ " }\n",
+ " ]\n",
+ "}\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.1.2: Save and Register Seed Data\n",
+ "\n",
+ "Save the foundation data to a JSON file and register it with SeedDataManager.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Save foundation data to JSON file\n",
+ "with open(\"skincare_base.json\", \"w\") as f:\n",
+ " json.dump(foundation_data, f, indent=2)\n",
+ "\n",
+ "print(\"Foundation data saved to skincare_base.json\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.1.3: Create Foundation Graph\n",
+ "\n",
+ "Use SeedDataManager to load the seed data and create the foundation graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize SeedDataManager\n",
+ "seed_manager = SeedDataManager()\n",
+ "\n",
+ "# Register the seed data source\n",
+ "seed_manager.register_source(\"core_ontology\", \"json\", \"skincare_base.json\")\n",
+ "\n",
+ "# Create foundation graph from seed data\n",
+ "foundation_graph = seed_manager.create_foundation_graph()\n",
+ "\n",
+ "print(f\"Phase 0.1 Complete. Seeded {len(foundation_data['entities'])} primary nodes and {len(foundation_data['relationships'])} relationships.\")\n",
+ "print(f\" - Foundation graph created successfully\")\n",
+ "print(f\" - Seed data will be merged with extracted data in Phase 4\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Multi-Source Ingestion\n",
+ "\n",
+ "Ingest real-world data from multiple sources to build a comprehensive knowledge base.\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "We'll ingest from three types of sources:\n",
+ "\n",
+ "1. **RSS/Atom Feeds**: Real-time updates from blogs and news sites\n",
+ "2. **Web Pages**: Structured content from websites\n",
+ "3. **Local Files**: Expert guides and documentation\n",
+ "\n",
+ "### Ingestion Strategy\n",
+ "\n",
+ "- **FeedIngestor**: Handles RSS and Atom feed formats\n",
+ "- **WebIngestor**: Scrapes and extracts content from web pages\n",
+ "- **FileIngestor**: Reads local text files and documents\n",
+ "- **TextNormalizer**: Cleans and normalizes all ingested content\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import ingestion and normalization modules\n",
+ "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.1: Initialize Ingestion Components\n",
+ "\n",
+ "Create instances of the ingestion classes and text normalizer.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize ingestion components\n",
+ "normalizer = TextNormalizer()\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "web_ingestor = WebIngestor()\n",
+ "file_ingestor = FileIngestor()\n",
+ "\n",
+ "# Container for all ingested content\n",
+ "all_content = []\n",
+ "\n",
+ "print(\"Ingestion components initialized.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.2: Ingest RSS/Atom Feeds\n",
+ "\n",
+ "RSS and Atom feeds provide structured, regularly updated content from blogs and news sites.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define feed URLs\n",
+ "feed_urls = [\n",
+ " \"https://makeupandbeautyblog.com/feed\",\n",
+ " \"https://www.drbaileyskincare.com/blogs/blog.atom\"\n",
+ "]\n",
+ "\n",
+ "print(\"Ingesting from RSS/Atom feeds...\")\n",
+ "for url in feed_urls:\n",
+ " try:\n",
+ " print(f\" Processing: {url}\")\n",
+ " feed_data = feed_ingestor.ingest_feed(url)\n",
+ " \n",
+ " # Extract content from feed items (limit to 3 per feed to avoid rate limits)\n",
+ " for item in feed_data.items[:3]:\n",
+ " text = item.content or item.description or item.title\n",
+ " if text:\n",
+ " all_content.append(text)\n",
+ " print(f\" Successfully ingested {min(3, len(feed_data.items))} items\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Failed to ingest {url}: {e}\")\n",
+ "\n",
+ "print(f\"\\nTotal feed items ingested: {len([c for c in all_content if c])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.3: Ingest Web Pages\n",
+ "\n",
+ "Web ingestion allows us to extract content from specific web pages, including Wikipedia articles and documentation.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define web URLs to ingest\n",
+ "web_urls = [\n",
+ " \"https://en.wikipedia.org/wiki/Retinol\"\n",
+ "]\n",
+ "\n",
+ "print(\"Ingesting from web pages...\")\n",
+ "for url in web_urls:\n",
+ " try:\n",
+ " print(f\" Processing: {url}\")\n",
+ " content = web_ingestor.ingest_url(url)\n",
+ " if content and content.text:\n",
+ " all_content.append(content.text)\n",
+ " print(f\" Successfully ingested content ({len(content.text)} characters)\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Failed to ingest {url}: {e}\")\n",
+ "\n",
+ "print(f\"\\nTotal web pages ingested: {len([c for c in all_content if c])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.4: Ingest Local Files\n",
+ "\n",
+ "Local files provide expert knowledge and documentation that may not be available online.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define local files to ingest\n",
+ "local_files = [\n",
+ " \"expert_skincare_guide.txt\",\n",
+ " \"data/sample_graphrag_paper.txt\"\n",
+ "]\n",
+ "\n",
+ "print(\"Ingesting from local files...\")\n",
+ "for file_path in local_files:\n",
+ " try:\n",
+ " if os.path.exists(file_path):\n",
+ " print(f\" Processing: {file_path}\")\n",
+ " files = file_ingestor.ingest_file(file_path)\n",
+ " for file_data in files:\n",
+ " if hasattr(file_data, 'text') and file_data.text:\n",
+ " all_content.append(file_data.text)\n",
+ " print(f\" Successfully ingested {file_path}\")\n",
+ " else:\n",
+ " print(f\" Warning: File not found: {file_path}\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Failed to ingest {file_path}: {e}\")\n",
+ "\n",
+ "print(f\"\\nTotal local files processed: {len([c for c in all_content if c])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.5: Normalize Content\n",
+ "\n",
+ "Text normalization cleans and standardizes the ingested content:\n",
+ "- Removes extra whitespace\n",
+ "- Normalizes encoding\n",
+ "- Standardizes formatting\n",
+ "- Filters out very short content\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Normalize all ingested content\n",
+ "print(\"Normalizing content...\")\n",
+ "normalized_content = []\n",
+ "\n",
+ "for text in all_content:\n",
+ " if text and len(text) > 50: # Filter out very short content\n",
+ " normalized_text = normalizer.normalize(text)\n",
+ " normalized_content.append(normalized_text)\n",
+ "\n",
+ "print(f\"\\nPhase 1 Complete. Ingested {len(normalized_content)} documents from multiple sources.\")\n",
+ "print(f\" - Feed items: {len(feed_urls)} feeds processed\")\n",
+ "print(f\" - Web pages: {len(web_urls)} URLs processed\")\n",
+ "print(f\" - Local files: {len(local_files)} files processed\")\n",
+ "print(f\" - Total normalized documents: {len(normalized_content)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Document Processing & Chunking\n",
+ "\n",
+ "Split documents into semantic chunks that preserve entity boundaries and maintain context.\n",
+ "\n",
+ "### Why Chunking?\n",
+ "\n",
+ "- **Processing Efficiency**: LLMs have token limits\n",
+ "- **Context Preservation**: Maintain semantic coherence within chunks\n",
+ "- **Entity Awareness**: Preserve entity boundaries to avoid splitting important relationships\n",
+ "\n",
+ "### Chunking Strategy\n",
+ "\n",
+ "- **EntityAwareChunker**: Intelligently splits text while preserving entity mentions\n",
+ "- **Chunk Size**: 1000 characters (balance between context and processing efficiency)\n",
+ "- **Overlap**: 200 characters (ensures continuity between chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import chunking module\n",
+ "from semantica.split import EntityAwareChunker\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 2.1: Initialize Chunker\n",
+ "\n",
+ "Configure the EntityAwareChunker with appropriate chunk size and overlap.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize EntityAwareChunker\n",
+ "# - chunk_size: Maximum characters per chunk (1000)\n",
+ "# - chunk_overlap: Characters to overlap between chunks (200) for context continuity\n",
+ "chunker = EntityAwareChunker(chunk_size=1000, chunk_overlap=200)\n",
+ "\n",
+ "print(\"EntityAwareChunker initialized.\")\n",
+ "print(f\" - Chunk size: 1000 characters\")\n",
+ "print(f\" - Overlap: 200 characters\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 2.2: Chunk All Documents\n",
+ "\n",
+ "Process all normalized documents into semantic chunks.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Chunk all normalized documents\n",
+ "all_chunks = []\n",
+ "\n",
+ "print(\"Chunking documents...\")\n",
+ "for i, text in enumerate(normalized_content, 1):\n",
+ " if text:\n",
+ " chunks = chunker.chunk(text)\n",
+ " all_chunks.extend(chunks)\n",
+ " print(f\" Document {i}: {len(chunks)} chunks created\")\n",
+ "\n",
+ "print(f\"\\nPhase 2 Complete. Generated {len(all_chunks)} semantic chunks.\")\n",
+ "if all_chunks:\n",
+ " avg_size = sum(len(str(c.text)) for c in all_chunks) / len(all_chunks)\n",
+ " print(f\" - Average chunk size: {avg_size:.0f} characters\")\n",
+ " print(f\" - Total chunks: {len(all_chunks)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Comprehensive Semantic Extraction\n",
+ "\n",
+ "Extract structured knowledge from unstructured text using multiple extraction methods.\n",
+ "\n",
+ "### Extraction Methods\n",
+ "\n",
+ "We'll use five different extraction techniques:\n",
+ "\n",
+ "1. **Named Entity Recognition (NER)**: Identify entities (people, places, concepts)\n",
+ "2. **Relation Extraction**: Find relationships between entities\n",
+ "3. **Triplet Extraction**: Extract subject-predicate-object triplets (RDF format)\n",
+ "4. **Event Detection**: Identify events and their participants\n",
+ "5. **Coreference Resolution**: Link pronouns and references to entities\n",
+ "\n",
+ "### Why Multiple Methods?\n",
+ "\n",
+ "- **Comprehensive Coverage**: Different methods capture different aspects\n",
+ "- **Redundancy**: Multiple methods increase extraction reliability\n",
+ "- **Complementary Information**: Each method provides unique insights\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import semantic extraction modules\n",
+ "from semantica.semantic_extract import (\n",
+ " NERExtractor, \n",
+ " RelationExtractor, \n",
+ " TripletExtractor,\n",
+ " EventDetector,\n",
+ " CoreferenceResolver\n",
+ ")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.1: Initialize Extractors\n",
+ "\n",
+ "Create instances of all extraction classes with appropriate configurations.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Named Entity Recognition extractor\n",
+ "# Uses LLM method with Groq for high-quality entity extraction\n",
+ "ner = NERExtractor(\n",
+ " method=\"llm\", \n",
+ " provider=\"groq\", \n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "# Initialize Relation Extraction extractor\n",
+ "# Extracts relationships between entities\n",
+ "rel_ext = RelationExtractor(\n",
+ " method=\"llm\", \n",
+ " provider=\"groq\", \n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "# Initialize Triplet Extraction extractor\n",
+ "# Extracts RDF-style triplets (subject-predicate-object)\n",
+ "triplet_ext = TripletExtractor(\n",
+ " method=\"llm\", \n",
+ " provider=\"groq\", \n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "# Initialize Event Detection extractor\n",
+ "# Detects events and their participants\n",
+ "event_detector = EventDetector()\n",
+ "\n",
+ "# Initialize Coreference Resolution\n",
+ "# Links pronouns and references to entities\n",
+ "coref_resolver = CoreferenceResolver()\n",
+ "\n",
+ "print(\"All extractors initialized successfully.\")\n",
+ "print(\" - NER Extractor: Ready\")\n",
+ "print(\" - Relation Extractor: Ready\")\n",
+ "print(\" - Triplet Extractor: Ready\")\n",
+ "print(\" - Event Detector: Ready\")\n",
+ "print(\" - Coreference Resolver: Ready\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.2: Initialize Results Container\n",
+ "\n",
+ "Create a dictionary to store all extraction results.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Container for all extraction results\n",
+ "combined_results = {\n",
+ " \"entities\": [],\n",
+ " \"relationships\": [],\n",
+ " \"triplets\": [],\n",
+ " \"events\": []\n",
+ "}\n",
+ "\n",
+ "print(\"Results container initialized.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.3: Extract Named Entities\n",
+ "\n",
+ "Named Entity Recognition identifies entities such as:\n",
+ "- **Persons**: People, characters\n",
+ "- **Organizations**: Companies, institutions\n",
+ "- **Locations**: Places, regions\n",
+ "- **Concepts**: Ideas, topics\n",
+ "- **Products**: Items, ingredients\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Process first 10 chunks to avoid rate limits\n",
+ "print(\"Extracting semantic information from chunks...\")\n",
+ "print(f\"Processing {min(10, len(all_chunks))} chunks...\\n\")\n",
+ "\n",
+ "for i, chunk in enumerate(all_chunks[:10]):\n",
+ " txt = str(chunk.text)\n",
+ " if len(txt) < 50:\n",
+ " continue\n",
+ " \n",
+ " print(f\"Chunk {i+1}/{min(10, len(all_chunks))}:\")\n",
+ " \n",
+ " try:\n",
+ " # Step 1: Named Entity Recognition\n",
+ " print(f\" Extracting entities...\")\n",
+ " entities = ner.extract(txt)\n",
+ " \n",
+ " for e in entities:\n",
+ " combined_results[\"entities\"].append({\n",
+ " \"name\": e.text, \n",
+ " \"type\": e.label, \n",
+ " \"id\": e.text.lower().replace(' ', '_').replace('-', '_'),\n",
+ " \"confidence\": getattr(e, 'confidence', 0.8)\n",
+ " })\n",
+ " \n",
+ " print(f\" Found {len(entities)} entities\")\n",
+ " \n",
+ " # Step 2: Relation Extraction (requires entities)\n",
+ " if entities:\n",
+ " print(f\" Extracting relationships...\")\n",
+ " try:\n",
+ " relations = rel_ext.extract(txt, entities=entities)\n",
+ " \n",
+ " for r in relations:\n",
+ " combined_results[\"relationships\"].append({\n",
+ " \"source\": r.subject, \n",
+ " \"target\": r.object, \n",
+ " \"type\": r.predicate,\n",
+ " \"confidence\": getattr(r, 'confidence', 0.7)\n",
+ " })\n",
+ " \n",
+ " print(f\" Found {len(relations)} relationships\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Error extracting relationships: {e}\")\n",
+ " else:\n",
+ " print(f\" Skipping relationship extraction (no entities found)\")\n",
+ " \n",
+ " # Step 3: Triplet Extraction\n",
+ " print(f\" Extracting triplets...\")\n",
+ " try:\n",
+ " triplets = triplet_ext.extract(txt, entities=entities if entities else None)\n",
+ " \n",
+ " for t in triplets:\n",
+ " combined_results[\"triplets\"].append({\n",
+ " \"subject\": t.subject,\n",
+ " \"predicate\": t.predicate,\n",
+ " \"object\": t.object\n",
+ " })\n",
+ " \n",
+ " print(f\" Found {len(triplets)} triplets\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Error extracting triplets: {e}\")\n",
+ " \n",
+ " # Step 4: Event Detection\n",
+ " print(f\" Detecting events...\")\n",
+ " try:\n",
+ " events = event_detector.detect_events(txt)\n",
+ " \n",
+ " for evt in events:\n",
+ " combined_results[\"events\"].append({\n",
+ " \"type\": evt.type,\n",
+ " \"text\": evt.text,\n",
+ " \"participants\": evt.participants\n",
+ " })\n",
+ " \n",
+ " print(f\" Found {len(events)} events\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Error detecting events: {e}\")\n",
+ " \n",
+ " print() # Blank line between chunks\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Error processing chunk: {e}\\n\")\n",
+ " continue\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Extraction Process Overview\n",
+ "\n",
+ "The extraction loop processes each chunk through four steps:\n",
+ "\n",
+ "1. **Named Entity Recognition**: Identifies entities in the text\n",
+ "2. **Relation Extraction**: Finds relationships between entities (requires entities from step 1)\n",
+ "3. **Triplet Extraction**: Extracts RDF-style triplets\n",
+ "4. **Event Detection**: Identifies temporal events and participants\n",
+ "\n",
+ "All extraction results are stored in the `combined_results` dictionary.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This cell is now part of the extraction loop in the previous cell\n",
+ "# The extraction process runs all four steps (NER, Relations, Triplets, Events) for each chunk\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Understanding the Extraction Results\n",
+ "\n",
+ "Each extraction method produces different types of structured data:\n",
+ "\n",
+ "- **Entities**: Individual concepts, people, places, products\n",
+ "- **Relationships**: Connections between entities (e.g., \"Retinol COMPLEMENTS Niacinamide\")\n",
+ "- **Triplets**: RDF-style facts (subject-predicate-object)\n",
+ "- **Events**: Temporal occurrences with participants\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This cell is now part of the extraction loop in cell 41\n",
+ "# All extraction steps run together for efficiency\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Error Handling\n",
+ "\n",
+ "Each extraction step includes try-except blocks to handle:\n",
+ "- API rate limits\n",
+ "- Network errors\n",
+ "- Parsing errors\n",
+ "- Invalid responses\n",
+ "\n",
+ "This ensures the pipeline continues even if individual extractions fail.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This cell is now part of the extraction loop in cell 41\n",
+ "# The complete extraction process is in the previous cell\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.7: Extraction Summary\n",
+ "\n",
+ "Review the extraction results and statistics.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Display extraction summary\n",
+ "print(\"=\" * 60)\n",
+ "print(\"Phase 3 Complete - Extraction Summary\")\n",
+ "print(\"=\" * 60)\n",
+ "print(f\"Entities extracted: {len(combined_results['entities'])}\")\n",
+ "print(f\"Relationships extracted: {len(combined_results['relationships'])}\")\n",
+ "print(f\"Triplets extracted: {len(combined_results['triplets'])}\")\n",
+ "print(f\"Events detected: {len(combined_results['events'])}\")\n",
+ "print(\"=\" * 60)\n",
+ "\n",
+ "# Show sample entities\n",
+ "if combined_results['entities']:\n",
+ " print(\"\\nSample entities:\")\n",
+ " for entity in combined_results['entities'][:5]:\n",
+ " print(f\" - {entity['name']} ({entity['type']})\")\n",
+ "\n",
+ "# Show sample relationships\n",
+ "if combined_results['relationships']:\n",
+ " print(\"\\nSample relationships:\")\n",
+ " for rel in combined_results['relationships'][:5]:\n",
+ " print(f\" - {rel['source']} --[{rel['type']}]--> {rel['target']}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 4: Knowledge Graph Construction & Refinement\n",
+ "\n",
+ "Build the knowledge graph from extracted entities and relationships, then refine it through entity resolution and analysis.\n",
+ "\n",
+ "### Graph Construction Process\n",
+ "\n",
+ "1. **Graph Building**: Create graph structure from entities and relationships\n",
+ "2. **Entity Resolution**: Deduplicate and merge similar entities\n",
+ "3. **Graph Analysis**: Analyze graph structure and properties\n",
+ "4. **Centrality Calculation**: Identify important entities\n",
+ "5. **Community Detection**: Find clusters of related entities\n",
+ "\n",
+ "### Why Entity Resolution?\n",
+ "\n",
+ "- **Deduplication**: Merge entities that refer to the same thing (e.g., \"Retinol\" and \"retinol\")\n",
+ "- **Consolidation**: Combine information from multiple sources\n",
+ "- **Quality Improvement**: Create a cleaner, more accurate graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import knowledge graph modules\n",
+ "from semantica.kg import (\n",
+ " GraphBuilder, \n",
+ " EntityResolver,\n",
+ " GraphAnalyzer,\n",
+ " CentralityCalculator,\n",
+ " CommunityDetector,\n",
+ " ConnectivityAnalyzer\n",
+ ")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.1: Build Initial Knowledge Graph\n",
+ "\n",
+ "Use GraphBuilder to create the initial graph structure from extracted entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize GraphBuilder with entity merging enabled\n",
+ "gb = GraphBuilder(merge_entities=True)\n",
+ "\n",
+ "# Build knowledge graph from extraction results\n",
+ "print(\"Building knowledge graph...\")\n",
+ "kg = gb.build(sources=[combined_results])\n",
+ "\n",
+ "print(f\"Initial graph statistics:\")\n",
+ "print(f\" - Entities: {len(kg.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(kg.get('relationships', []))}\")\n",
+ "print(f\" - Metadata: {kg.get('metadata', {})}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.2: Resolve Entities (Deduplication)\n",
+ "\n",
+ "Entity resolution merges duplicate entities using semantic similarity. This is crucial for:\n",
+ "- **Consistency**: Ensure each real-world entity appears only once\n",
+ "- **Information Aggregation**: Combine properties from multiple mentions\n",
+ "- **Quality**: Create a cleaner, more accurate graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize EntityResolver\n",
+ "# similarity_threshold: Minimum similarity (0.85 = 85%) to consider entities as duplicates\n",
+ "resolver = EntityResolver(similarity_threshold=0.85)\n",
+ "\n",
+ "print(\"Resolving entities (deduplication)...\")\n",
+ "print(f\" Method: Semantic similarity matching\")\n",
+ "print(f\" Threshold: 0.85 (85% similarity)\")\n",
+ "\n",
+ "# Resolve entities using semantic method\n",
+ "resolved_entities = resolver.resolve_entities(\n",
+ " kg.get('entities', []), \n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "# Create final graph with resolved entities\n",
+ "kg_final = {\n",
+ " **kg,\n",
+ " 'entities': resolved_entities\n",
+ "}\n",
+ "\n",
+ "print(f\"\\nEntity resolution complete:\")\n",
+ "print(f\" - Original entities: {len(kg.get('entities', []))}\")\n",
+ "print(f\" - Resolved entities: {len(kg_final['entities'])}\")\n",
+ "print(f\" - Entities merged: {len(kg.get('entities', [])) - len(kg_final['entities'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.3: Analyze Graph Structure\n",
+ "\n",
+ "Graph analysis provides insights into the graph's topology and connectivity.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize GraphAnalyzer\n",
+ "analyzer = GraphAnalyzer()\n",
+ "\n",
+ "print(\"Analyzing graph structure...\")\n",
+ "\n",
+ "# Perform comprehensive graph analysis\n",
+ "analysis = analyzer.analyze_graph(kg_final)\n",
+ "\n",
+ "print(f\"\\nGraph structure metrics:\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.4f}\")\n",
+ "print(f\" - Connected components: {analysis.get('connected_components', 0)}\")\n",
+ "print(f\" - Average degree: {analysis.get('average_degree', 0):.2f}\")\n",
+ "print(f\" - Total nodes: {analysis.get('num_nodes', 0)}\")\n",
+ "print(f\" - Total edges: {analysis.get('num_edges', 0)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.4: Calculate Centrality Measures\n",
+ "\n",
+ "Centrality measures identify the most important entities in the graph:\n",
+ "- **Degree Centrality**: Entities with many connections\n",
+ "- **Betweenness Centrality**: Entities that bridge different parts of the graph\n",
+ "- **Closeness Centrality**: Entities that are close to all other entities\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize CentralityCalculator\n",
+ "centrality_calc = CentralityCalculator()\n",
+ "\n",
+ "print(\"Calculating centrality measures...\")\n",
+ "\n",
+ "# Calculate degree centrality (simplest and most common)\n",
+ "degree_centrality = centrality_calc.calculate_degree_centrality(kg_final)\n",
+ "\n",
+ "if degree_centrality:\n",
+ " # Get top entities by degree centrality\n",
+ " top_entities = sorted(\n",
+ " degree_centrality.items(), \n",
+ " key=lambda x: x[1], \n",
+ " reverse=True\n",
+ " )[:5]\n",
+ " \n",
+ " print(f\"\\nTop 5 entities by degree centrality:\")\n",
+ " for rank, (entity_id, score) in enumerate(top_entities, 1):\n",
+ " print(f\" {rank}. {entity_id}: {score:.4f}\")\n",
+ "else:\n",
+ " print(\" No centrality data available\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.5: Detect Communities\n",
+ "\n",
+ "Community detection identifies clusters of closely connected entities, revealing:\n",
+ "- **Thematic Groups**: Entities that belong to the same topic\n",
+ "- **Subnetworks**: Dense regions within the graph\n",
+ "- **Domain Structure**: How knowledge is organized\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize CommunityDetector\n",
+ "community_detector = CommunityDetector()\n",
+ "\n",
+ "print(\"Detecting communities...\")\n",
+ "print(\" Method: Louvain algorithm (greedy modularity optimization)\")\n",
+ "\n",
+ "# Detect communities using Louvain algorithm\n",
+ "communities = community_detector.detect_communities(\n",
+ " kg_final, \n",
+ " method=\"louvain\"\n",
+ ")\n",
+ "\n",
+ "if communities:\n",
+ " print(f\"\\nCommunity detection results:\")\n",
+ " print(f\" - Total communities found: {len(communities)}\")\n",
+ " \n",
+ " # Show top 3 communities\n",
+ " sorted_communities = sorted(communities, key=len, reverse=True)\n",
+ " for i, community in enumerate(sorted_communities[:3], 1):\n",
+ " print(f\" - Community {i}: {len(community)} entities\")\n",
+ " # Show sample entities from this community\n",
+ " sample_entities = list(community)[:3]\n",
+ " print(f\" Sample entities: {', '.join(sample_entities)}\")\n",
+ "else:\n",
+ " print(\" No communities detected\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.6: Phase 4 Summary\n",
+ "\n",
+ "Review the final graph statistics and quality metrics.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"=\" * 60)\n",
+ "print(\"Phase 4 Complete - Knowledge Graph Summary\")\n",
+ "print(\"=\" * 60)\n",
+ "print(f\"Final graph contains:\")\n",
+ "print(f\" - Entities: {len(kg_final['entities'])}\")\n",
+ "print(f\" - Relationships: {len(kg_final.get('relationships', []))}\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.4f}\")\n",
+ "print(f\" - Connected components: {analysis.get('connected_components', 0)}\")\n",
+ "print(f\" - Communities: {len(communities) if communities else 0}\")\n",
+ "print(\"=\" * 60)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 5: Vector Store Population\n",
+ "\n",
+ "Generate embeddings for all document chunks and store them in the vector database for hybrid retrieval.\n",
+ "\n",
+ "### Why Vector Store?\n",
+ "\n",
+ "- **Semantic Search**: Find text chunks by meaning, not just keywords\n",
+ "- **Hybrid Retrieval**: Combine with graph traversal for comprehensive results\n",
+ "- **Fast Lookup**: Efficient similarity search using FAISS\n",
+ "\n",
+ "### Embedding Process\n",
+ "\n",
+ "1. Generate embeddings for all chunks using the configured embedding model\n",
+ "2. Store vectors with metadata linking back to original chunks\n",
+ "3. Enable fast similarity search for retrieval\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Prepare texts for embedding generation\n",
+ "print(\"Preparing texts for embedding...\")\n",
+ "texts = [str(c.text) for c in all_chunks]\n",
+ "\n",
+ "print(f\" - Total chunks to embed: {len(texts)}\")\n",
+ "print(f\" - Embedding model: all-MiniLM-L6-v2\")\n",
+ "print(f\" - Expected dimension: 384\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate embeddings using the configured embedding generator\n",
+ "print(\"Generating embeddings...\")\n",
+ "embeddings = core.embedding_generator.generate_embeddings(texts)\n",
+ "\n",
+ "print(f\"Embeddings generated successfully:\")\n",
+ "print(f\" - Total embeddings: {len(embeddings)}\")\n",
+ "print(f\" - Embedding dimension: {len(embeddings[0]) if embeddings else 0}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.2: Prepare Metadata\n",
+ "\n",
+ "Create metadata for each vector that links it back to the original chunk and provides context.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create metadata for each vector\n",
+ "metadata_list = []\n",
+ "\n",
+ "print(\"Preparing metadata...\")\n",
+ "for i, chunk in enumerate(all_chunks):\n",
+ " metadata_list.append({\n",
+ " \"text\": str(chunk.text),\n",
+ " \"chunk_id\": i,\n",
+ " \"source\": \"multi_source_ingestion\",\n",
+ " \"chunk_length\": len(str(chunk.text))\n",
+ " })\n",
+ "\n",
+ "print(f\" - Metadata entries created: {len(metadata_list)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.3: Store Vectors\n",
+ "\n",
+ "Store all embeddings in the FAISS vector store for fast similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Store vectors in FAISS vector store\n",
+ "print(\"Storing vectors in vector store...\")\n",
+ "vs.store_vectors(vectors=embeddings, metadata=metadata_list)\n",
+ "\n",
+ "print(f\"\\nPhase 5 Complete. Vector store populated successfully.\")\n",
+ "print(f\" - Vectors stored: {len(embeddings)}\")\n",
+ "print(f\" - Vector store backend: FAISS\")\n",
+ "print(f\" - Embedding dimension: {len(embeddings[0]) if embeddings else 0}\")\n",
+ "print(f\" - Ready for similarity search\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: GraphRAG Query System\n",
+ "\n",
+ "Implement the hybrid retrieval system that combines vector search with graph traversal.\n",
+ "\n",
+ "### What is Hybrid Retrieval?\n",
+ "\n",
+ "Hybrid retrieval combines two complementary approaches:\n",
+ "\n",
+ "1. **Vector Search**: Finds semantically similar text chunks\n",
+ "2. **Graph Traversal**: Follows entity relationships to find connected information\n",
+ "\n",
+ "### AgentContext Features\n",
+ "\n",
+ "- **Auto-detection**: Automatically chooses RAG vs GraphRAG based on available components\n",
+ "- **Graph Expansion**: Traverses relationships up to N hops (configurable)\n",
+ "- **Hybrid Scoring**: Combines vector and graph scores with configurable weights\n",
+ "- **Entity Linking**: Links query terms to entities in the knowledge graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import context and provider modules\n",
+ "from semantica.context import AgentContext, EntityLinker\n",
+ "from semantica.semantic_extract.providers import create_provider\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.1: Initialize AgentContext\n",
+ "\n",
+ "AgentContext is the main interface for GraphRAG. It orchestrates:\n",
+ "- Vector store queries\n",
+ "- Knowledge graph traversal\n",
+ "- Hybrid scoring and ranking\n",
+ "- Context aggregation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize AgentContext with hybrid retrieval enabled\n",
+ "print(\"Initializing AgentContext for GraphRAG...\")\n",
+ "\n",
+ "ctx = AgentContext(\n",
+ " vector_store=vs, # Vector store for semantic search\n",
+ " knowledge_graph=kg_final, # Knowledge graph for relationship traversal\n",
+ " use_graph_expansion=True, # Enable graph traversal\n",
+ " max_expansion_hops=2, # Traverse up to 2 hops from initial entities\n",
+ " hybrid_alpha=0.6 # 60% weight on graph, 40% on vector\n",
+ ")\n",
+ "\n",
+ "print(\"AgentContext initialized successfully.\")\n",
+ "print(f\" - Graph expansion: Enabled\")\n",
+ "print(f\" - Max expansion hops: 2\")\n",
+ "print(f\" - Hybrid alpha: 0.6 (60% graph, 40% vector)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.2: Initialize LLM Provider\n",
+ "\n",
+ "Set up the LLM provider for generating final answers from retrieved context.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize LLM provider for answer generation\n",
+ "llm_provider = create_provider(\"groq\", model=\"llama-3.1-70b-versatile\")\n",
+ "\n",
+ "print(\"LLM provider initialized.\")\n",
+ "print(f\" - Provider: Groq\")\n",
+ "print(f\" - Model: llama-3.1-70b-versatile\")\n",
+ "print(f\" - Ready for answer generation\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.3: Initialize Entity Linker\n",
+ "\n",
+ "EntityLinker resolves text mentions to entities in the knowledge graph, enabling better query understanding.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize EntityLinker\n",
+ "linker = EntityLinker(knowledge_graph=kg_final)\n",
+ "\n",
+ "print(\"EntityLinker initialized.\")\n",
+ "print(f\" - Knowledge graph: Linked\")\n",
+ "print(f\" - Ready for entity resolution in queries\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Interactive Query Example\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define the user query\n",
+ "user_query = \"What ingredients synergize with Retinol to prevent irritation?\"\n",
+ "\n",
+ "print(\"=\" * 70)\n",
+ "print(\"GRAPH RAG QUERY PROCESSING\")\n",
+ "print(\"=\" * 70)\n",
+ "print(f\"Query: {user_query}\\n\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.4: Retrieve Context Using Hybrid Search\n",
+ "\n",
+ "Use AgentContext to retrieve relevant context using both vector search and graph traversal.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Retrieve context using hybrid retrieval\n",
+ "print(\"Retrieving context using hybrid search...\")\n",
+ "print(\" - Vector search: Finding semantically similar chunks\")\n",
+ "print(\" - Graph traversal: Following entity relationships\")\n",
+ "print(\" - Max results: 5\")\n",
+ "print(\" - Graph expansion: Enabled (2 hops)\\n\")\n",
+ "\n",
+ "context_results = ctx.retrieve(\n",
+ " user_query, \n",
+ " max_results=5,\n",
+ " use_graph=True, # Enable graph-based retrieval\n",
+ " expand_graph=True, # Expand to related entities\n",
+ " include_entities=True, # Include related entities in results\n",
+ " include_relationships=True # Include relationships in results\n",
+ ")\n",
+ "\n",
+ "print(f\"Retrieved {len(context_results)} context results.\\n\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.5: Display Retrieved Context\n",
+ "\n",
+ "Review the retrieved context and multi-hop connections discovered by GraphRAG.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if context_results:\n",
+ " print(\"=\" * 70)\n",
+ " print(\"MULTI-HOP CONTEXT DISCOVERED\")\n",
+ " print(\"=\" * 70)\n",
+ " \n",
+ " for i, res in enumerate(context_results, 1):\n",
+ " print(f\"\\nResult {i}:\")\n",
+ " print(f\" Content: {res.get('content', '')[:150]}...\")\n",
+ " print(f\" Relevance Score: {res.get('score', 0):.4f}\")\n",
+ " \n",
+ " # Display related entities (multi-hop connections)\n",
+ " if res.get('related_entities'):\n",
+ " print(f\" Related Entities ({len(res['related_entities'])}):\")\n",
+ " for entity in res['related_entities'][:3]:\n",
+ " entity_name = entity.get('name', entity.get('content', 'Unknown'))\n",
+ " print(f\" - {entity_name}\")\n",
+ " \n",
+ " # Display related relationships\n",
+ " if res.get('related_relationships'):\n",
+ " print(f\" Related Relationships: {len(res['related_relationships'])}\")\n",
+ " \n",
+ " print(\"\\n\" + \"=\" * 70)\n",
+ "else:\n",
+ " print(\"No relevant context found.\")\n",
+ " print(\"This may indicate:\")\n",
+ " print(\" - The knowledge graph doesn't contain relevant information\")\n",
+ " print(\" - Try a different query\")\n",
+ " print(\" - Check if entities in the query exist in the graph\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.6: Generate Final Answer\n",
+ "\n",
+ "Use the LLM to synthesize a comprehensive answer from the retrieved context.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if context_results:\n",
+ " # Combine all retrieved context\n",
+ " context_text = \"\\n\\n\".join([r.get('content', '') for r in context_results])\n",
+ " \n",
+ " # Create prompt for LLM\n",
+ " prompt = f\"\"\"Based on the following context from a knowledge graph, answer the user query accurately and comprehensively.\n",
+ "\n",
+ "Context:\n",
+ "{context_text}\n",
+ "\n",
+ "Query: {user_query}\n",
+ "\n",
+ "Provide a detailed answer based on the context above:\"\"\"\n",
+ " \n",
+ " print(\"=\" * 70)\n",
+ " print(\"GENERATING FINAL ANSWER\")\n",
+ " print(\"=\" * 70)\n",
+ " print(\"Using LLM to synthesize answer from retrieved context...\\n\")\n",
+ " \n",
+ " try:\n",
+ " final_answer = llm_provider.generate(prompt, temperature=0.3)\n",
+ " print(final_answer)\n",
+ " except Exception as e:\n",
+ " print(f\"Warning: LLM generation failed: {e}\")\n",
+ " print(\"\\nHowever, we successfully retrieved relevant context using GraphRAG!\")\n",
+ " print(\"The context above can be used to answer the query manually.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization & Export\n",
+ "\n",
+ "Visualize the knowledge graph and export it in various formats for analysis and sharing.\n",
+ "\n",
+ "### Visualization Options\n",
+ "\n",
+ "- **Network Visualization**: Interactive graph showing entities and relationships\n",
+ "- **Layout Algorithms**: Spring, circular, hierarchical layouts\n",
+ "- **Export Formats**: JSON, GraphML, RDF, CSV\n",
+ "\n",
+ "### Export Formats\n",
+ "\n",
+ "- **JSON**: Human-readable, easy to process\n",
+ "- **GraphML**: Standard graph format, compatible with many tools\n",
+ "- **RDF**: Semantic web format, supports SPARQL queries\n",
+ "- **CSV**: Tabular format for analysis\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import visualization and export modules\n",
+ "from semantica.visualization import KGVisualizer\n",
+ "from semantica.export import GraphExporter\n",
+ "import matplotlib.pyplot as plt\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 7.1: Visualize Knowledge Graph\n",
+ "\n",
+ "Create a visual representation of the knowledge graph showing entities and their relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize KGVisualizer\n",
+ "viz = KGVisualizer()\n",
+ "\n",
+ "print(\"Visualizing knowledge graph...\")\n",
+ "print(\" - Layout: Spring (force-directed)\")\n",
+ "print(\" - Title: GraphRAG Knowledge Graph\")\n",
+ "\n",
+ "try:\n",
+ " viz.visualize_network(\n",
+ " kg_final, \n",
+ " layout=\"spring\", \n",
+ " title=\"GraphRAG Knowledge Graph\",\n",
+ " output=\"static\"\n",
+ " )\n",
+ " plt.show()\n",
+ " print(\"Graph visualization complete.\")\n",
+ "except Exception as e:\n",
+ " print(f\"Warning: Visualization error: {e}\")\n",
+ " print(\"Graph structure:\")\n",
+ " print(f\" - Entities: {len(kg_final.get('entities', []))}\")\n",
+ " print(f\" - Relationships: {len(kg_final.get('relationships', []))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 7.2: Export Knowledge Graph\n",
+ "\n",
+ "Export the graph in multiple formats for different use cases.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize GraphExporter\n",
+ "exporter = GraphExporter()\n",
+ "\n",
+ "print(\"\\nExporting knowledge graph...\")\n",
+ "\n",
+ "# Export to JSON (human-readable, easy to process)\n",
+ "try:\n",
+ " exporter.export_json(kg_final, \"graphrag_kg.json\")\n",
+ " print(\" Exported to JSON: graphrag_kg.json\")\n",
+ "except Exception as e:\n",
+ " print(f\" Warning: JSON export error: {e}\")\n",
+ "\n",
+ "# Export to GraphML (standard graph format)\n",
+ "try:\n",
+ " exporter.export_graphml(kg_final, \"graphrag_kg.graphml\")\n",
+ " print(\" Exported to GraphML: graphrag_kg.graphml\")\n",
+ "except Exception as e:\n",
+ " print(f\" Warning: GraphML export error: {e}\")\n",
+ "\n",
+ "print(\"\\nPhase 7 Complete. Graph visualized and exported.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Summary\n",
+ "\n",
+ "This notebook demonstrated a complete GraphRAG pipeline from data ingestion to question answering.\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "The complete pipeline consisted of 7 phases:\n",
+ "\n",
+ "1. **Phase 0**: Setup & Foundation Seeding\n",
+ " - Configured Semantica with all components\n",
+ " - Seeded knowledge graph with ground truth data\n",
+ "\n",
+ "2. **Phase 1**: Multi-Source Ingestion\n",
+ " - Ingested from RSS feeds, web pages, and local files\n",
+ " - Normalized all content for processing\n",
+ "\n",
+ "3. **Phase 2**: Document Processing & Chunking\n",
+ " - Split documents into semantic chunks\n",
+ " - Preserved entity boundaries\n",
+ "\n",
+ "4. **Phase 3**: Comprehensive Semantic Extraction\n",
+ " - Extracted entities using NER\n",
+ " - Extracted relationships between entities\n",
+ " - Extracted RDF triplets\n",
+ " - Detected events and their participants\n",
+ "\n",
+ "5. **Phase 4**: Knowledge Graph Construction & Refinement\n",
+ " - Built graph from extracted data\n",
+ " - Resolved duplicate entities\n",
+ " - Analyzed graph structure\n",
+ " - Calculated centrality measures\n",
+ " - Detected communities\n",
+ "\n",
+ "6. **Phase 5**: Vector Store Population\n",
+ " - Generated embeddings for all chunks\n",
+ " - Stored vectors with metadata\n",
+ "\n",
+ "7. **Phase 6**: GraphRAG Query System\n",
+ " - Implemented hybrid retrieval\n",
+ " - Demonstrated multi-hop reasoning\n",
+ " - Generated answers using LLM\n",
+ "\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ " - Visualized knowledge graph\n",
+ " - Exported in multiple formats\n",
+ "\n",
+ "### Key Takeaways\n",
+ "\n",
+ "- **GraphRAG** combines the best of vector search and graph traversal\n",
+ "- **Multi-hop reasoning** allows answering complex questions that require connecting multiple pieces of information\n",
+ "- **Hybrid retrieval** provides more contextually accurate results than vector-only search\n",
+ "- **Semantica framework** provides all the tools needed for production-ready GraphRAG systems\n",
+ "\n",
+ "### Next Steps\n",
+ "\n",
+ "- Experiment with different queries to explore the knowledge graph\n",
+ "- Add more data sources to expand the knowledge base\n",
+ "- Fine-tune extraction parameters for your specific domain\n",
+ "- Explore advanced features like temporal reasoning and conflict resolution\n",
+ "- Integrate with persistent graph stores (Neo4j, ArangoDB) for production use\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Phase 2: Document Processing & Chunking\n",
+ "\n",
+ "Split documents into semantic chunks for processing.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Phase 5: Vector Store Population\n",
+ "\n",
+ "Generate embeddings and populate the vector store for hybrid retrieval.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Phase 7: Visualization & Export\n",
+ "\n",
+ "Visualize the knowledge graph and export it in various formats.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n"
+ ]
}
- ],
- "source": [
- "from semantica.kg import GraphBuilder, EntityResolver\n",
- "\n",
- "# 1. Build & Vectorize\n",
- "gb = GraphBuilder(merge_entities=True)\n",
- "kg = gb.build(sources=[combined_results])\n",
- "\n",
- "# 2. Deduplicate\n",
- "resolver = EntityResolver(similarity_threshold=0.85)\n",
- "kg_final = {**kg, 'entities': resolver.resolve_entities(kg['entities'])}\n",
- "\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",
- "print(f\"\u2705 Phase 3 Complete. Graph contains {len(kg_final['entities'])} resolved entities.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "76cbe42a",
- "metadata": {},
- "source": [
- "## \ud83d\udcac Phase 4: Interactive GraphRAG Question Answering\n",
- "Using **AgentContext** for unified hybrid retrieval."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "id": "29d04181",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "\ud83d\udd0d Processing Multi-Hop Query: What ingredients synergize with Retinol to prevent irritation?\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\numpy\\linalg\\linalg.py:2582: RuntimeWarning:\n",
- "\n",
- "overflow encountered in multiply\n",
- "\n",
- "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:498: RuntimeWarning:\n",
- "\n",
- "invalid value encountered in divide\n",
- "\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n",
- "\u274c No relevant context found.\n"
- ]
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
}
- ],
- "source": [
- "from semantica.context import AgentContext\n",
- "\n",
- "# 1. Initialize AgentContext (Hybrid Retrieval)\n",
- "ctx = AgentContext(\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg_final,\n",
- " use_graph_expansion=True,\n",
- " max_expansion_hops=2\n",
- ")\n",
- "\n",
- "\n",
- "# 2. Interactive Query Loop\n",
- "user_query = \"What ingredients synergize with Retinol to prevent irritation?\"\n",
- "\n",
- "print(f\"\\n\ud83d\udd0d Processing Multi-Hop Query: {user_query}\")\n",
- "\n",
- "# Retrieve multi-hop context using AgentContext\n",
- "context_results = ctx.retrieve(user_query, max_results=2)\n",
- "\n",
- "if context_results:\n",
- " print(\"\\n--- \ud83e\udde0 MULTI-HOP CONTEXT DISCOVERED ---\")\n",
- " for res in context_results:\n",
- " print(f\"Recall: {res['content'][:120]}...\")\n",
- " if res.get('related_entities'):\n",
- " print(f\" \ud83d\udd17 Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\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",
- " \n",
- " try:\n",
- " print(\"\\n--- \u2728 FINAL GRAPHRAG ANSWER ---\")\n",
- " print(final_answer)\n",
- " except Exception as e:\n",
- " print(f\"\\n(LLM synthesis skipped: {e})\")\n",
- "else:\n",
- " print(\"\\n\u274c No relevant context found.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "5c478f11",
- "metadata": {},
- "source": [
- "## \ud83d\udcca Visualizing the Intelligence\n",
- "A final look at the relationships we've built."
- ]
},
- {
- "cell_type": "code",
- "execution_count": 14,
- "id": "851383de",
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "viz = KGVisualizer()\n",
- "viz.visualize_network(kg_final, layout=\"spring\", title=\"Skincare Ingredient Intelligence Graph\")\n",
- "plt.show()"
- ]
->>>>>>> Stashed changes
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.9"
- }
- },
- "nbformat": 4,
-<<<<<<< HEAD
-<<<<<<< Updated upstream
- "nbformat_minor": 2
-=======
- "nbformat_minor": 5
->>>>>>> Stashed changes
-}
-=======
- "nbformat_minor": 5
+ "nbformat": 4,
+ "nbformat_minor": 2
}
->>>>>>> main
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 8ac05255..8022b3e5 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
@@ -1,432 +1,1178 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "id": "ff1ebefe",
- "metadata": {},
- "source": [
- "# RAG vs. GraphRAG: Investigative Intelligence 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",
- "\n",
- "### The Challenge: Navigating Fragmentation\n",
-<<<<<<< HEAD
- "In intelligence work, facts are scattered across reports. Vector search often fails to bridge \"semantic gaps\"\u2014logical connections between entities that are not physically co-located in text. \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",
->>>>>>> main
- "\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."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "id": "f0f2029d",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Note: you may need to restart the kernel to use updated packages.\n"
- ]
- },
- {
- "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"
- ]
- }
- ],
- "source": [
- "# Environment Setup\n",
- "import os\n",
- "import sys\n",
- "\n",
- "# Ensure Groq API Key is set if using Groq\n",
- "os.environ['GROQ_API_KEY'] = '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'\n",
- "\n",
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "094fb9f7",
- "metadata": {},
- "source": [
- "## 1. Domain Acquisition: Real-World Intelligence gathering\n",
- "We ingest from high-signal feeds to build our knowledge base."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "id": "1da63d04",
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
-<<<<<<< HEAD
- "<div style='font-family: monospace;'><h4>\ud83e\udde0 Semantica - \ud83d\udcca 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>\u2705</td><td>Semantica is building</td><td>\ud83e\udde0 kg</td><td>GraphBuilder</td><td>-</td><td>21.67s</td></tr><tr><td>\ud83d\udd04</td><td>Semantica is building</td><td>\ud83e\udde0 kg</td><td>EntityResolver</td><td>-</td><td>11.02s</td></tr><tr><td>\u2705</td><td>Semantica is deduplicating</td><td>\ud83d\udd04 deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.03s</td></tr><tr><td>\u2705</td><td>Semantica is deduplicating</td><td>\ud83d\udd04 deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.01s</td></tr><tr><td>\u2705</td><td>Semantica is deduplicating</td><td>\ud83d\udd04 deduplication</td><td>EntityMerger</td><td>-</td><td>0.07s</td></tr><tr><td>\u2705</td><td>Semantica is deduplicating</td><td>\ud83d\udd04 deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.03s</td></tr><tr><td>\u2705</td><td>Semantica is resolving</td><td>\u26a0\ufe0f conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>\u2705</td><td>Semantica is processing</td><td>\ud83d\udd17 context</td><td>ContextRetriever</td><td>-</td><td>0.04s</td></tr><tr><td>\u2705</td><td>Semantica is processing</td><td>\ud83d\udd17 context</td><td>AgentMemory</td><td>-</td><td>0.02s</td></tr><tr><td>\u2705</td><td>Semantica is embedding</td><td>\ud83d\udcbe embeddings</td><td>TextEmbedder</td><td>-</td><td>0.00s</td></tr></table></div>"
-=======
- "<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>GraphBuilder</td><td>-</td><td>21.67s</td></tr><tr><td>πŸ”„</td><td>Semantica is building</td><td>🧠 kg</td><td>EntityResolver</td><td>-</td><td>11.02s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.03s</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.07s</td></tr><tr><td>βœ…</td><td>Semantica is deduplicating</td><td>πŸ”„ deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.03s</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 processing</td><td>πŸ”— context</td><td>ContextRetriever</td><td>-</td><td>0.04s</td></tr><tr><td>βœ…</td><td>Semantica is processing</td><td>πŸ”— context</td><td>AgentMemory</td><td>-</td><td>0.02s</td></tr><tr><td>βœ…</td><td>Semantica is embedding</td><td>πŸ’Ύ embeddings</td><td>TextEmbedder</td><td>-</td><td>0.00s</td></tr></table></div>"
->>>>>>> main
- ],
- "text/plain": [
- "<IPython.core.display.HTML object>"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Intelligence Knowledge Hub Populated with 27 reports.\n"
- ]
- }
- ],
- "source": [
- "from semantica.ingest import WebIngestor, FeedIngestor\n",
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "normalizer = TextNormalizer()\n",
- "all_content = []\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.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1404d812",
- "metadata": {},
- "source": [
- "## 2. Standard Vector RAG Pipeline\n",
- "Linear retrieval via semantic embedding overlap."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "id": "f5759b37",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n",
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Vector RAG ready with 10 encoded fragments.\n"
- ]
- }
- ],
- "source": [
- "from semantica.core import Semantica\n",
- "from semantica.split import EntityAwareChunker\n",
- "from semantica.vector_store import VectorStore\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",
- "\n",
- "# Using EntityAwareChunker for better intelligence-domain chunking\n",
- "splitter = EntityAwareChunker(chunk_size=600, chunk_overlap=50)\n",
- "chunks = []\n",
- "for doc in clean_docs[:10]:\n",
- " chunks.extend(splitter.chunk(doc))\n",
- "\n",
- "# Initialize Vector Store\n",
- "vs = VectorStore(backend=\"faiss\", dimension=1536) \n",
- "# Use the core embedding generator\n",
- "embeddings = v_core.embedding_generator.generate_embeddings([str(c.text) for c in chunks[:15]])\n",
- "vs.store_vectors(vectors=embeddings, metadata=[{\"content\": str(c.text)} for c in chunks[:15]])\n",
- "\n",
- "print(f\"Vector RAG ready with {len(chunks[:15])} encoded fragments.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "08ce3d9c",
- "metadata": {},
- "source": [
- "## 3. High-Fidelity GraphRAG Pipeline\n",
- "Synthesizing entities and relationships from fragmented reports."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "id": "6b1829f5",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "GraphRAG Synthesis Complete: 21 entities, 0 relationships.\n"
- ]
- }
- ],
- "source": [
- "from semantica.kg import GraphBuilder\n",
- "from semantica.context import AgentContext\n",
- "\n",
- "gb = GraphBuilder(merge_entities=True)\n",
- "# We process a subset for demonstration\n",
- "kg_data = gb.build(sources=[{\"text\": str(c.text)} for c in chunks[:10]])\n",
- "\n",
- "# Initialize AgentContext for GraphRAG\n",
- "# This combines Vector Store and Knowledge Graph for hybrid retrieval\n",
- "ctx = AgentContext(\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg_data,\n",
- " use_graph_expansion=True,\n",
- " max_expansion_hops=2\n",
- ")\n",
- "\n",
- "print(f\"GraphRAG Synthesis Complete: {len(kg_data.get('entities', []))} entities, {len(kg_data.get('relationships', []))} relationships.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3992e7d9",
- "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.\"**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "id": "6a9bf3e4",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "--- Standard Vector Recall ---\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\numpy\\linalg\\linalg.py:2582: RuntimeWarning: invalid value encountered in multiply\n",
- " s = (x.conj() * x).real\n",
- "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:498: RuntimeWarning: invalid value encountered in divide\n",
- " similarities = np.dot(vectors, query_vector) / (vector_norms * query_norm)\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Recall: No content... (Score: nan)\n",
- "Recall: No content... (Score: nan)\n",
- "Recall: No content... (Score: nan)\n",
- "\n",
- "--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\n",
- "\n",
- "(LLM synthesis skipped: 'InferenceEngine' object has no attribute 'generate')\n"
- ]
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# RAG vs. GraphRAG: Investigative Intelligence Comparison\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook provides a rigorous, side-by-side comparison of **Standard RAG (Vector-based)** and **GraphRAG (Graph-based)**, focusing on how GraphRAG creates a \"Chain of Evidence\" that Vector RAG cannot see.\n",
+ "\n",
+ "### The Challenge: Navigating Fragmentation\n",
+ "\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",
+ "\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.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Environment Setup\n",
+ "import os\n",
+ "\n",
+ "os.environ['GROQ_API_KEY'] = os.getenv('GROQ_API_KEY', 'your-groq-api-key-here')\n",
+ "\n",
+ "# Install Semantica and all required dependencies\n",
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Setup & Configuration\n",
+ "\n",
+ "Configure the environment and import necessary modules for both RAG approaches.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.1: Import Required Modules\n",
+ "\n",
+ "Import all necessary modules for data ingestion, processing, and both RAG approaches.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import core modules\n",
+ "import os\n",
+ "from semantica.core import Semantica\n",
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "# Import ingestion modules\n",
+ "from semantica.ingest import WebIngestor, FeedIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import EntityAwareChunker\n",
+ "\n",
+ "# Import knowledge graph modules\n",
+ "from semantica.kg import GraphBuilder, EntityResolver, GraphAnalyzer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",
+ "from semantica.context import AgentContext\n",
+ "from semantica.semantic_extract.providers import create_provider\n",
+ "\n",
+ "print(\"All modules imported successfully.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 0.2: Configure API Keys\n",
+ "\n",
+ "Set up API keys for LLM providers. In production, use environment variables.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Set up API keys\n",
+ "# Note: In production, use environment variables: export GROQ_API_KEY=\"your-key\"\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-groq-api-key-here\")\n",
+ "\n",
+ "print(\"API keys configured.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Section 1: Domain Acquisition - Real-World Intelligence Gathering\n",
+ "\n",
+ "Build a knowledge base from real-world intelligence sources to demonstrate the differences between Vector RAG and GraphRAG.\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "We'll ingest from multiple intelligence sources:\n",
+ "- **RSS Feeds**: News feeds from BBC, Al Jazeera, Reuters\n",
+ "- **Web Pages**: Wikipedia articles on intelligence analysis\n",
+ "- **Real-World Data**: No mock data - all sources are actual, live feeds\n",
+ "\n",
+ "### Why Multiple Sources?\n",
+ "\n",
+ "- **Diversity**: Different perspectives and reporting styles\n",
+ "- **Complexity**: Real-world data has noise and inconsistencies\n",
+ "- **Realistic**: Mirrors actual intelligence gathering scenarios\n",
+ "\n",
+ "We ingest from high-signal feeds to build our knowledge base.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import WebIngestor, FeedIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import EntityAwareChunker\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "all_content = []\n",
+ "\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\"\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",
+ " 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",
+ "web_urls = [\"https://en.wikipedia.org/wiki/Intelligence_analysis\"]\n",
+ "web_ingestor = WebIngestor()\n",
+ "for url in web_urls:\n",
+ " try:\n",
+ " content = web_ingestor.ingest_url(url)\n",
+ " if content and 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_docs = [normalizer.normalize(text) for text in all_content if len(text) > 100]\n",
+ "print(f\"Intelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.1: Ingest RSS Feeds\n",
+ "\n",
+ "RSS feeds provide structured, regularly updated content from news sources.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define RSS feed URLs\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\"\n",
+ "]\n",
+ "\n",
+ "print(\"Ingesting from RSS feeds...\")\n",
+ "for f in feeds:\n",
+ " try:\n",
+ " print(f\" Processing: {f}\")\n",
+ " data = feed_ingestor.ingest_feed(f)\n",
+ " items = data.items[:10] # Limit to 10 items per feed\n",
+ " \n",
+ " for item in items:\n",
+ " text = item.content or item.description or item.title\n",
+ " if text:\n",
+ " all_content.append(text)\n",
+ " \n",
+ " print(f\" Successfully ingested {len(items)} items\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Failed to ingest feed {f}: {e}\")\n",
+ "\n",
+ "print(f\"\\nTotal feed items ingested: {len([c for c in all_content if c])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.2: Ingest Web Pages\n",
+ "\n",
+ "Web ingestion extracts content from specific web pages, including Wikipedia articles.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define web URLs to ingest\n",
+ "web_urls = [\n",
+ " \"https://en.wikipedia.org/wiki/Intelligence_analysis\"\n",
+ "]\n",
+ "\n",
+ "print(\"Ingesting from web pages...\")\n",
+ "for url in web_urls:\n",
+ " try:\n",
+ " print(f\" Processing: {url}\")\n",
+ " content = web_ingestor.ingest_url(url)\n",
+ " if content and content.text:\n",
+ " all_content.append(content.text)\n",
+ " print(f\" Successfully ingested content ({len(content.text)} characters)\")\n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Failed to ingest URL {url}: {e}\")\n",
+ "\n",
+ "print(f\"\\nTotal web pages ingested: {len([c for c in all_content if c])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1.3: Normalize Content\n",
+ "\n",
+ "Text normalization cleans and standardizes all ingested content for consistent processing.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Normalize all ingested content\n",
+ "print(\"Normalizing content...\")\n",
+ "clean_docs = []\n",
+ "\n",
+ "for text in all_content:\n",
+ " if len(text) > 100: # Filter out very short content\n",
+ " normalized_text = normalizer.normalize(text)\n",
+ " clean_docs.append(normalized_text)\n",
+ "\n",
+ "print(f\"\\nIntelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")\n",
+ "print(f\" - Total documents: {len(clean_docs)}\")\n",
+ "print(f\" - Ready for processing\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Section 2: Standard Vector RAG Pipeline\n",
+ "\n",
+ "Implement a traditional vector-based RAG system using semantic similarity search only.\n",
+ "\n",
+ "### How Vector RAG Works\n",
+ "\n",
+ "1. **Chunk Documents**: Split text into smaller pieces\n",
+ "2. **Generate Embeddings**: Create vector representations\n",
+ "3. **Store Vectors**: Save in a vector database (FAISS)\n",
+ "4. **Query**: Find similar chunks using cosine similarity\n",
+ "\n",
+ "### Limitations of Vector RAG\n",
+ "\n",
+ "- **No Relationship Awareness**: Cannot follow entity connections\n",
+ "- **Semantic Gaps**: Misses connections between related but distant facts\n",
+ "- **No Multi-hop Reasoning**: Cannot chain facts across multiple documents\n",
+ "- **Context Fragmentation**: Each chunk is independent\n",
+ "\n",
+ "Linear retrieval via semantic embedding overlap.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.core import Semantica\n",
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "v_core = Semantica()\n",
+ "splitter = EntityAwareChunker(chunk_size=600, chunk_overlap=50)\n",
+ "chunks = []\n",
+ "for doc in clean_docs[:10]:\n",
+ " chunks.extend(splitter.chunk(doc))\n",
+ "\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "embeddings = v_core.embedding_generator.generate_embeddings([str(c.text) for c in chunks[:15]])\n",
+ "vs.store_vectors(vectors=embeddings, metadata=[{\"content\": str(c.text)} for c in chunks[:15]])\n",
+ "\n",
+ "print(f\"Vector RAG ready with {len(chunks[:15])} encoded fragments.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 2.1: Chunk Documents\n",
+ "\n",
+ "Split documents into semantic chunks for embedding generation.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize chunker\n",
+ "splitter = EntityAwareChunker(chunk_size=600, chunk_overlap=50)\n",
+ "\n",
+ "# Chunk documents\n",
+ "print(\"Chunking documents...\")\n",
+ "chunks = []\n",
+ "\n",
+ "for i, doc in enumerate(clean_docs[:10], 1):\n",
+ " doc_chunks = splitter.chunk(doc)\n",
+ " chunks.extend(doc_chunks)\n",
+ " print(f\" Document {i}: {len(doc_chunks)} chunks created\")\n",
+ "\n",
+ "print(f\"\\nTotal chunks created: {len(chunks)}\")\n",
+ "print(f\" - Chunk size: 600 characters\")\n",
+ "print(f\" - Overlap: 50 characters\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 2.2: Generate Embeddings\n",
+ "\n",
+ "Create vector embeddings for all chunks using the embedding model.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate embeddings for chunks (limit to 15 for demonstration)\n",
+ "print(\"Generating embeddings...\")\n",
+ "chunks_to_embed = chunks[:15]\n",
+ "texts_to_embed = [str(c.text) for c in chunks_to_embed]\n",
+ "\n",
+ "embeddings = v_core.embedding_generator.generate_embeddings(texts_to_embed)\n",
+ "\n",
+ "print(f\"Embeddings generated:\")\n",
+ "print(f\" - Total embeddings: {len(embeddings)}\")\n",
+ "print(f\" - Embedding dimension: {len(embeddings[0]) if embeddings else 0}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 2.3: Store Vectors\n",
+ "\n",
+ "Store embeddings in FAISS vector store for fast similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize vector store\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "\n",
+ "# Prepare metadata\n",
+ "metadata = [{\"content\": str(c.text)} for c in chunks_to_embed]\n",
+ "\n",
+ "# Store vectors\n",
+ "print(\"Storing vectors in vector store...\")\n",
+ "vs.store_vectors(vectors=embeddings, metadata=metadata)\n",
+ "\n",
+ "print(f\"\\nVector RAG ready with {len(chunks_to_embed)} encoded fragments.\")\n",
+ "print(f\" - Vector store backend: FAISS\")\n",
+ "print(f\" - Ready for semantic similarity search\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Section 3: High-Fidelity GraphRAG Pipeline\n",
+ "\n",
+ "Build a GraphRAG system that combines vector search with knowledge graph traversal.\n",
+ "\n",
+ "### How GraphRAG Works\n",
+ "\n",
+ "1. **Extract Entities & Relationships**: Build a knowledge graph\n",
+ "2. **Generate Embeddings**: Create vector representations (same as Vector RAG)\n",
+ "3. **Store Vectors**: Save in vector database\n",
+ "4. **Hybrid Query**: \n",
+ " - Find similar chunks (vector search)\n",
+ " - Follow entity relationships (graph traversal)\n",
+ " - Combine results with hybrid scoring\n",
+ "\n",
+ "### Advantages of GraphRAG\n",
+ "\n",
+ "- **Multi-hop Reasoning**: Follows relationships across entities\n",
+ "- **Semantic Gap Bridging**: Connects related but distant facts\n",
+ "- **Context Expansion**: Discovers related entities automatically\n",
+ "- **Relationship Awareness**: Understands how entities connect\n",
+ "\n",
+ "Synthesizing entities and relationships from fragmented reports.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize extractors\n",
+ "print(\"Initializing GraphRAG extractors...\")\n",
+ "ner = NERExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
+ "rel_ext = RelationExtractor(method=\"llm\", provider=\"groq\", model=\"llama-3.1-8b-instant\")\n",
+ "\n",
+ "print(\"Extractors initialized.\")\n",
+ "print(\" - NER Extractor: Ready\")\n",
+ "print(\" - Relation Extractor: Ready\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.1: Extract Entities and Relationships\n",
+ "\n",
+ "Extract structured knowledge from document chunks to build the knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Container for extraction results\n",
+ "kg_sources = {\"entities\": [], \"relationships\": []}\n",
+ "\n",
+ "print(\"Extracting entities and relationships from chunks...\")\n",
+ "print(f\"Processing {min(10, len(chunks))} chunks...\\n\")\n",
+ "\n",
+ "for i, chunk in enumerate(chunks[:10], 1):\n",
+ " txt = str(chunk.text)\n",
+ " try:\n",
+ " print(f\"Chunk {i}:\")\n",
+ " \n",
+ " # Extract entities\n",
+ " entities = ner.extract(txt)\n",
+ " for e in entities:\n",
+ " kg_sources[\"entities\"].append({\n",
+ " \"name\": e.text,\n",
+ " \"type\": e.label,\n",
+ " \"id\": e.text.lower().replace(' ', '_')\n",
+ " })\n",
+ " \n",
+ " print(f\" Found {len(entities)} entities\")\n",
+ " \n",
+ " # Extract relationships (requires entities)\n",
+ " if entities:\n",
+ " relations = rel_ext.extract(txt, entities=entities)\n",
+ " for r in relations:\n",
+ " kg_sources[\"relationships\"].append({\n",
+ " \"source\": r.subject,\n",
+ " \"target\": r.object,\n",
+ " \"type\": r.predicate\n",
+ " })\n",
+ " print(f\" Found {len(relations)} relationships\")\n",
+ " else:\n",
+ " print(f\" No relationships (no entities found)\")\n",
+ " \n",
+ " except Exception as e:\n",
+ " print(f\" Warning: Error extracting from chunk: {e}\")\n",
+ " continue\n",
+ "\n",
+ "print(f\"\\nExtraction complete:\")\n",
+ "print(f\" - Total entities extracted: {len(kg_sources['entities'])}\")\n",
+ "print(f\" - Total relationships extracted: {len(kg_sources['relationships'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.2: Build Knowledge Graph\n",
+ "\n",
+ "Construct the knowledge graph from extracted entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize GraphBuilder\n",
+ "gb = GraphBuilder(merge_entities=True)\n",
+ "\n",
+ "print(\"Building knowledge graph...\")\n",
+ "kg_data = gb.build(sources=[kg_sources])\n",
+ "\n",
+ "print(f\"Initial graph:\")\n",
+ "print(f\" - Entities: {len(kg_data.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.3: Resolve Entities\n",
+ "\n",
+ "Entity resolution merges duplicate entities to create a cleaner, more accurate graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize EntityResolver\n",
+ "resolver = EntityResolver(similarity_threshold=0.85)\n",
+ "\n",
+ "print(\"Resolving entities (deduplication)...\")\n",
+ "print(f\" Similarity threshold: 0.85 (85%)\")\n",
+ "\n",
+ "# Resolve entities\n",
+ "kg_data['entities'] = resolver.resolve_entities(kg_data.get('entities', []))\n",
+ "\n",
+ "print(f\"\\nEntity resolution complete:\")\n",
+ "print(f\" - Resolved entities: {len(kg_data['entities'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 3.4: Initialize AgentContext for Hybrid Retrieval\n",
+ "\n",
+ "AgentContext enables hybrid retrieval by combining vector search with graph traversal.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize AgentContext with hybrid retrieval\n",
+ "ctx = AgentContext(\n",
+ " vector_store=vs, # Same vector store as Vector RAG\n",
+ " knowledge_graph=kg_data, # Knowledge graph for traversal\n",
+ " use_graph_expansion=True, # Enable graph traversal\n",
+ " max_expansion_hops=2, # Traverse up to 2 hops\n",
+ " hybrid_alpha=0.6 # 60% weight on graph, 40% on vector\n",
+ ")\n",
+ "\n",
+ "print(\"AgentContext initialized with hybrid retrieval.\")\n",
+ "print(f\" - Graph expansion: Enabled\")\n",
+ "print(f\" - Max expansion hops: 2\")\n",
+ "print(f\" - Hybrid alpha: 0.6 (60% graph, 40% vector)\")\n",
+ "\n",
+ "print(f\"\\nGraphRAG Synthesis Complete:\")\n",
+ "print(f\" - Entities: {len(kg_data.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n",
+ "print(f\" - Ready for hybrid retrieval\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract.providers import create_provider\n",
+ "\n",
+ "user_query = \"Identify high-risk security escalations and their regional implications.\"\n",
+ "\n",
+ "print(\"=\" * 80)\n",
+ "print(\"QUERY:\", user_query)\n",
+ "print(\"=\" * 80)\n",
+ "\n",
+ "print(\"\\n--- Standard Vector Recall ---\")\n",
+ "v_res = vs.search(user_query, limit=3)\n",
+ "for i, r in enumerate(v_res, 1):\n",
+ " text = r.get('metadata', {}).get('content', 'No content')\n",
+ " score = r.get('score', 0)\n",
+ " print(f\"\\nResult {i} (Score: {score:.4f}):\")\n",
+ " print(f\" {text[:200]}...\")\n",
+ "\n",
+ "print(\"\\n--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\")\n",
+ "graph_res = ctx.retrieve(user_query, max_results=3, use_graph=True, expand_graph=True)\n",
+ "\n",
+ "for i, res in enumerate(graph_res, 1):\n",
+ " print(f\"\\nResult {i}:\")\n",
+ " print(f\" Content: {res.get('content', '')[:200]}...\")\n",
+ " print(f\" Score: {res.get('score', 0):.4f}\")\n",
+ " if res.get('related_entities'):\n",
+ " print(f\" Multi-hop connections: {len(res['related_entities'])} entities\")\n",
+ " for entity in res['related_entities'][:3]:\n",
+ " print(f\" - {entity.get('name', entity.get('content', 'Unknown'))}\")\n",
+ " if res.get('related_relationships'):\n",
+ " print(f\" Related relationships: {len(res['related_relationships'])}\")\n",
+ "\n",
+ "print(\"\\n--- FINAL INTELLIGENCE SYNTHESIS (GraphRAG) ---\")\n",
+ "context_text = \"\\n\\n\".join([r.get('content', '') for r in graph_res])\n",
+ "prompt = f\"\"\"Based on the following intelligence context, answer the query comprehensively.\n",
+ "\n",
+ "Context:\n",
+ "{context_text}\n",
+ "\n",
+ "Query: {user_query}\n",
+ "\n",
+ "Provide a detailed analysis:\"\"\"\n",
+ "\n",
+ "try:\n",
+ " llm_provider = create_provider(\"groq\", model=\"llama-3.1-70b-versatile\")\n",
+ " answer = llm_provider.generate(prompt, temperature=0.3)\n",
+ " print(answer)\n",
+ "except Exception as e:\n",
+ " print(f\"\\nWarning: LLM synthesis skipped: {e}\")\n",
+ " print(\"However, GraphRAG successfully retrieved multi-hop context!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.1: Vector RAG Retrieval\n",
+ "\n",
+ "Query the vector store using semantic similarity only.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"--- Standard Vector Recall ---\")\n",
+ "print(\"Method: Semantic similarity search only\")\n",
+ "print(\"Limitation: Cannot follow entity relationships\\n\")\n",
+ "\n",
+ "# Vector search\n",
+ "v_res = vs.search(user_query, limit=3)\n",
+ "\n",
+ "print(f\"Found {len(v_res)} results:\\n\")\n",
+ "for i, r in enumerate(v_res, 1):\n",
+ " text = r.get('metadata', {}).get('content', 'No content')\n",
+ " score = r.get('score', 0)\n",
+ " print(f\"Result {i} (Score: {score:.4f}):\")\n",
+ " print(f\" {text[:200]}...\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.2: GraphRAG Hybrid Retrieval\n",
+ "\n",
+ "Query using hybrid retrieval that combines vector search with graph traversal.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\")\n",
+ "print(\"Method: Vector search + Graph traversal\")\n",
+ "print(\"Advantage: Multi-hop reasoning across entity relationships\\n\")\n",
+ "\n",
+ "# GraphRAG hybrid retrieval\n",
+ "graph_res = ctx.retrieve(\n",
+ " user_query, \n",
+ " max_results=3, \n",
+ " use_graph=True, # Enable graph-based retrieval\n",
+ " expand_graph=True # Expand to related entities\n",
+ ")\n",
+ "\n",
+ "print(f\"Found {len(graph_res)} results:\\n\")\n",
+ "for i, res in enumerate(graph_res, 1):\n",
+ " print(f\"Result {i}:\")\n",
+ " print(f\" Content: {res.get('content', '')[:200]}...\")\n",
+ " print(f\" Score: {res.get('score', 0):.4f}\")\n",
+ " \n",
+ " # Show multi-hop connections (GraphRAG advantage)\n",
+ " if res.get('related_entities'):\n",
+ " print(f\" Multi-hop connections: {len(res['related_entities'])} entities\")\n",
+ " print(f\" Related entities:\")\n",
+ " for entity in res['related_entities'][:3]:\n",
+ " entity_name = entity.get('name', entity.get('content', 'Unknown'))\n",
+ " print(f\" - {entity_name}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 4.3: Generate Final Answer (GraphRAG)\n",
+ "\n",
+ "Use the LLM to synthesize a comprehensive answer from GraphRAG-retrieved context.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Combine retrieved context\n",
+ "context_text = \"\\n\\n\".join([r.get('content', '') for r in graph_res])\n",
+ "\n",
+ "# Create prompt for LLM\n",
+ "prompt = f\"\"\"Based on the following intelligence context, answer the query comprehensively.\n",
+ "\n",
+ "Context:\n",
+ "{context_text}\n",
+ "\n",
+ "Query: {user_query}\n",
+ "\n",
+ "Provide a detailed analysis:\"\"\"\n",
+ "\n",
+ "print(\"--- FINAL INTELLIGENCE SYNTHESIS (GraphRAG) ---\")\n",
+ "print(\"Using LLM to synthesize answer from multi-hop context...\\n\")\n",
+ "\n",
+ "try:\n",
+ " llm_provider = create_provider(\"groq\", model=\"llama-3.1-70b-versatile\")\n",
+ " answer = llm_provider.generate(prompt, temperature=0.3)\n",
+ " print(answer)\n",
+ "except Exception as e:\n",
+ " print(f\"Warning: LLM synthesis skipped: {e}\")\n",
+ " print(\"\\nHowever, GraphRAG successfully retrieved multi-hop context!\")\n",
+ " print(\"The retrieved context above demonstrates the multi-hop connections.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import advanced reasoning and conflict detection modules\n",
+ "from semantica.reasoning import GraphReasoner, SPARQLReasoner, ExplanationGenerator\n",
+ "from semantica.conflicts import ConflictDetector\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.1: Graph Reasoning\n",
+ "\n",
+ "GraphReasoner enables logical inference across the knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Graph Reasoning Capabilities\")\n",
+ "print(\"-\" * 50)\n",
+ "\n",
+ "# Initialize GraphReasoner\n",
+ "graph_reasoner = GraphReasoner(knowledge_graph=kg_data)\n",
+ "\n",
+ "print(\"GraphReasoner initialized for logical inference\")\n",
+ "print(\" - Can perform transitive reasoning\")\n",
+ "print(\" - Can infer implicit relationships\")\n",
+ "print(\" - Can validate logical consistency\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.2: SPARQL Query Capabilities\n",
+ "\n",
+ "SPARQLReasoner enables structured queries using SPARQL syntax (if available).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"\\nSPARQL Query Capabilities\")\n",
+ "print(\"-\" * 50)\n",
+ "\n",
+ "try:\n",
+ " sparql_reasoner = SPARQLReasoner()\n",
+ " print(\"SPARQLReasoner available for structured queries\")\n",
+ " print(\" - Can execute SPARQL queries\")\n",
+ " print(\" - Supports complex graph patterns\")\n",
+ "except Exception as e:\n",
+ " print(f\"Warning: SPARQLReasoner: {e}\")\n",
+ " print(\" SPARQLReasoner may require additional dependencies\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.3: Explanation Generation\n",
+ "\n",
+ "ExplanationGenerator provides explanations for why certain results were retrieved.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"\\nExplanation Generation\")\n",
+ "print(\"-\" * 50)\n",
+ "\n",
+ "# Initialize ExplanationGenerator\n",
+ "explanation_gen = ExplanationGenerator()\n",
+ "\n",
+ "print(\"ExplanationGenerator available for reasoning explanations\")\n",
+ "print(\" - Can explain retrieval paths\")\n",
+ "print(\" - Can show entity connections\")\n",
+ "print(\" - Can provide reasoning chains\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 5.4: Conflict Detection\n",
+ "\n",
+ "ConflictDetector identifies contradictory information in the knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"\\nConflict Detection\")\n",
+ "print(\"-\" * 50)\n",
+ "\n",
+ "# Initialize ConflictDetector\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "# Detect conflicts in the knowledge graph\n",
+ "conflicts = conflict_detector.detect_conflicts(kg_data)\n",
+ "\n",
+ "print(\"Conflict detection results:\")\n",
+ "print(f\" - Value conflicts: {len(conflicts.get('value_conflicts', []))}\")\n",
+ "print(f\" - Relationship conflicts: {len(conflicts.get('relationship_conflicts', []))}\")\n",
+ "\n",
+ "if conflicts.get('value_conflicts') or conflicts.get('relationship_conflicts'):\n",
+ " print(\" Conflicts detected - review for data quality\")\n",
+ "else:\n",
+ " print(\" No conflicts detected - graph is consistent\")\n",
+ "\n",
+ "print(\"\\nAdvanced GraphRAG features demonstrated.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 6. Visualizing the Intelligence Landscape\n",
+ "\n",
+ "Seeing the 'Bridges' between disconnected events.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "viz = KGVisualizer()\n",
+ "try:\n",
+ " viz.visualize_network(kg_data, output=\"static\", title=\"Intelligence Connectivity Map\")\n",
+ " plt.show()\n",
+ " print(\"Graph visualization complete.\")\n",
+ "except Exception as e:\n",
+ " print(f\"Warning: Visualization error: {e}\")\n",
+ " print(\"Graph structure:\")\n",
+ " print(f\" - Entities: {len(kg_data.get('entities', []))}\")\n",
+ " print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 6.1: Visualize Knowledge Graph\n",
+ "\n",
+ "Create a visual representation of the knowledge graph showing entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize KGVisualizer\n",
+ "viz = KGVisualizer()\n",
+ "\n",
+ "print(\"Visualizing knowledge graph...\")\n",
+ "print(\" - Layout: Spring (force-directed)\")\n",
+ "print(\" - Title: Intelligence Connectivity Map\")\n",
+ "\n",
+ "try:\n",
+ " viz.visualize_network(\n",
+ " kg_data,\n",
+ " output=\"static\",\n",
+ " title=\"Intelligence Connectivity Map\"\n",
+ " )\n",
+ " plt.show()\n",
+ " print(\"\\nGraph visualization complete.\")\n",
+ " print(f\" - Entities: {len(kg_data.get('entities', []))}\")\n",
+ " print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n",
+ "except Exception as e:\n",
+ " print(f\"Warning: Visualization error: {e}\")\n",
+ " print(\"Graph structure:\")\n",
+ " print(f\" - Entities: {len(kg_data.get('entities', []))}\")\n",
+ " print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 7. Performance & Quality Metrics Comparison\n",
+ "\n",
+ "Compare retrieval quality and demonstrate reasoning capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import pandas for comparison table\n",
+ "import pandas as pd\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 7.1: Create Comparison Table\n",
+ "\n",
+ "Create a side-by-side comparison of Vector RAG vs GraphRAG capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create comparison data\n",
+ "comparison_data = {\n",
+ " \"Metric\": [\n",
+ " \"Retrieval Method\",\n",
+ " \"Multi-hop Reasoning\",\n",
+ " \"Entity Connections\",\n",
+ " \"Relationship Traversal\",\n",
+ " \"Context Expansion\",\n",
+ " \"Semantic Gap Handling\"\n",
+ " ],\n",
+ " \"Vector RAG\": [\n",
+ " \"Semantic similarity only\",\n",
+ " \"No\",\n",
+ " \"No\",\n",
+ " \"No\",\n",
+ " \"Limited\",\n",
+ " \"Fails on disconnected facts\"\n",
+ " ],\n",
+ " \"GraphRAG\": [\n",
+ " \"Hybrid (Vector + Graph)\",\n",
+ " \"Yes (configurable hops)\",\n",
+ " \"Yes (graph traversal)\",\n",
+ " \"Yes (relationship following)\",\n",
+ " \"Yes (graph expansion)\",\n",
+ " \"Bridges semantic gaps\"\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Create DataFrame\n",
+ "df_comparison = pd.DataFrame(comparison_data)\n",
+ "\n",
+ "# Display comparison\n",
+ "print(\"RAG vs GraphRAG Comparison\")\n",
+ "print(\"=\" * 80)\n",
+ "print(df_comparison.to_string(index=False))\n",
+ "print(\"\\n\" + \"=\" * 80)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 7.2: Graph Statistics\n",
+ "\n",
+ "Analyze the knowledge graph structure and quality metrics.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize GraphAnalyzer\n",
+ "analyzer = GraphAnalyzer()\n",
+ "\n",
+ "print(\"\\nGraphRAG Knowledge Graph Statistics\")\n",
+ "print(\"-\" * 50)\n",
+ "\n",
+ "# Analyze graph structure\n",
+ "analysis = analyzer.analyze_graph(kg_data)\n",
+ "\n",
+ "print(f\"Entities: {len(kg_data.get('entities', []))}\")\n",
+ "print(f\"Relationships: {len(kg_data.get('relationships', []))}\")\n",
+ "print(f\"Graph Density: {analysis.get('density', 0):.4f}\")\n",
+ "print(f\"Connected Components: {analysis.get('connected_components', 0)}\")\n",
+ "print(f\"Average Degree: {analysis.get('average_degree', 0):.2f}\")\n",
+ "\n",
+ "print(\"\\n\" + \"=\" * 80)\n",
+ "print(\"Comparison complete. GraphRAG demonstrates superior multi-hop reasoning capabilities.\")\n",
+ "print(\"=\" * 80)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Summary\n",
+ "\n",
+ "This notebook demonstrated a comprehensive comparison between Standard Vector RAG and GraphRAG.\n",
+ "\n",
+ "### Key Findings\n",
+ "\n",
+ "1. **Vector RAG Limitations**:\n",
+ " - Cannot follow entity relationships\n",
+ " - Misses connections between related facts\n",
+ " - Limited context expansion\n",
+ " - Fails on semantic gaps\n",
+ "\n",
+ "2. **GraphRAG Advantages**:\n",
+ " - Multi-hop reasoning across entities\n",
+ " - Relationship-aware retrieval\n",
+ " - Automatic context expansion\n",
+ " - Bridges semantic gaps\n",
+ "\n",
+ "3. **When to Use Each**:\n",
+ " - **Vector RAG**: Simple queries, single-document retrieval, fast responses\n",
+ " - **GraphRAG**: Complex queries, multi-hop reasoning, relationship-aware search\n",
+ "\n",
+ "### Next Steps\n",
+ "\n",
+ "- Experiment with different queries to explore the differences\n",
+ "- Adjust hybrid_alpha to balance vector vs graph retrieval\n",
+ "- Explore advanced features like conflict detection and SPARQL queries\n",
+ "- Integrate with production systems for real-world applications\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Summary\n",
+ "\n",
+ "### Key Findings\n",
+ "\n",
+ "1. **Vector RAG Limitations**:\n",
+ " - Only finds semantically similar text chunks\n",
+ " - Cannot traverse relationships between entities\n",
+ " - Fails when facts are scattered across documents\n",
+ " - No multi-hop reasoning capability\n",
+ "\n",
+ "2. **GraphRAG Advantages**:\n",
+ " - Combines vector search with graph traversal\n",
+ " - Follows relationships to find connected information\n",
+ " - Bridges semantic gaps through graph structure\n",
+ " - Enables multi-hop reasoning (2+ hops)\n",
+ " - Provides \"Chain of Evidence\" for complex queries\n",
+ "\n",
+ "3. **When to Use Each**:\n",
+ " - **Vector RAG**: Simple fact retrieval, single-document queries, when relationships are not important\n",
+ " - **GraphRAG**: Complex multi-hop queries, relationship-heavy domains, when context expansion is needed\n",
+ "\n",
+ "### Conclusion\n",
+ "\n",
+ "GraphRAG creates a **\"Chain of Evidence\"** that Vector RAG cannot see by:\n",
+ "- Traversing the knowledge graph structure\n",
+ "- Following entity relationships across documents\n",
+ "- Expanding context through graph connections\n",
+ "- Enabling multi-hop reasoning for complex questions\n",
+ "\n",
+ "This makes GraphRAG particularly powerful for intelligence analysis, research, and any domain where understanding relationships is crucial.\n"
+ ]
}
- ],
- "source": [
-<<<<<<< HEAD
-=======
- "from semantica.reasoning import InferenceEngine\n",
->>>>>>> main
- "\n",
- "user_query = \"Identify high-risk security escalations and their regional implications.\"\n",
- "\n",
- "print(\"--- Standard Vector Recall ---\")\n",
- "# Direct search in vector store\n",
- "v_res = vs.search(user_query, limit=3)\n",
- "for r in v_res:\n",
- " text = r.get('metadata', {}).get('content', 'No content')\n",
- " print(f\"Recall: {text[:120]}... (Score: {r['score']:.4f})\")\n",
- "\n",
- "print(\"\\n--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\")\n",
- "# Use AgentContext for multi-hop retrieval\n",
- "graph_res = ctx.retrieve(user_query, max_results=3)\n",
- "\n",
- "for i, res in enumerate(graph_res):\n",
- " print(f\"Result {i+1}: {res['content'][:120]}...\")\n",
- " if res.get('related_entities'):\n",
-<<<<<<< HEAD
- " print(f\" \ud83d\udd17 Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\n",
- "\n",
-=======
- " print(f\" πŸ”— Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\n",
- "\n",
- "# Final Synthesis using InferenceEngine\n",
- "engine = InferenceEngine(provider=\"groq\", model=\"llama-3.1-70b-versatile\")\n",
->>>>>>> main
- "context_text = \"\\n\".join([r['content'] for r in graph_res])\n",
- "prompt = f\"Based on the following intelligence context, {user_query}\\n\\nContext:\\n{context_text}\"\n",
- "\n",
- "# Note: Requires GROQ_API_KEY\n",
- "try:\n",
-<<<<<<< HEAD
- " print(\"\\n--- \u2728 FINAL INTELLIGENCE SYNTHESIS ---\")\n",
-=======
- " answer = engine.generate(prompt)\n",
- " print(\"\\n--- ✨ FINAL INTELLIGENCE SYNTHESIS ---\")\n",
->>>>>>> main
- " print(answer)\n",
- "except Exception as e:\n",
- " print(f\"\\n(LLM synthesis skipped: {e})\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f6d37cc8",
- "metadata": {},
- "source": [
- "## 5. Visualizing the Intelligence Landscape\n",
- "Seeing the 'Bridges' between disconnected events."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "id": "854a8576",
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\umap\\__init__.py:9: ImportWarning: Tensorflow not installed; ParametricUMAP will be unavailable\n",
- " warn(\n"
- ]
- },
- {
- "ename": "NameError",
- "evalue": "name 'kg' is not defined",
- "output_type": "error",
- "traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
- "Cell \u001b[1;32mIn[6], line 6\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mmatplotlib\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mpyplot\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mplt\u001b[39;00m\n\u001b[0;32m 4\u001b[0m viz \u001b[38;5;241m=\u001b[39m KGVisualizer()\n\u001b[0;32m 5\u001b[0m viz\u001b[38;5;241m.\u001b[39mvisualize_network(\n\u001b[1;32m----> 6\u001b[0m \u001b[43mkg\u001b[49m,\n\u001b[0;32m 7\u001b[0m output\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mstatic\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 8\u001b[0m title\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIntelligence Connectivity Map\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 9\u001b[0m )\n\u001b[0;32m 10\u001b[0m plt\u001b[38;5;241m.\u001b[39mshow()\n",
- "\u001b[1;31mNameError\u001b[0m: name 'kg' is not defined"
- ]
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
}
- ],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "viz = KGVisualizer()\n",
- "viz.visualize_network(\n",
-<<<<<<< HEAD
- " kg_data,\n",
-=======
- " kg,\n",
->>>>>>> main
- " output=\"static\",\n",
- " title=\"Intelligence Connectivity Map\"\n",
- ")\n",
- "plt.show()"
- ]
-<<<<<<< HEAD
-=======
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "14f46e4d",
- "metadata": {},
- "outputs": [],
- "source": []
->>>>>>> main
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
},
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.9"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 5
-<<<<<<< HEAD
-}
-=======
+ "nbformat": 4,
+ "nbformat_minor": 2
}
->>>>>>> main