Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: professional restructure of comparison notebook and core API enhancements

KaifAhmad1b07b1d58f7d8
diff --git a/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb b/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb
index 85989d0c..84b467c6 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,243 +1,239 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# RAG vs. GraphRAG: \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 the Global Intelligence & security domain.\n",
- "\n",
- "### The Challenge: Navigating Fragmentation\n",
- "In intelligence work, facts are scattered. One report might mention a person, another a location, and a third a specific project. Vector search often fails to bridge these \"semantic gaps\" if the keywords aren't directly co-located.\n",
- "\n",
- "We will demonstrate how GraphRAG creates a \"Chain of Evidence\" that Vector RAG simply cannot see.\n",
- "\n",
- "### Key Semantica Modules Utilized\n",
- "\n",
- "| Pipeline Stage | Modules Selection |\n",
- "| :--- | :--- |\n",
- "| **Intelligence Gathering** | `semantica.ingest`, `semantica.normalize` |\n",
- "| **Vector Pipeline** | `semantica.split`, `semantica.vector_store` |\n",
- "| **Graph Pipeline** | `semantica.kg`, `semantica.deduplication`, `semantica.conflicts` |\n",
- "| **Inference/Reasoning**| `semantica.reasoning`, `semantica.pipeline` |\n",
- "| **Interface** | `semantica.context`, `semantica.visualization` |"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Setup\n",
- "!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 1. Domain Acquisition: Real-World Intelligence Feeds\n",
- "\n",
- "We ingest from real-world feeds to build our knowledge base. We'll look for connections across global security news and official reports."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import WebIngestor, FeedIngestor\n",
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "normalizer = TextNormalizer()\n",
- "all_content = []\n",
- "\n",
- "print(\"Gathering Intelligence Data...\")\n",
- "\n",
- "# 1. Global News Feeds\n",
- "feeds = [\n",
- " \"http://feeds.bbci.co.uk/news/world/rss.xml\",\n",
- " \"https://www.reutersagency.com/feed/\" \n",
- "]\n",
- "feed_ingestor = FeedIngestor()\n",
- "for f in feeds:\n",
- " docs = feed_ingestor.ingest(f)[:5]\n",
- " all_content.extend([d.content if hasattr(d, 'content') else str(d) for d in docs])\n",
- "\n",
- "# 2. Official Intelligence/Security Overviews\n",
- "web_urls = [\n",
- " \"https://www.cia.gov/the-world-factbook/\",\n",
- " \"https://www.un.org/en/observances/security-council-day\"\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_docs = [normalizer.normalize(text) for text in all_content if len(text) > 100]\n",
- "\n",
- "print(f\"\\nIntelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 2. Standard Vector RAG Pipeline\n",
- "\n",
- "The baseline approach: Linear retrieval via semantic overlap."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.split import TextSplitter\n",
- "from semantica.vector_store import VectorStore\n",
- "\n",
- "v_core = Semantica(config=ConfigManager().load_from_dict({\n",
- " \"embedding\": {\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"},\n",
- " \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 1536}\n",
- "}))\n",
- "\n",
- "splitter = TextSplitter(method=\"recursive\", chunk_size=800, chunk_overlap=100)\n",
- "chunks = []\n",
- "for doc in clean_docs:\n",
- " chunks.extend(splitter.split(doc))\n",
- "\n",
- "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",
- "embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks[:20]])\n",
- "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks[:20]])\n",
- "\n",
- "print(f\"Vector RAG ready with {len(chunks[:20])} encoded fragments.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3. High-Fidelity GraphRAG Pipeline\n",
- "\n",
- "Utilizing Entity resolution and relationship synthesis to bridge reports."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.kg import GraphBuilder\n",
- "from semantica.deduplication import DuplicateDetector\n",
- "from semantica.conflicts import ConflictDetector\n",
- "\n",
- "gb = GraphBuilder(merge_entities=True)\n",
- "kg = gb.build(sources=[{\"text\": str(c.text)} for c in chunks[:12]])\n",
- "\n",
- "detector = DuplicateDetector(similarity_threshold=0.85)\n",
- "\n",
- "print(f\"GraphRAG Synthesis Complete: {len(kg.get('entities', []))} Entity Nodes mapped.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4. The Intelligence Test: Multi-Source Linkage\n",
- "\n",
- "Intelligence query: \"What are the current global security challenges mentioned across different regions?\"\n",
- "\n",
- "Vector RAG will likely return fragments about specific countries but fail to group them. GraphRAG will traverse nodes of type Region to find shared CHALLENGE edges."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.kg import ConnectivityAnalyzer\n",
- "from semantica.reasoning import InferenceEngine\n",
- "\n",
- "query = \"Identify interconnected security risks across the UN and major regions.\"\n",
- "print(f\"Investigative Query: {query}\\n\")\n",
- "\n",
- "print(\"--- Standard Vector Recall ---\")\n",
- "q_vec = v_core.embedding_generator.generate_embeddings(query)\n",
- "v_res = vs.search_vectors(q_vec, k=3)\n",
- "for r in v_res:\n",
- " print(f\"Recall: {r['metadata']['text'][:150]}...\")\n",
- "\n",
- "print(\"\\n--- Graph Intelligence Reasoning ---\")\n",
- "analyzer = ConnectivityAnalyzer()\n",
- "connectivity = analyzer.analyze_graph_structure(kg)\n",
- "\n",
- "# Advanced Feature: Inference-Enhanced GraphRAG\n",
- "# Vector RAG only sees surface similarity. \n",
- "# InferenceEngine can follow logical rules (e.g., IF Conflict in Region A AND Region A is part of Trade Route B -> THEN Trade Route B is AT RISK)\n",
- "engine = InferenceEngine(strategy=\"forward\")\n",
- "engine.add_rule(\"IF ?x :type 'Conflict' AND ?y :type 'Region' AND ?x :locatedIn ?y THEN ?y :status 'HighRisk'\")\n",
- "\n",
- "print(f\"Knowledge Structure: {connectivity.get('structure_type', 'complex')}\")\n",
- "print(f\"Identified {len(connectivity.get('bridges', []))} critical intelligence bridges.\")\n",
- "print(\"Logical Inference Engine active: Monitoring for high-risk regional propagation.\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 5. Visualizing the Semantic Network\n",
- "\n",
- "We visualize how the Semantica engine has mapped the relationships between global actors and current events."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "KGVisualizer().visualize_network(\n",
- " kg, \n",
- " layout=\"spring\", \n",
- " output=\"static\",\n",
- " title=\"Intelligence Connectivity Map\"\n",
- ")\n",
- "plt.show()"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.10.0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "de0a7591",
+ "metadata": {},
+ "source": [
+ "# RAG vs. GraphRAG: Investigative Intelligence Comparison\n",
+ "\n",
+ "## Overview\n",
+ "This notebook provides a rigorous, side-by-side comparison of **Standard RAG (Vector-based)** and **GraphRAG (Graph-based)**, focusing on the Global Intelligence and Security domain.\n",
+ "\n",
+ "### The Challenge: Navigating Fragmentation\n",
+ "In intelligence work, facts are scattered across reports. Vector search often fails to bridge \"semantic gaps\"—logical connections between entities that are not physically co-located in text. \n",
+ "\n",
+ "We will demonstrate how GraphRAG creates a **\"Chain of Evidence\"** that Vector RAG cannot see.\n",
+ "\n",
+ "### Framework: Semantica\n",
+ "We use the [Semantica](https://github.com/Hawksight-AI/semantica) framework to orchestrate common intelligence tasks like entity resolution, conflict detection, and graph-based reasoning."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ca782326",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Environment Setup\n",
+ "import os\n",
+ "import sys\n",
+ "\n",
+ "# Ensure Groq API Key is set if using Groq\n",
+ "# os.environ['GROQ_API_KEY'] = 'your-key'\n",
+ "\n",
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "889e971d",
+ "metadata": {},
+ "source": [
+ "## 1. Domain Acquisition: Real-World Intelligence gathering\n",
+ "We ingest from high-signal feeds to build our knowledge base."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b332d1ab",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import WebIngestor, FeedIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "all_content = []\n",
+ "\n",
+ "# 1. Global News Feeds (RSS)\n",
+ "feeds = [\n",
+ " \"http://feeds.bbci.co.uk/news/world/rss.xml\",\n",
+ " \"https://www.reutersagency.com/feed/\" \n",
+ "]\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "for f in feeds:\n",
+ " try:\n",
+ " data = feed_ingestor.ingest_feed(f) # FIXED: Use ingest_feed, not ingest\n",
+ " items = data.items[:5]\n",
+ " all_content.extend([getattr(item, 'content', getattr(item, 'text', str(item))) for item in items])\n",
+ " except Exception as e:\n",
+ " print(f\"Warning: Failed to ingest feed {f}: {e}\")\n",
+ "\n",
+ "# 2. Strategic Overviews (Web)\n",
+ "web_urls = [\n",
+ " \"https://www.cia.gov/the-world-factbook/\",\n",
+ " \"https://www.un.org/en/observances/security-council-day\"\n",
+ "]\n",
+ "web_ingestor = WebIngestor()\n",
+ "for url in web_urls:\n",
+ " try:\n",
+ " content = web_ingestor.ingest_url(url) # FIXED: Use ingest_url, not ingest\n",
+ " all_content.append(getattr(content, 'text', getattr(content, 'content', str(content))))\n",
+ " except Exception as e:\n",
+ " print(f\"Warning: Failed to ingest URL {url}: {e}\")\n",
+ "\n",
+ "# Clean and normalize\n",
+ "clean_docs = [normalizer.normalize(text) for text in all_content if len(text) > 50]\n",
+ "print(f\"Intelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ba35952",
+ "metadata": {},
+ "source": [
+ "## 2. Standard Vector RAG Pipeline\n",
+ "Linear retrieval via semantic embedding overlap."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aedbf41c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.core import Semantica\n",
+ "from semantica.split import TextSplitter\n",
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "# v_core = Semantica(embedding={\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"})\n",
+ "# Using framework defaults which utilize the core.config\n",
+ "v_core = Semantica()\n",
+ "\n",
+ "splitter = TextSplitter(method=\"recursive\", chunk_size=600, chunk_overlap=50)\n",
+ "chunks = []\n",
+ "for doc in clean_docs[:10]:\n",
+ " chunks.extend(splitter.split(doc))\n",
+ "\n",
+ "# Initialize Vector Store\n",
+ "vs = VectorStore(backend=\"faiss\", dimension=1536) \n",
+ "embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks[:15]])\n",
+ "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks[:15]])\n",
+ "\n",
+ "print(f\"Vector RAG ready with {len(chunks[:15])} encoded fragments.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "92d1b0cf",
+ "metadata": {},
+ "source": [
+ "## 3. High-Fidelity GraphRAG Pipeline\n",
+ "Synthesizing entities and relationships from fragmented reports."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c66212ed",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "gb = GraphBuilder(merge_entities=True)\n",
+ "# We process a subset for demonstration\n",
+ "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:10]])\n",
+ "\n",
+ "print(f\"GraphRAG Synthesis Complete: {len(kg.get('entities', []))} entities, {len(kg.get('relationships', []))} relationships.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7b97e797",
+ "metadata": {},
+ "source": [
+ "## 4. The Intelligence Challenge: Multi-Hop Inference\n",
+ "Standard RAG finds fragments *about* a topic. GraphRAG finds *connections between* topics.\n",
+ "\n",
+ "Query: **\"Identify high-risk security escalations and their regional implications.\"**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0b9fcae5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import InferenceEngine\n",
+ "\n",
+ "print(\"--- Standard Vector Recall ---\")\n",
+ "q_vec = v_core.embedding_generator.generate_embeddings(\"security risks and regional conflict\")\n",
+ "v_res = vs.search_vectors(q_vec, k=3)\n",
+ "for r in v_res:\n",
+ " print(f\"Recall: {r['metadata']['text'][:120]}...\")\n",
+ "\n",
+ "print(\"\\n--- Graph Intelligence Reasoning ---\")\n",
+ "engine = InferenceEngine(strategy=\"forward\")\n",
+ "\n",
+ "# Prefix Rule: IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)\n",
+ "engine.add_rule(\"IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)\")\n",
+ "\n",
+ "# Add facts from extracted KG\n",
+ "for rel in kg.get('relationships', []):\n",
+ " source = rel.get('source', '')\n",
+ " target = rel.get('target', '')\n",
+ " rtype = rel.get('type', '').lower()\n",
+ " \n",
+ " if 'locate' in rtype or 'in' in rtype:\n",
+ " engine.add_fact(f\"LocatedIn({source}, {target})\")\n",
+ "\n",
+ "# Simulated High-Priority Facts for demonstration\n",
+ "engine.add_fact(\"Conflict(Political_Internal_Unrest)\")\n",
+ "engine.add_fact(\"LocatedIn(Political_Internal_Unrest, Strategic_Region_A)\")\n",
+ "\n",
+ "# Perform Inference\n",
+ "results = engine.forward_chain()\n",
+ "for res in results:\n",
+ " print(f\"Inferred: {res.conclusion}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5928355c",
+ "metadata": {},
+ "source": [
+ "## 5. Visualizing the Intelligence Landscape\n",
+ "Seeing the 'Bridges' between disconnected events."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b209720f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "viz = KGVisualizer()\n",
+ "viz.visualize_network(\n",
+ " kg,\n",
+ " output=\"static\",\n",
+ " title=\"Intelligence Connectivity Map\"\n",
+ ")\n",
+ "plt.show()"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
}
diff --git a/restructure_utf8.py b/restructure_utf8.py
new file mode 100644
index 00000000..a6b4dc63
--- /dev/null
+++ b/restructure_utf8.py
@@ -0,0 +1,167 @@
+
+import nbformat as nbf
+import os
+import sys
+
+nb = nbf.v4.new_notebook()
+
+# Phase 0: Overview
+nb.cells.append(nbf.v4.new_markdown_cell("""# RAG vs. GraphRAG: Investigative Intelligence Comparison
+
+## Overview
+This notebook provides a rigorous, side-by-side comparison of **Standard RAG (Vector-based)** and **GraphRAG (Graph-based)**, focusing on the Global Intelligence and Security domain.
+
+### The Challenge: Navigating Fragmentation
+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.
+
+We will demonstrate how GraphRAG creates a **"Chain of Evidence"** that Vector RAG cannot see.
+
+### Framework: Semantica
+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."""))
+
+# Phase 0: Setup
+nb.cells.append(nbf.v4.new_code_cell("""# Environment Setup
+import os
+import sys
+
+# Ensure Groq API Key is set if using Groq
+# os.environ['GROQ_API_KEY'] = 'your-key'
+
+%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"""))
+
+# Phase 1: Gathering
+nb.cells.append(nbf.v4.new_markdown_cell("""## 1. Domain Acquisition: Real-World Intelligence gathering
+We ingest from high-signal feeds to build our knowledge base."""))
+
+nb.cells.append(nbf.v4.new_code_cell("""from semantica.ingest import WebIngestor, FeedIngestor
+from semantica.normalize import TextNormalizer
+
+normalizer = TextNormalizer()
+all_content = []
+
+# 1. Global News Feeds (RSS)
+feeds = [
+ "http://feeds.bbci.co.uk/news/world/rss.xml",
+ "https://www.reutersagency.com/feed/"
+]
+feed_ingestor = FeedIngestor()
+for f in feeds:
+ try:
+ data = feed_ingestor.ingest_feed(f) # FIXED: Use ingest_feed, not ingest
+ items = data.items[:5]
+ all_content.extend([getattr(item, 'content', getattr(item, 'text', str(item))) for item in items])
+ except Exception as e:
+ print(f"Warning: Failed to ingest feed {f}: {e}")
+
+# 2. Strategic Overviews (Web)
+web_urls = [
+ "https://www.cia.gov/the-world-factbook/",
+ "https://www.un.org/en/observances/security-council-day"
+]
+web_ingestor = WebIngestor()
+for url in web_urls:
+ try:
+ content = web_ingestor.ingest_url(url) # FIXED: Use ingest_url, not ingest
+ all_content.append(getattr(content, 'text', getattr(content, 'content', str(content))))
+ except Exception as e:
+ print(f"Warning: Failed to ingest URL {url}: {e}")
+
+# Clean and normalize
+clean_docs = [normalizer.normalize(text) for text in all_content if len(text) > 50]
+print(f"Intelligence Knowledge Hub Populated with {len(clean_docs)} reports.")"""))
+
+# Phase 2: Vector RAG
+nb.cells.append(nbf.v4.new_markdown_cell("""## 2. Standard Vector RAG Pipeline
+Linear retrieval via semantic embedding overlap."""))
+
+nb.cells.append(nbf.v4.new_code_cell("""from semantica.core import Semantica
+from semantica.split import TextSplitter
+from semantica.vector_store import VectorStore
+
+# v_core = Semantica(embedding={"provider": "openai", "model": "text-embedding-3-small"})
+# Using framework defaults which utilize the core.config
+v_core = Semantica()
+
+splitter = TextSplitter(method="recursive", chunk_size=600, chunk_overlap=50)
+chunks = []
+for doc in clean_docs[:10]:
+ chunks.extend(splitter.split(doc))
+
+# Initialize Vector Store
+vs = VectorStore(backend="faiss", dimension=1536)
+embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks[:15]])
+vs.store_vectors(vectors=embeddings, metadata=[{"text": str(c)} for c in chunks[:15]])
+
+print(f"Vector RAG ready with {len(chunks[:15])} encoded fragments.")"""))
+
+# Phase 3: GraphRAG
+nb.cells.append(nbf.v4.new_markdown_cell("""## 3. High-Fidelity GraphRAG Pipeline
+Synthesizing entities and relationships from fragmented reports."""))
+
+nb.cells.append(nbf.v4.new_code_cell("""from semantica.kg import GraphBuilder
+from semantica.deduplication import DuplicateDetector
+
+gb = GraphBuilder(merge_entities=True)
+# We process a subset for demonstration
+kg = gb.build(sources=[{"text": str(c)} for c in chunks[:10]])
+
+print(f"GraphRAG Synthesis Complete: {len(kg.get('entities', []))} entities, {len(kg.get('relationships', []))} relationships.")"""))
+
+# Phase 4: Comparative Test
+nb.cells.append(nbf.v4.new_markdown_cell("""## 4. The Intelligence Challenge: Multi-Hop Inference
+Standard RAG finds fragments *about* a topic. GraphRAG finds *connections between* topics.
+
+Query: **"Identify high-risk security escalations and their regional implications."**"""))
+
+nb.cells.append(nbf.v4.new_code_cell("""from semantica.reasoning import InferenceEngine
+
+print("--- Standard Vector Recall ---")
+q_vec = v_core.embedding_generator.generate_embeddings("security risks and regional conflict")
+v_res = vs.search_vectors(q_vec, k=3)
+for r in v_res:
+ print(f"Recall: {r['metadata']['text'][:120]}...")
+
+print("\\n--- Graph Intelligence Reasoning ---")
+engine = InferenceEngine(strategy="forward")
+
+# Prefix Rule: IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)
+engine.add_rule("IF Conflict(?x) AND LocatedIn(?x, ?y) THEN HighRisk(?y)")
+
+# Add facts from extracted KG
+for rel in kg.get('relationships', []):
+ source = rel.get('source', '')
+ target = rel.get('target', '')
+ rtype = rel.get('type', '').lower()
+
+ if 'locate' in rtype or 'in' in rtype:
+ engine.add_fact(f"LocatedIn({source}, {target})")
+
+# Simulated High-Priority Facts for demonstration
+engine.add_fact("Conflict(Political_Internal_Unrest)")
+engine.add_fact("LocatedIn(Political_Internal_Unrest, Strategic_Region_A)")
+
+# Perform Inference
+results = engine.forward_chain()
+for res in results:
+ print(f"Inferred: {res.conclusion}")"""))
+
+# Phase 5: Visualization
+nb.cells.append(nbf.v4.new_markdown_cell("""## 5. Visualizing the Intelligence Landscape
+Seeing the 'Bridges' between disconnected events."""))
+
+nb.cells.append(nbf.v4.new_code_cell("""from semantica.visualization import KGVisualizer
+import matplotlib.pyplot as plt
+
+viz = KGVisualizer()
+viz.visualize_network(
+ kg,
+ output="static",
+ title="Intelligence Connectivity Map"
+)
+plt.show()"""))
+
+target_path = 'cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb'
+with open(target_path, 'w', encoding='utf-8') as f:
+ nbf.write(nb, f)
+
+print(f"Successfully restructured {target_path} (UTF-8)")
diff --git a/semantica/core/orchestrator.py b/semantica/core/orchestrator.py
index b833bd86..6e4e6e18 100644
--- a/semantica/core/orchestrator.py
+++ b/semantica/core/orchestrator.py
@@ -99,6 +99,42 @@ class Semantica:
self.logger.info("Semantica framework initialized")
+ @property
+ def embedding_generator(self) -> Any:
+ """
+ Get the framework's embedding generator.
+
+ Returns:
+ EmbeddingGenerator instance
+ """
+ if "embedding_generator" not in self._modules:
+ try:
+ from ..embeddings import EmbeddingGenerator
+ self._modules["embedding_generator"] = EmbeddingGenerator(
+ config=self.config.get("embedding", {})
+ )
+ except ImportError as e:
+ self.logger.warning(f"Could not import EmbeddingGenerator: {e}")
+ raise ProcessingError(f"Embeddings module not available: {e}")
+ return self._modules["embedding_generator"]
+
+ @property
+ def reasoner(self) -> Any:
+ """
+ Get the framework's graph reasoner.
+
+ Returns:
+ GraphReasoner instance
+ """
+ if "reasoner" not in self._modules:
+ try:
+ from ..reasoning import GraphReasoner
+ self._modules["reasoner"] = GraphReasoner(config=self.config)
+ except ImportError as e:
+ self.logger.warning(f"Could not import GraphReasoner: {e}")
+ raise ProcessingError(f"Reasoning module not available: {e}")
+ return self._modules["reasoner"]
+
@log_execution_time
def initialize(self) -> None:
"""