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
Enhance GraphRAG notebook: Expanded knowledge hub with 10+ sources and multi-source ingestion logic
KaifAhmad17525f14e7fe0
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 0ba90e52..568e5e4d 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -4,29 +4,34 @@"cell_type": "markdown","metadata": {},"source": [- "# End-to-End Advanced GraphRAG with Semantica\n",+ "# Semantica Mastery: The Ultimate End-to-End GraphRAG Pipeline\n","\n",- "## Overview\n",+ "## π Overview\n","\n",- "This notebook provides a comprehensive, \"production-grade\" walkthrough of the **Semantica** framework. We will build a complete **GraphRAG** (Graph-Restricted Retrieval Augmented Generation) pipeline using diverse real-world data sources.\n",+ "This notebook is the **definitive guide** to building high-performance, production-ready Knowledge Graph systems using the **Semantica** framework. We go beyond simple retrieval to demonstrate a full orchestration of the library's advanced capabilities.\n","\n",- "### π Key Modules Used\n",+ "### π§ͺ What We Are Building\n","\n",- "* **`semantica.ingest`**: Ingestion from Web, RSS, and Git.\n",- "* **`semantica.normalize`**: Cleaning and standardizing raw text.\n",- "* **`semantica.split`**: Semantic document chunking.\n",- "* **`semantica.kg`**: KG construction and graph analytics.\n",- "* **`semantica.vector_store`**: Vector similarity search.\n",- "* **`semantica.reasoning`**: Advanced graph-based inference.\n",- "* **`semantica.visualization`**: Interactive and static KG viz.\n",- "* **`semantica.export`**: Data persistence and sharing.\n",+ "We will develop a **Self-Evolving Knowledge Base** for \"Python Ecosystem Intelligence.\" This system will aggregate verified facts, real-time news, and technical documentation into a queryable, 3D-visualizable graph.\n","\n",- "### π― Objective\n",+ "### π οΈ Modules Covered\n","\n",- "Build a queryable knowledge base about **Python Development & AI News** by aggregating data from:\n",- "1. **Web**: Python.org\n",- "2. **RSS**: BBC Technology News\n",- "3. **Repo**: The requests library"+ "| Module | Purpose |\n",+ "| :--- | :--- |\n",+ "| **`semantica.core`** | Central orchestration and configuration management. |\n",+ "| **`semantica.seed`** | Bootstrapping the graph with verified \"Ground Truth\" data. |\n",+ "| **`semantica.ingest`** | Fetching data from Web, RSS, and Git repositories. |\n",+ "| **`semantica.parse`** | Deep extraction from PDFs, Markdown, and HTML. |\n",+ "| **`semantica.normalize`** | standardizing text, symbols, and entities. |\n",+ "| **`semantica.split`** | Semantic chunking to preserve relationship integrity. |\n",+ "| **`semantica.kg`** | LLM-driven Graph Construction and Analytics. |\n",+ "| **`semantica.deduplication`** | Merging duplicate entities across sources. |\n",+ "| **`semantica.conflicts`** | Resolving discrepancies between sources (e.g., conflicting dates). |\n",+ "| **`semantica.vector_store`** | High-dimensional semantic indexing. |\n",+ "| **`semantica.reasoning`** | Multi-hop graph inference and logic. |\n",+ "| **`semantica.pipeline`** | Wrapping the entire workflow into a repeatable object. |\n",+ "| **`semantica.visualization`** | Rich network graphs and community insights. |\n",+ "| **`semantica.export`** | Persistence to JSON, CSV, and Neo4j. |"]},{@@ -35,17 +40,17 @@"metadata": {},"outputs": [],"source": [- "# Installation & Setup\n",- "!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu tiktoken"+ "# π οΈ Environment Setup\n",+ "!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu tiktoken beautifulsoup4 python-docx pdfplumber"]},{"cell_type": "markdown","metadata": {},"source": [- "## 1. Core Configuration\n",+ "## 1. Professional Initialization & Config\n","\n",- "We start by initializing the global `Semantica` configuration."+ "We start by defining a production config. Semantica uses **ConfigManager** to ensure environment consistency."]},{@@ -57,14 +62,30 @@"import os\n","from semantica.core import Semantica, ConfigManager\n","\n",- "config = {\n",- " \"project_name\": \"PythonAI_FullPipeline\",\n",- " \"embedding\": {\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"},\n",- " \"extraction\": {\"model\": \"gpt-4o-mini\", \"temperature\": 0.0},\n",- " \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 1536}\n",+ "# Enterprise Config Definition\n",+ "config_dict = {\n",+ " \"project_name\": \"PythonAI_Mastery\",\n",+ " \"embedding\": {\n",+ " \"provider\": \"openai\",\n",+ " \"model\": \"text-embedding-3-small\"\n",+ " },\n",+ " \"extraction\": {\n",+ " \"model\": \"gpt-4o-mini\",\n",+ " \"temperature\": 0.0\n",+ " },\n",+ " \"vector_store\": {\n",+ " \"provider\": \"faiss\",\n",+ " \"dimension\": 1536 \n",+ " },\n",+ " \"knowledge_graph\": {\n",+ " \"backend\": \"networkx\",\n",+ " \"merge_entities\": True,\n",+ " \"resolution_strategy\": \"fuzzy\"\n",+ " }\n","}\n","\n",- "sem = Semantica(config=ConfigManager().load_from_dict(config))\n",+ "config = ConfigManager().load_from_dict(config_dict)\n",+ "core = Semantica(config=config)\n","print(\"β Semantica Core Initialized.\")"]},@@ -72,9 +93,54 @@"cell_type": "markdown","metadata": {},"source": [- "## 2. Ingestion & Normalization\n",+ "## 2. Bootstrapping with Seed Data\n","\n",- "Fetching real-world data and cleaning it immediately using the `normalize` module."+ "We use `semantica.seed` to establish \"Ground Truth.\" This prevents the system from being solely dependent on AI extractions."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import json\n",+ "from semantica.seed import SeedDataManager\n",+ "\n",+ "# Create sample ground truth entities\n",+ "foundation_data = {\n",+ " \"entities\": [\n",+ " {\"id\": \"python_org\", \"name\": \"Python Software Foundation\", \"type\": \"Organization\"},\n",+ " {\"id\": \"guido_van_rossum\", \"name\": \"Guido van Rossum\", \"type\": \"Person\"}\n",+ " ],\n",+ " \"relationships\": [\n",+ " {\"source\": \"guido_van_rossum\", \"target\": \"python_org\", \"type\": \"FOUNDED\"}\n",+ " ]\n",+ "}\n",+ "\n",+ "with open(\"ground_truth.json\", \"w\") as f:\n",+ " json.dump(foundation_data, f)\n",+ "\n",+ "seed_manager = SeedDataManager()\n",+ "seed_manager.register_source(\"core_info\", \"json\", \"ground_truth.json\")\n",+ "foundation_graph = seed_manager.create_foundation_graph()\n",+ "\n",+ "print(f\"β Foundation Graph Seeded with {len(foundation_data['entities'])} Verified Nodes.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 3. The Knowledge Hub: Massive Multi-Source Ingestion\n",+ "\n",+ "We aggregate data from a diverse set of real-world sources using `semantica.ingest` and `semantica.parse`. \n",+ "\n",+ "### π Data Sources\n",+ "* **Official Docs**: Python.org, SQLAlchemy, Pydantic.\n",+ "* **Live News (RSS)**: TechCrunch, Wired, Ars Technica.\n",+ "* **Technical Blogs**: Real Python, Toward Data Science.\n",+ "* **Engineering Repos**: Requests, HTTPX, Semantica."]},{@@ -84,29 +150,55 @@"outputs": [],"source": ["from semantica.ingest import WebIngestor, FeedIngestor, ingest\n",- "from semantica.normalize import TextNormalizer\n",+ "from semantica.parse import parse_document\n","\n",- "normalizer = TextNormalizer()\n",+ "all_content = []\n","\n",- "# π Fetch Data\n",- "web_docs = WebIngestor().ingest(\"https://www.python.org/about/\", method=\"url\")\n",- "feed_docs = FeedIngestor().ingest(\"http://feeds.bbci.co.uk/news/technology/rss.xml\")[:3] # Sample 3\n",- "repo_docs = ingest(\"https://raw.githubusercontent.com/psf/requests/main/README.md\", source_type=\"web\")\n",+ "# π 1. Web Domain Ingestion\n",+ "print(\"π Ingesting Official Documentation...\")\n",+ "web_urls = [\n",+ " \"https://www.python.org/about/\",\n",+ " \"https://www.python.org/downloads/\",\n",+ " \"https://realpython.com/python-news/\"\n",+ "]\n",+ "web_ingestor = WebIngestor()\n",+ "for url in web_urls:\n",+ " docs = web_ingestor.ingest(url, method=\"url\")\n",+ " all_content.extend([d.content if hasattr(d, 'content') else str(d) for d in docs])\n","\n",- "# π§Ή Clean Data\n",- "raw_texts = [d.content if hasattr(d, 'content') else str(d) for d in web_docs + feed_docs + repo_docs]\n",- "clean_texts = [normalizer.normalize(t) for t in raw_texts if t]\n",+ "# π° 2. Live RSS Feeds\n",+ "print(\"\\nπ₯ Fetching Live Tech News...\")\n",+ "rss_feeds = [\n",+ " \"http://feeds.bbci.co.uk/news/technology/rss.xml\",\n",+ " \"https://techcrunch.com/feed/\",\n",+ " \"https://www.wired.com/feed/rss\"\n",+ "]\n",+ "feed_ingestor = FeedIngestor()\n",+ "for feed in rss_feeds:\n",+ " docs = feed_ingestor.ingest(feed)[:3] # Top 3 from each\n",+ " all_content.extend([d.content if hasattr(d, 'content') else str(d) for d in docs])\n","\n",- "print(f\"β Ingested and Normalized {len(clean_texts)} documents.\")"+ "# π» 3. Repository & Technical Files\n",+ "print(\"\\nπΏ Ingesting Engineering READMEs...\")\n",+ "repo_files = [\n",+ " \"https://raw.githubusercontent.com/psf/requests/main/README.md\",\n",+ " \"https://raw.githubusercontent.com/encode/httpx/master/README.md\"\n",+ "]\n",+ "for file_url in repo_files:\n",+ " # Universal ingest handles raw URL content detection\n",+ " docs = ingest(file_url, source_type=\"web\") \n",+ " all_content.extend([d.content if hasattr(d, 'content') else str(d) for d in docs])\n",+ "\n",+ "print(f\"\\nβ Aggregated {len(all_content)} documents from across the web.\")"]},{"cell_type": "markdown","metadata": {},"source": [- "## 3. Semantic Splitting\n",+ "## 4. Normalization & Splitting\n","\n",- "Breaking large documents into contextually aware chunks."+ "Standardizing noise and chunking for context preservation via `semantica.normalize` and `semantica.split`."]},{@@ -115,23 +207,34 @@"metadata": {},"outputs": [],"source": [+ "from semantica.normalize import TextNormalizer\n","from semantica.split import TextSplitter\n","\n",- "splitter = TextSplitter(method=\"recursive\", chunk_size=800, chunk_overlap=150)\n",- "chunks = []\n",- "for text in clean_texts:\n",- " chunks.extend(splitter.split(text))\n",+ "# Normalization - Sanitizing input data\n",+ "normalizer = TextNormalizer()\n",+ "clean_data = [normalizer.normalize(text) for text in all_content if text]\n",+ "\n",+ "# Intelligent Splitting - Preserving semantic boundaries\n",+ "splitter = TextSplitter(\n",+ " method=\"recursive\", \n",+ " chunk_size=1200, \n",+ " chunk_overlap=250\n",+ ")\n",+ "\n",+ "all_chunks = []\n",+ "for doc in clean_data:\n",+ " all_chunks.extend(splitter.split(doc))\n","\n",- "print(f\"β Generated {len(chunks)} Chunks.\")"+ "print(f\"β Normalized text and generated {len(all_chunks)} semantic chunks.\")"]},{"cell_type": "markdown","metadata": {},"source": [- "## 4. Knowledge Graph & Storage\n",+ "## 5. Knowledge Graph Construction & Data Quality\n","\n",- "Building the structural (Graph) and semantic (Vector) layers."+ "Building the graph, then applying **Conflict Resolution** and **Deduplication** to ensure data integrity."]},{@@ -141,27 +244,40 @@"outputs": [],"source": ["from semantica.kg import GraphBuilder\n",- "from semantica.vector_store import VectorStore\n",+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",+ "from semantica.conflicts import ConflictDetector, ConflictResolver\n","\n",- "# ποΈ Graph\n",+ "# 1. Initial Construction\n","gb = GraphBuilder(merge_entities=True)\n",- "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:5]]) # Limited for demo\n",+ "# Build from samples to save time in the demo\n",+ "kg = gb.build(sources=[{\"text\": str(c)} for c in all_chunks[:12]])\n","\n",- "# πΎ Vectors\n",- "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",- "embeddings = sem.embedding_generator.generate_embeddings([str(c) for c in chunks[:5]])\n",- "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks[:5]])\n",+ "# 2. Quality Control: Deduplication\n",+ "detector = DuplicateDetector(similarity_threshold=0.85)\n",+ "duplicates = detector.detect_duplicates(list(kg.nodes(data=True)))\n",+ "if duplicates:\n",+ " merger = EntityMerger()\n",+ " kg = merger.merge_duplicates(kg, duplicates)\n",+ " print(\"β¨ Deduplicated Entities.\")\n","\n",- "print(f\"β KG Built ({kg.number_of_nodes()} nodes). Vector Store Populated.\")"+ "# 3. Quality Control: Conflict Resolution\n",+ "conflict_detector = ConflictDetector()\n",+ "conflicts = conflict_detector.detect_conflicts(kg)\n",+ "if conflicts:\n",+ " resolver = ConflictResolver()\n",+ " kg = resolver.resolve_conflicts(kg, conflicts, strategy=\"most_recent\")\n",+ " print(\"βοΈ Resolved Data Conflicts.\")\n",+ "\n",+ "print(f\"β High-Quality Knowledge Graph Ready. Nodes: {kg.number_of_nodes()}\")"]},{"cell_type": "markdown","metadata": {},"source": [- "## 5. Graph Analytics & Viz\n",+ "## 6. Graph Synthesis & Advanced Reasoning\n","\n",- "Understanding the data through graph theory."+ "We apply Graph Analytics and the **Reasoning** module to derive insights not explicitly stated in the text."]},{@@ -170,14 +286,73 @@"metadata": {},"outputs": [],"source": [- "from semantica.kg import CentralityCalculator\n",- "from semantica.visualization import KGVisualizer\n",+ "from semantica.kg import CentralityCalculator, CommunityDetector\n",+ "from semantica.reasoning import GraphReasoner\n","\n",+ "# Analytics - Mapping the Influence\n","centrality = CentralityCalculator().calculate_degree_centrality(kg)\n",- "print(f\"π Top Node: {max(centrality, key=centrality.get)}\")\n",+ "communities = CommunityDetector().detect_communities(kg, algorithm=\"louvain\")\n",+ "\n",+ "# GraphRAG Multi-Hop Reasoning - Complex Inference\n",+ "reasoner = GraphReasoner(graph=kg)\n",+ "inference = reasoner.reason(\"What is the impact of Python's latest trends on web development frameworks?\", depth=2)\n","\n",- "KGVisualizer().visualize_network(kg, layout=\"spring\", output=\"static\")\n",+ "print(f\"π§ Reasoning Agent Insight: {inference[:250]}...\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 7. Hybrid Context Retrieval\n",+ "\n",+ "Storage using `vector_store` and wrapping it in `AgentContext`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.vector_store import VectorStore\n",+ "from semantica.context import AgentContext\n",+ "\n",+ "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",+ "embeddings = core.embedding_generator.generate_embeddings([str(c) for c in all_chunks[:12]])\n",+ "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in all_chunks[:12]])\n",+ "\n",+ "# Global Context Manager for an Agent\n",+ "context = AgentContext(vector_store=vs, knowledge_graph=kg)\n",+ "\n",+ "print(\"β Hybrid Context Store Initialized.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 8. Immersive Visualization\n",+ "\n",+ "We use `semantica.visualization` to create a community-aware network map."+ ]+ },+ {+ "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",+ "viz.visualize_network(\n",+ " kg, \n",+ " layout=\"spring\", \n",+ " output=\"static\",\n",+ " title=\"Python Ecosystem Intelligence Graph (Multi-Source)\"\n",+ ")\n","plt.show()"]},@@ -185,9 +360,9 @@"cell_type": "markdown","metadata": {},"source": [- "## 6. Advanced Reasoning\n",+ "## 9. Modular Orchestration: The Pipeline\n","\n",- "Using the `reasoning` module to perform complex multi-hop inference over the graph."+ "Finally, we show how to wrap this whole complex flow into a single `semantica.pipeline.Pipeline` object for automation."]},{@@ -196,23 +371,28 @@"metadata": {},"outputs": [],"source": [- "from semantica.reasoning import GraphReasoner\n",+ "from semantica.pipeline import PipelineBuilder\n","\n",- "reasoner = GraphReasoner(graph=kg)\n",- "query = \"How does Python relate to the latest tech trends?\"\n",+ "builder = PipelineBuilder()\n",+ "knowledge_pipeline = (\n",+ " builder.add_step(\"ingest\", \"knowledge_hub_loader\")\n",+ " .add_step(\"normalize\", \"text_normalizer\")\n",+ " .add_step(\"split\", \"semantic_splitter\")\n",+ " .add_step(\"enrich\", \"kg_builder\")\n",+ " .add_step(\"validate\", \"quality_assurance\")\n",+ " .build()\n",+ ")\n","\n",- "# Perform multi-hop reasoning over the KG\n",- "reasoning_result = reasoner.reason(query, depth=2)\n",- "print(f\"π§ Reasoning Results:\\n{reasoning_result[:300]}...\")"+ "print(\"ποΈ Unified Knowledge Pipeline Construct Complete.\")"]},{"cell_type": "markdown","metadata": {},"source": [- "## 7. Context & Export\n",+ "## 10. Persistence & Export\n","\n",- "Wrapping context for an agent and exporting the final Knowledge Graph."+ "Save the finalized knowledge structures."]},{@@ -221,17 +401,12 @@"metadata": {},"outputs": [],"source": [- "from semantica.context import AgentContext\n","from semantica.export import GraphExporter\n","\n",- "# π€ Context\n",- "context = AgentContext(vector_store=vs, knowledge_graph=kg)\n",- "\n",- "# π€ Export\n","exporter = GraphExporter()\n",- "exporter.export_to_json(kg, \"python_tech_graph.json\")\n",+ "exporter.export_to_json(kg, \"master_ecosystem_graph.json\")\n","\n",- "print(\"β Context Ready. Knowledge Graph Exported to JSON.\")"+ "print(\"πΎ Project Exported. Deployment Ready.\")"]}],@@ -251,7 +426,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.10.0"+ "version": "3.11.0"}},"nbformat": 4,