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
Refine notebooks: Removed all emojis for a cleaner, professional presentation
KaifAhmad10c9d6dad64b9
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 568e5e4d..4d981acf 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -6,15 +6,15 @@"source": ["# Semantica Mastery: The Ultimate End-to-End GraphRAG Pipeline\n","\n",- "## π Overview\n",+ "## Overview\n","\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",+ "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",- "### π§ͺ What We Are Building\n",+ "### What We Are Building\n","\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",+ "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",- "### π οΈ Modules Covered\n",+ "### Modules Covered\n","\n","| Module | Purpose |\n","| :--- | :--- |\n",@@ -40,7 +40,7 @@"metadata": {},"outputs": [],"source": [- "# π οΈ Environment Setup\n",+ "# Environment Setup\n","!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu tiktoken beautifulsoup4 python-docx pdfplumber"]},@@ -50,7 +50,7 @@"source": ["## 1. Professional Initialization & Config\n","\n",- "We start by defining a production config. Semantica uses **ConfigManager** to ensure environment consistency."+ "We start by defining a production config. Semantica uses ConfigManager to ensure environment consistency."]},{@@ -86,7 +86,7 @@"\n","config = ConfigManager().load_from_dict(config_dict)\n","core = Semantica(config=config)\n",- "print(\"β Semantica Core Initialized.\")"+ "print(\"Config Loaded.\")"]},{@@ -125,7 +125,7 @@"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.\")"+ "print(f\"Foundation Graph Seeded with {len(foundation_data['entities'])} Verified Nodes.\")"]},{@@ -136,7 +136,7 @@"\n","We aggregate data from a diverse set of real-world sources using `semantica.ingest` and `semantica.parse`. \n","\n",- "### π Data Sources\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",@@ -154,8 +154,8 @@"\n","all_content = []\n","\n",- "# π 1. Web Domain Ingestion\n",- "print(\"π Ingesting Official Documentation...\")\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",@@ -166,8 +166,8 @@" 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",- "# π° 2. Live RSS Feeds\n",- "print(\"\\nπ₯ Fetching Live Tech News...\")\n",+ "# 2. Live RSS Feeds\n",+ "print(\"\\nFetching Live Tech News...\")\n","rss_feeds = [\n"," \"http://feeds.bbci.co.uk/news/technology/rss.xml\",\n"," \"https://techcrunch.com/feed/\",\n",@@ -178,18 +178,17 @@" 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",- "# π» 3. Repository & Technical Files\n",- "print(\"\\nπΏ Ingesting Engineering READMEs...\")\n",+ "# 3. Repository & Technical Files\n",+ "print(\"\\nIngesting 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.\")"+ "print(f\"\\nAggregated {len(all_content)} documents from across the web.\")"]},{@@ -225,7 +224,7 @@"for doc in clean_data:\n"," all_chunks.extend(splitter.split(doc))\n","\n",- "print(f\"β Normalized text and generated {len(all_chunks)} semantic chunks.\")"+ "print(f\"Normalized text and generated {len(all_chunks)} semantic chunks.\")"]},{@@ -234,7 +233,7 @@"source": ["## 5. Knowledge Graph Construction & Data Quality\n","\n",- "Building the graph, then applying **Conflict Resolution** and **Deduplication** to ensure data integrity."+ "Building the graph, then applying Conflict Resolution and Deduplication to ensure data integrity."]},{@@ -249,7 +248,6 @@"\n","# 1. Initial Construction\n","gb = GraphBuilder(merge_entities=True)\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","# 2. Quality Control: Deduplication\n",@@ -258,7 +256,7 @@"if duplicates:\n"," merger = EntityMerger()\n"," kg = merger.merge_duplicates(kg, duplicates)\n",- " print(\"β¨ Deduplicated Entities.\")\n",+ " print(\"Deduplicated Entities.\")\n","\n","# 3. Quality Control: Conflict Resolution\n","conflict_detector = ConflictDetector()\n",@@ -266,9 +264,9 @@"if conflicts:\n"," resolver = ConflictResolver()\n"," kg = resolver.resolve_conflicts(kg, conflicts, strategy=\"most_recent\")\n",- " print(\"βοΈ Resolved Data Conflicts.\")\n",+ " print(\"Resolved Data Conflicts.\")\n","\n",- "print(f\"β High-Quality Knowledge Graph Ready. Nodes: {kg.number_of_nodes()}\")"+ "print(f\"High-Quality Knowledge Graph Ready. Nodes: {kg.number_of_nodes()}\")"]},{@@ -277,7 +275,7 @@"source": ["## 6. Graph Synthesis & Advanced Reasoning\n","\n",- "We apply Graph Analytics and the **Reasoning** module to derive insights not explicitly stated in the text."+ "We apply Graph Analytics and the Reasoning module to derive insights not explicitly stated in the text."]},{@@ -297,7 +295,7 @@"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",- "print(f\"π§ Reasoning Agent Insight: {inference[:250]}...\")"+ "print(f\"Reasoning Agent Insight: {inference[:250]}...\")"]},{@@ -325,7 +323,7 @@"# Global Context Manager for an Agent\n","context = AgentContext(vector_store=vs, knowledge_graph=kg)\n","\n",- "print(\"β Hybrid Context Store Initialized.\")"+ "print(\"Hybrid Context Store Initialized.\")"]},{@@ -383,7 +381,7 @@" .build()\n",")\n","\n",- "print(\"ποΈ Unified Knowledge Pipeline Construct Complete.\")"+ "print(\"Unified Knowledge Pipeline Construct Complete.\")"]},{@@ -406,7 +404,7 @@"exporter = GraphExporter()\n","exporter.export_to_json(kg, \"master_ecosystem_graph.json\")\n","\n",- "print(\"πΎ Project Exported. Deployment Ready.\")"+ "print(\"Project Exported. Deployment Ready.\")"]}],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 8e789c7f..79ab94d4 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,277 +1,233 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# RAG vs. GraphRAG: A Side-by-Side Comparison\n",- "\n",- "This notebook demonstrates the difference between **Standard RAG** (Vector-based) and **GraphRAG** (Graph-based) using the `semantica` framework. We will use a real-world text source to build both systems and compare their retrieval capabilities.\n",- "\n",- "## What is the difference?\n",- "- **Standard RAG**: Retrieves documents based on semantic similarity (vector distance). Good for direct matching but can miss connected concepts.\n",- "- **GraphRAG**: Retrieves information by traversing a Knowledge Graph (nodes and edges). Excellent for multi-hop reasoning and understanding relationships between entities.\n",- "\n",- "## Workflow\n",- "1. **Ingest Data**: Load a technical article.\n",- "2. **Build Standard RAG**: Chunk text -> Embeddings -> Vector Store -> Similarity Search.\n",- "3. **Build GraphRAG**: Extract Entities/Relations -> Knowledge Graph -> Graph Traversal.\n",- "4. **Compare Results**: Ask the same complex question to both systems."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install semantica if not already installed\n",- "!pip install semantica networkx matplotlib plotly sentence-transformers"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "import networkx as nx\n",- "import matplotlib.pyplot as plt\n",- "import numpy as np\n",- "\n",- "# Import Semantica Core Modules\n",- "from semantica.core import Semantica\n",- "from semantica.ingest import WebIngestor\n",- "from semantica.split import TextSplitter # Proper Semantica splitter\n",- "from semantica.vector_store import FAISSStore\n",- "from semantica.embeddings import EmbeddingGenerator # Proper embedding generator\n",- "from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor\n",- "from semantica.kg import GraphBuilder\n",- "from semantica.visualization import KGVisualizer # Proper visualization module\n",- "\n",- "# Initialize Semantica\n",- "semantica = Semantica()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 1. Data Ingestion\n",- "We'll use a text about **\"The Impact of AI on Healthcare\"**. This topic has rich relationships (AI -> improves -> Diagnosis, Privacy -> challenges -> AI)."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Sample \"Real World\" Data Source\n",- "text_content = \"\"\"\n",- "Artificial Intelligence (AI) is revolutionizing healthcare by enabling early diagnosis and personalized treatment plans.\n",- "Machine Learning algorithms analyze medical imaging to detect anomalies like tumors faster than human radiologists.\n",- "For instance, DeepMind's AlphaFold has solved the protein folding problem, accelerating drug discovery.\n",- "However, the integration of AI in healthcare faces significant challenges, primarily concerning patient data privacy and algorithmic bias.\n",- "Regulatory bodies like the FDA are establishing guidelines to ensure AI tools are safe and effective.\n",- "Unlike traditional software, AI systems can adapt and learn, which complicates validation processes.\n",- "Hospitals using predictive analytics have seen a 30% reduction in patient readmission rates.\n",- "Yet, cybersecurity threats remain a critical risk for connected medical devices.\n",- "\"\"\"\n",- "\n",- "print(f\"Loaded text with {len(text_content)} characters.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 2. Standard RAG (Vector Search)\n",- "We will chunk the text using `TextSplitter`, create embeddings with `EmbeddingGenerator`, and store them in a `FAISSStore`."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# 1. Split Text using Semantica's TextSplitter\n",- "splitter = TextSplitter(method=\"recursive\", chunk_size=100, chunk_overlap=20)\n",- "chunks = splitter.split(text_content)\n",- "\n",- "# Extract text from chunk objects\n",- "chunk_texts = [chunk.text for chunk in chunks]\n",- "print(f\"Created {len(chunks)} chunks.\")\n",- "\n",- "# 2. Initialize Vector Store\n",- "vector_store = FAISSStore(dimension=384) # Standard dimension for MiniLM\n",- "vector_store.create_index(index_type=\"flat\", metric=\"L2\")\n",- "\n",- "# 3. Generate Embeddings using Semantica's EmbeddingGenerator\n",- "# This uses local Sentence Transformers by default\n",- "generator = EmbeddingGenerator(text={\"method\": \"sentence_transformers\", \"model_name\": \"all-MiniLM-L6-v2\"})\n",- "embeddings = generator.generate_embeddings(chunk_texts, data_type=\"text\")\n",- "\n",- "# 4. Store Vectors\n",- "vector_store.add_vectors(embeddings, ids=[f\"chunk_{i}\" for i in range(len(chunks))])\n",- "\n",- "# 5. Define a search function\n",- "def standard_rag_search(query):\n",- " # Generate query embedding\n",- " query_vec = generator.generate_embeddings(query, data_type=\"text\")\n",- " \n",- " # Search\n",- " results = vector_store.search_similar(query_vec, k=2)\n",- " \n",- " # Retrieve actual text\n",- " retrieved_texts = []\n",- " for res in results:\n",- " idx = int(res['id'].split('_')[1])\n",- " retrieved_texts.append(chunk_texts[idx])\n",- " return retrieved_texts\n",- "\n",- "print(\"Standard RAG Pipeline Built.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 3. GraphRAG (Knowledge Graph)\n",- "Now we extract entities and relationships to build a structured graph using `GraphBuilder` and visualize it with `KGVisualizer`."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# 1. Extract Entities and Relations\n",- "ner = NamedEntityRecognizer()\n",- "rel_extractor = RelationExtractor()\n",- "\n",- "entities = ner.extract_entities(text_content)\n",- "relations = rel_extractor.extract_relations(text_content, entities=entities)\n",- "\n",- "print(f\"Extracted {len(entities)} entities and {len(relations)} relationships.\")\n",- "\n",- "# 2. Build Graph using Semantica's GraphBuilder\n",- "builder = GraphBuilder()\n",- "kg = builder.build([{\"entities\": entities, \"relationships\": relations}])\n",- "\n",- "# 3. Visualize Graph using Semantica's KGVisualizer\n",- "viz = KGVisualizer()\n",- "fig = viz.visualize_network(kg, output=\"interactive\")\n",- "fig.show()\n",- "\n",- "# Fallback static visualization if interactive fails in some environments\n",- "# plt.figure(figsize=(10, 8))\n",- "# pos = nx.spring_layout(kg, k=0.5)\n",- "# nx.draw(kg, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=10)\n",- "# edge_labels = nx.get_edge_attributes(kg, 'relation')\n",- "# nx.draw_networkx_edge_labels(kg, pos, edge_labels=edge_labels)\n",- "# plt.show()"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# 4. Define Graph Search Function\n",- "def graph_rag_search(start_entity, hops=1):\n",- " if start_entity not in kg:\n",- " # Try simple fuzzy match\n",- " for node in kg.nodes():\n",- " if start_entity.lower() in node.lower():\n",- " start_entity = node\n",- " break\n",- " else:\n",- " return [f\"Entity '{start_entity}' not found in graph.\"]\n",- " \n",- " # Traverse graph\n",- " subgraph_nodes = list(nx.bfs_tree(kg, source=start_entity, depth_limit=hops))\n",- " subgraph = kg.subgraph(subgraph_nodes)\n",- " \n",- " # Convert paths to natural language\n",- " facts = []\n",- " for u, v, data in subgraph.edges(data=True):\n",- " relation = data.get('relation', 'related to')\n",- " facts.append(f\"{u} --[{relation}]--> {v}\")\n",- " \n",- " return facts"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 4. Comparison Results\n",- "Let's compare what each system retrieves for the query: **\"What are the risks associated with AI?\"**"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "query = \"What are the risks associated with AI?\"\n",- "\n",- "print(f\"Query: {query}\\n\")\n",- "\n",- "print(\"--- Standard RAG Results (Vector Similarity) ---\")\n",- "rag_results = standard_rag_search(query)\n",- "for i, res in enumerate(rag_results):\n",- " print(f\"{i+1}. {res}...\")\n",- "\n",- "print(\"\\n--- GraphRAG Results (Graph Traversal) ---\")\n",- "# In a full system, we would link the query \"AI\" to the node \"Artificial Intelligence\"\n",- "graph_results = graph_rag_search(\"Artificial Intelligence\", hops=2)\n",- "for i, res in enumerate(graph_results):\n",- " print(f\"{i+1}. {res}\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "| Feature | Standard RAG | GraphRAG |\n",- "|---------|--------------|----------|\n",- "| **Mechanism** | Semantic Similarity (Vector) | Graph Traversal (Structural) |\n",- "| **Strengths** | Fast, good for general queries | Captures explicit relationships, multi-hop reasoning |\n",- "| **Weaknesses**| May miss disconnected chunks | Requires entity extraction & graph construction overhead |\n",- "| **Best For** | Fact retrieval | Complex reasoning & relationship mapping |\n",- "\n",- "**Semantica** allows you to combine both into a **Hybrid RAG** system for optimal performance."- ]- }- ],- "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.8.5"- }- },- "nbformat": 4,- "nbformat_minor": 4+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# RAG vs. GraphRAG: Global Intelligence Edition\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\": text} for text in clean_docs[:10]])\n",+ "\n",+ "detector = DuplicateDetector(similarity_threshold=0.85)\n",+ "\n",+ "print(f\"GraphRAG Synthesis Complete: {kg.number_of_nodes()} 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.reasoning import GraphReasoner\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",+ "reasoner = GraphReasoner(graph=kg)\n",+ "g_res = reasoner.reason(query, depth=2)\n",+ "print(f\"Final Combined Intelligence: {g_res[:400]}...\")"+ ]+ },+ {+ "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}\ No newline at end of file