Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Refactor GraphRAG notebooks: remove empty cells, step numbers, reorganize imports, and make markdown concise
KaifAhmad19cc096dcd5e0
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 61474bce..d33e4ed6 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -1,1967 +1,1796 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](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"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "[](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": [+ "# Core imports will be added in cells where they're first used\n",+ "import os\n",+ "import json\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### 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": [+ "### Configure Semantica\n",+ "\n",+ "Create a configuration dictionary specifying:\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": [+ "### 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": [+ "from semantica.core import Semantica, ConfigManager\n",+ "from semantica.vector_store import VectorStore\n",+ "\n",+ "# 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": [+ "### 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": [+ "### 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": [+ "from semantica.seed import SeedDataManager\n",+ "\n",+ "# 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",+ "- **RSS/Atom Feeds**: Real-time updates from blogs and news sites\n",+ "- **Web Pages**: Structured content from websites\n",+ "- **Local Files**: Expert guides and documentation\n",+ "\n",+ "### Components\n",+ "\n",+ "- FeedIngestor, WebIngestor, FileIngestor for ingestion\n",+ "- TextNormalizer for content cleaning and normalization\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": [+ "### Initialize Ingestion Components\n",+ "\n",+ "Create instances of the ingestion classes and text normalizer.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",+ "from semantica.normalize import TextNormalizer\n",+ "\n",+ "# 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": [+ "### 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": [+ "### Ingest Web Pages\n",+ "\n",+ "Web ingestion extracts 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": [+ "### 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": [+ "### 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": [+ "### Initialize Chunker\n",+ "\n",+ "Configure the EntityAwareChunker with appropriate chunk size and overlap.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.split import EntityAwareChunker\n",+ "\n",+ "# 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": [+ "### 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: Semantic Extraction\n",+ "\n",+ "Extract structured knowledge from unstructured text using multiple extraction methods.\n",+ "\n",+ "### Extraction Methods\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",+ "Multiple methods provide comprehensive coverage and increased reliability.\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": [+ "### Initialize Extractors\n",+ "\n",+ "Create instances of all extraction classes with appropriate configurations.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",+ "\n",+ "# 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": [+ "### 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": [+ "### 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": [+ "### 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 from entities and relationships\n",+ "2. Entity resolution to deduplicate and merge similar entities\n",+ "3. Graph analysis of structure and properties\n",+ "4. Centrality calculation to identify important entities\n",+ "5. Community detection to find clusters of related entities\n",+ "\n",+ "Entity resolution merges duplicate entities (e.g., \"Retinol\" and \"retinol\") to improve graph quality.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Knowledge graph imports will be added in cells where they're first used\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### 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": [+ "from semantica.kg import GraphBuilder\n",+ "\n",+ "# 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": [+ "### 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",+ "- **Accuracy**: Improve graph quality by removing duplicates\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": [+ "from semantica.kg import EntityResolver\n",+ "\n",+ "# 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": [+ "### 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": [+ "from semantica.kg import GraphAnalyzer\n",+ "\n",+ "# 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": [+ "### 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": [+ "from semantica.kg import CentralityCalculator\n",+ "\n",+ "# 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": [+ "### 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 clusters 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": [+ "### 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": "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": [+ "### 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": [+ "### 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 hybrid retrieval that combines vector search with graph traversal.\n",+ "\n",+ "### Hybrid Retrieval\n",+ "\n",+ "- **Vector Search**: Finds semantically similar text chunks\n",+ "- **Graph Traversal**: Follows entity relationships to find connected information\n",+ "\n",+ "### AgentContext Features\n",+ "\n",+ "- Auto-detection of RAG vs GraphRAG based on available components\n",+ "- Graph expansion with configurable hop limits\n",+ "- Hybrid scoring combining vector and graph scores\n",+ "- Entity linking to connect query terms to graph entities\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": [+ "### 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": [+ "from semantica.context import AgentContext\n",+ "\n",+ "# 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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### 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\n",+ "\n",+ "- Interactive network visualization with multiple layout algorithms (spring, circular, hierarchical)\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": [+ "# Visualization and export imports will be added in cells where they're used\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### 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": [+ "from semantica.visualization import KGVisualizer\n",+ "import matplotlib.pyplot as plt\n",+ "\n",+ "# 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": [+ "### 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": [+ "from semantica.export import GraphExporter\n",+ "\n",+ "# 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": [+ "## Phase 2: Document Processing & Chunking\n",+ "\n",+ "Split documents into semantic chunks for processing.\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": "markdown",+ "metadata": {},+ "source": [+ "## Phase 7: Visualization & Export\n",+ "\n",+ "Visualize the knowledge graph and export it in various formats.\n"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2}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.ipynbindex 8022b3e5..36ed2d6f 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,1178 +1,1151 @@{- "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"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }+ "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"+ ]},- "nbformat": 4,- "nbformat_minor": 2+ {+ "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": [+ "### Import Required Modules\n",+ "\n",+ "Import modules for data ingestion, processing, and RAG approaches.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Core imports will be added in cells where they're first used\n",+ "import os\n",+ "print(\"Environment ready. Imports will be added as needed in subsequent cells.\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### 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\n",+ "\n",+ "Build a knowledge base from real-world intelligence sources to demonstrate Vector RAG vs GraphRAG differences.\n",+ "\n",+ "### Data Sources\n",+ "\n",+ "- **RSS Feeds**: BBC, Al Jazeera, Reuters\n",+ "- **Web Pages**: Wikipedia articles on intelligence analysis\n",+ "- **Real-World Data**: Live feeds with diverse perspectives and realistic complexity\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": [+ "### 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": [+ "### 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": [+ "### 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",+ "Traditional vector-based RAG using semantic similarity search only.\n",+ "\n",+ "### How Vector RAG Works\n",+ "\n",+ "1. Chunk documents\n",+ "2. Generate embeddings\n",+ "3. Store vectors in FAISS\n",+ "4. Query using cosine similarity\n",+ "\n",+ "### Limitations\n",+ "\n",+ "- No relationship awareness\n",+ "- Misses connections between distant facts\n",+ "- No multi-hop reasoning\n",+ "- Context fragmentation\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.core import Semantica\n",+ "from semantica.vector_store import VectorStore\n",+ "from semantica.split import EntityAwareChunker\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": [+ "### 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": [+ "### 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": [+ "### Store Vectors\n",+ "\n",+ "Store embeddings in FAISS vector store for fast similarity search.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.vector_store import VectorStore\n",+ "\n",+ "# 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: GraphRAG Pipeline\n",+ "\n",+ "GraphRAG combines vector search with knowledge graph traversal.\n",+ "\n",+ "### How GraphRAG Works\n",+ "\n",+ "1. Extract entities and relationships to build knowledge graph\n",+ "2. Generate embeddings (same as Vector RAG)\n",+ "3. Store vectors in database\n",+ "4. Hybrid query: vector search + graph traversal with hybrid scoring\n",+ "\n",+ "### Advantages\n",+ "\n",+ "- Multi-hop reasoning across entities\n",+ "- Bridges semantic gaps between distant facts\n",+ "- Automatic context expansion\n",+ "- Relationship awareness\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",+ "\n",+ "# 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": [+ "### 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": [+ "### Build Knowledge Graph\n",+ "\n",+ "Construct the knowledge graph from extracted entities and relationships.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphBuilder\n",+ "\n",+ "# 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": [+ "### Resolve Entities\n",+ "\n",+ "Entity resolution merges duplicate entities to create a cleaner, more consistent graph.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import EntityResolver\n",+ "\n",+ "# 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": [+ "### 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": [+ "from semantica.context import AgentContext\n",+ "\n",+ "# 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": "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": [+ "### 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": [+ "### 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": [+ "### Generate Final Answer (GraphRAG)\n",+ "\n",+ "Use the LLM to synthesize a comprehensive answer from 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": "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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### 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": [+ "### Graph Statistics\n",+ "\n",+ "Analyze the knowledge graph structure and quality metrics.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphAnalyzer\n",+ "\n",+ "# 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"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2}