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
feat: enhance GraphRAG notebooks with AgentContext and improve VectorStore API
KaifAhmad1644314e9768f
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 20e95b25..c5179528 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -2,66 +2,59 @@"cells": [{"cell_type": "markdown",- "id": "9570d208",+ "id": "31d1a12c","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: Skincare Intelligence System\n","## π Overview\n",- "\n",- "This notebook demonstrates the construction and querying of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain. \n",+ "This notebook demonstrates the construction and querying of a **highly detailed Knowledge Graph** for the Skincare and Dermatology domain using the Semantica framework.\n","\n","### ποΈ Pipeline Architecture\n","1. **Phase 0: Foundation**: Environment setup and \"Ground Truth\" seeding.\n","2. **Phase 1: Multi-Source Ingestion**: Aggregating knowledge from Expert RSS Feeds and clinical guides.\n",- "3. **Phase 2: Semantic Extraction**: Deep extraction using `semantica.semantic_extract` via **Llama 3.1 8B**.\n",+ "3. **Phase 2: Semantic Extraction**: Deep extraction of entities and relationships using Llama 3.1.\n","4. **Phase 3: Refinement**: Autonomous deduplication and conflict resolution.\n",- "5. **Phase 4: Multi-Hop Question Answering**: Interactive user queries using **Graph-Enhanced Retrieval**.\n",- "\n",- "---"+ "5. **Phase 4: Multi-Hop Question Answering**: Interactive user queries using **AgentContext (Hybrid Retrieval)**."]},{"cell_type": "code","execution_count": 1,- "id": "aa672d39",+ "id": "fdef52b8","metadata": {},"outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Note: you may need to restart the kernel to use updated packages.\n"+ ]+ },{"name": "stderr","output_type": "stream","text": [- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",- "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"]}],"source": ["# Install dependencies\n",- "!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers"- ]- },- {- "cell_type": "markdown",- "id": "b7a767b5",- "metadata": {},- "source": [- "## π οΈ Phase 0: Environment & Foundation\n",- "We configure **Groq** as our primary LLM provider and use **Sentence-Transformers** for local embeddings to avoid API dependencies."+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers"]},{"cell_type": "code",- "execution_count": 2,- "id": "6840539f",+ "execution_count": 8,+ "id": "508c1ce5","metadata": {},"outputs": [{@@ -71,18 +64,6 @@"fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"]},- {- "data": {- "text/html": [- "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>GraphBuilder</td><td>-</td><td>20.76s</td></tr><tr><td>π</td><td>Semantica is building</td><td>π§ kg</td><td>EntityResolver</td><td>-</td><td>146.04s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>DuplicateDetector</td><td>-</td><td>1.99s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.05s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>EntityMerger</td><td>-</td><td>0.33s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.09s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is indexing</td><td>π vector_store</td><td>VectorStore</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is processing</td><td>π context</td><td>ContextRetriever</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>KGVisualizer</td><td>-</td><td>0.64s</td></tr></table></div>"- ],- "text/plain": [- "<IPython.core.display.HTML object>"- ]- },- "metadata": {},- "output_type": "display_data"- },{"name": "stdout","output_type": "stream",@@ -100,9 +81,7 @@"from semantica.vector_store import VectorStore\n","\n","# 1. Groq Configuration\n",- "import getpass\n",- "if \"GROQ_API_KEY\" not in os.environ:\n",- " os.environ[\"GROQ_API_KEY\"] = getpass.getpass(\"Enter your Groq API Key: \")\n",+ "os.environ[\"GROQ_API_KEY\"] = \"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\"\n","\n","config_dict = {\n"," \"project_name\": \"Skincare_Intelligence\",\n",@@ -146,7 +125,7 @@},{"cell_type": "markdown",- "id": "9f2ce49c",+ "id": "0b1a2ebc","metadata": {},"source": ["## π₯ Phase 1: Ingestion & Processing\n",@@ -155,8 +134,8 @@},{"cell_type": "code",- "execution_count": 3,- "id": "879f9fd9",+ "execution_count": 9,+ "id": "52f20118","metadata": {},"outputs": [{@@ -164,98 +143,29 @@"output_type": "stream","text": ["Ingesting from: https://makeupandbeautyblog.com/feed\n",- "Ingesting from: https://www.westlakedermatology.com/feed\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "Failed to fetch feed https://www.westlakedermatology.com/feed: 403 Client Error: Forbidden for url: https://www.westlakedermatology.com/feed\n",- "Failed to ingest feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.westlakedermatology.com/feed\n"- ]- },- {- "name": "stdout",- "output_type": "stream",- "text": [- "Failed to ingest https://www.westlakedermatology.com/feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.westlakedermatology.com/feed\n",- "Ingesting from: https://www.contourderm.com/feed\n",- "Ingesting from: https://www.michelegreenmd.com/feed\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "Failed to fetch feed https://www.michelegreenmd.com/feed: 403 Client Error: Forbidden for url: https://www.michelegreenmd.com/feed\n",- "Failed to ingest feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.michelegreenmd.com/feed\n"- ]- },- {- "name": "stdout",- "output_type": "stream",- "text": [- "Failed to ingest https://www.michelegreenmd.com/feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.michelegreenmd.com/feed\n",- "Ingesting from: https://www.skincarephysicians.net/blog/feed/\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "Failed to fetch feed https://www.skincarephysicians.net/blog/feed/: 403 Client Error: Forbidden for url: https://www.skincarephysicians.net/blog/feed/\n",- "Failed to ingest feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.skincarephysicians.net/blog/feed/\n"- ]- },- {- "name": "stdout",- "output_type": "stream",- "text": [- "Failed to ingest https://www.skincarephysicians.net/blog/feed/: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.skincarephysicians.net/blog/feed/\n",- "Ingesting from: https://www.beautifulwithbrains.com/blog/feed/\n"- ]- },- {- "name": "stderr",- "output_type": "stream",- "text": [- "Failed to fetch feed https://www.beautifulwithbrains.com/blog/feed/: 403 Client Error: Forbidden for url: https://www.beautifulwithbrains.com/blog/feed/\n",- "Failed to ingest feed: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.beautifulwithbrains.com/blog/feed/\n"- ]- },- {- "name": "stdout",- "output_type": "stream",- "text": [- "Failed to ingest https://www.beautifulwithbrains.com/blog/feed/: Failed to fetch feed: 403 Client Error: Forbidden for url: https://www.beautifulwithbrains.com/blog/feed/\n","Ingesting from: https://www.drbaileyskincare.com/blogs/blog.atom\n",- "β Phase 1 Complete. Generated 77 semantic chunks.\n"+ "β Phase 1 Complete. Generated 74 semantic chunks.\n"]}],"source": [- "from semantica.ingest import ingest_feed, ingest_file\n",+ "from semantica.ingest import FeedIngestor\n","from semantica.split import EntityAwareChunker\n","from semantica.normalize import TextNormalizer\n","\n","sources = []\n",+ "feed_ingestor = FeedIngestor()\n","\n","# 1. RSS Ingestion\n","feed_urls = [\n"," \"https://makeupandbeautyblog.com/feed\",\n",- " \"https://www.westlakedermatology.com/feed\",\n",- " \"https://www.contourderm.com/feed\",\n",- " \"https://www.michelegreenmd.com/feed\",\n",- " \"https://www.skincarephysicians.net/blog/feed/\",\n",- " \"https://www.beautifulwithbrains.com/blog/feed/\",\n"," \"https://www.drbaileyskincare.com/blogs/blog.atom\"\n","]\n","\n","for url in feed_urls:\n"," try:\n"," print(f\"Ingesting from: {url}\")\n",- " feed_data = ingest_feed(url, method=\"rss\")\n",+ " feed_data = feed_ingestor.ingest_feed(url)\n"," sources.extend([item.content or item.description for item in feed_data.items[:3]])\n"," except Exception as e:\n"," print(f\"Failed to ingest {url}: {e}\")\n",@@ -267,7 +177,6 @@"Precautions: Should not be used with high-concentration AHA/BHA exfoliants.\n","Synergy: Highly effective when paired with Niacinamide to offset potential erythema.\n","\"\"\"\n",- "with open(\"expert_guide.txt\", \"w\") as f: f.write(expert_content)\n","sources.append(expert_content)\n","\n","# 3. Chunking & Normalization\n",@@ -284,7 +193,7 @@},{"cell_type": "markdown",- "id": "86a699bc",+ "id": "de3c9cc0","metadata": {},"source": ["## π§ Phase 2: Semantic Extraction\n",@@ -293,16 +202,29 @@},{"cell_type": "code",- "execution_count": 4,- "id": "54fa8fad",+ "execution_count": 10,+ "id": "10be6143","metadata": {},"outputs": [{"name": "stdout","output_type": "stream","text": [- "Extracting intelligence from chunks...\n",- "β Phase 2 Complete. Extracted 30 entities.\n"+ "Extracting intelligence from chunks...\n"+ ]+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "LLM relation extraction failed: Failed to parse JSON from Groq response: No JSON structure found in response\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "β Phase 2 Complete. Extracted 29 entities.\n"]}],@@ -327,7 +249,7 @@},{"cell_type": "markdown",- "id": "19a78219",+ "id": "0ef80273","metadata": {},"source": ["## β¨ Phase 3: Graph Refinement\n",@@ -336,8 +258,8 @@},{"cell_type": "code",- "execution_count": 5,- "id": "97a63461",+ "execution_count": 12,+ "id": "c836e86f","metadata": {},"outputs": [{@@ -351,7 +273,7 @@"name": "stdout","output_type": "stream","text": [- "β Phase 3 Complete. Graph contains 9 resolved entities.\n"+ "β Phase 3 Complete. Graph contains 10 resolved entities.\n"]}],@@ -360,10 +282,9 @@"\n","# 1. Build & Vectorize\n","gb = GraphBuilder(merge_entities=True)\n",- "kg = gb.build([combined_results])\n",+ "kg = gb.build(sources=[combined_results])\n","\n","# 2. Deduplicate\n",- "# Use EntityResolver for comprehensive deduplication and merging\n","resolver = EntityResolver(similarity_threshold=0.85)\n","kg_final = {**kg, 'entities': resolver.resolve_entities(kg['entities'])}\n","\n",@@ -377,17 +298,17 @@},{"cell_type": "markdown",- "id": "b1d1ffb3",+ "id": "76cbe42a","metadata": {},"source": ["## π¬ Phase 4: Interactive GraphRAG Question Answering\n",- "Enter a skincare query to see the **multi-hop retrieval** and **final answer**."+ "Using **AgentContext** for unified hybrid retrieval."]},{"cell_type": "code",- "execution_count": 6,- "id": "4edf258c",+ "execution_count": 15,+ "id": "29d04181","metadata": {},"outputs": [{@@ -395,20 +316,40 @@"output_type": "stream","text": ["\n",- "π Processing Multi-Hop Query: What ingredients synergize with Retinol to prevent irritation?\n",+ "π Processing Multi-Hop Query: What ingredients synergize with Retinol to prevent irritation?\n"+ ]+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\numpy\\linalg\\linalg.py:2582: RuntimeWarning:\n",+ "\n",+ "overflow encountered in multiply\n",+ "\n",+ "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:498: RuntimeWarning:\n","\n",- "β No relevant context found in the knowledge graph.\n"+ "invalid value encountered in divide\n",+ "\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\n",+ "β No relevant context found.\n"]}],"source": [- "from semantica.context import ContextRetriever\n",+ "from semantica.context import AgentContext\n","from semantica.reasoning import InferenceEngine\n","\n",- "# 1. Initialize Retriever & Engine\n",- "retriever = ContextRetriever(\n",- " vector_store=vs, \n",- " knowledge_graph=kg_final, \n",+ "# 1. Initialize AgentContext (Hybrid Retrieval)\n",+ "ctx = AgentContext(\n",+ " vector_store=vs,\n",+ " knowledge_graph=kg_final,\n"," use_graph_expansion=True,\n"," max_expansion_hops=2\n",")\n",@@ -416,34 +357,37 @@"engine = InferenceEngine(provider=\"groq\", model=\"llama-3.1-70b-versatile\")\n","\n","# 2. Interactive Query Loop\n",- "user_query = input(\"Enter your skincare query: \") or \"What ingredients synergize with Retinol to prevent irritation?\"\n",+ "user_query = \"What ingredients synergize with Retinol to prevent irritation?\"\n","\n","print(f\"\\nπ Processing Multi-Hop Query: {user_query}\")\n","\n",- "# Retrieve multi-hop context\n",- "context_results = retriever.retrieve(user_query, max_results=2)\n",+ "# Retrieve multi-hop context using AgentContext\n",+ "context_results = ctx.retrieve(user_query, max_results=2)\n","\n","if context_results:\n",- " # Show the reasoning path (Connected Entities)\n",- " if context_results[0].related_entities:\n",- " print(\"\\n--- π§ MULTI-HOP CONTEXT DISCOVERED ---\")\n",- " for ent in context_results[0].related_entities[:5]:\n",- " print(f\"- {ent['content']} ({ent['type']}) via {ent['relationship']}\")\n",+ " print(\"\\n--- π§ MULTI-HOP CONTEXT DISCOVERED ---\")\n",+ " for res in context_results:\n",+ " print(f\"Recall: {res['content'][:120]}...\")\n",+ " if res.get('related_entities'):\n",+ " print(f\" π Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\n","\n"," # Generate Final Answer\n",- " context_text = \" \".join([r.content for r in context_results])\n",+ " context_text = \" \".join([r['content'] for r in context_results])\n"," prompt = f\"Based on the following context, answer the user query accurately.\\nContext: {context_text}\\nQuery: {user_query}\"\n",- " final_answer = engine.generate(prompt)\n",- "\n",- " print(\"\\n--- β¨ FINAL GRAPHRAG ANSWER ---\")\n",- " print(final_answer)\n",+ " \n",+ " try:\n",+ " final_answer = engine.generate(prompt)\n",+ " print(\"\\n--- β¨ FINAL GRAPHRAG ANSWER ---\")\n",+ " print(final_answer)\n",+ " except Exception as e:\n",+ " print(f\"\\n(LLM synthesis skipped: {e})\")\n","else:\n",- " print(\"\\nβ No relevant context found in the knowledge graph.\")"+ " print(\"\\nβ No relevant context found.\")"]},{"cell_type": "markdown",- "id": "e7c15dd7",+ "id": "5c478f11","metadata": {},"source": ["## π Visualizing the Intelligence\n",@@ -452,19 +396,10 @@},{"cell_type": "code",- "execution_count": 7,- "id": "4b52490d",+ "execution_count": 14,+ "id": "851383de","metadata": {},- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\umap\\__init__.py:9: ImportWarning: Tensorflow not installed; ParametricUMAP will be unavailable\n",- " warn(\n"- ]- }- ],+ "outputs": [],"source": ["from semantica.visualization import KGVisualizer\n","import matplotlib.pyplot as plt\n",@@ -473,6 +408,14 @@"viz.visualize_network(kg_final, layout=\"spring\", title=\"Skincare Ingredient Intelligence Graph\")\n","plt.show()"]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a45000b6",+ "metadata": {},+ "outputs": [],+ "source": []}],"metadata": {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 eac58515..5c39fa1d 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@@ -2,276 +2,398 @@"cells": [{"cell_type": "markdown",- "id": "de0a7591",+ "id": "ff1ebefe","metadata": {},"source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)\n",+ "# RAG vs. GraphRAG: Investigative Intelligence Comparison\n","\n",- "# RAG vs. GraphRAG: Final Answer Comparison\n",- "This notebook demonstrates the difference in final answers generated by **Standard Vector RAG** and **Semantica GraphRAG** for a complex multi-hop query. We use **FalkorDB** as our high-performance graph backend.\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",- "### FalkorDB Setup\n",- "To use the persistent graph store, you can start a FalkorDB instance using the provided Docker Compose file:\n",- "```bash\n",- "docker compose up -d\n",- "```"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "ca782326",- "metadata": {},- "outputs": [],- "source": [- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu falkordb sentence-transformers beautifulsoup4 requests"- ]- },- {- "cell_type": "markdown",- "id": "889e971d",- "metadata": {},- "source": [- "## 1. Environment & Store Initialization\n",- "We set up our **Vector Store** using **Sentence-Transformers** for local embeddings and **FalkorDB** for persistent graph storage."+ "### 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": "init_stores",+ "execution_count": 1,+ "id": "f0f2029d","metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Note: you may need to restart the kernel to use updated packages.\n"+ ]+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"+ ]+ }+ ],"source": [- "from semantica.core import Semantica, ConfigManager\n",- "from semantica.vector_store import VectorStore\n",- "from semantica.graph_store import GraphStore\n",- "from semantica.kg import GraphBuilder\n",- "from semantica.split import TextSplitter\n",- "from semantica.normalize import TextNormalizer\n",+ "# Environment Setup\n","import os\n",+ "import sys\n","\n",- "# 1. Core Semantica & Vector Store\n",- "import getpass\n",- "if \"GROQ_API_KEY\" not in os.environ:\n",- " os.environ[\"GROQ_API_KEY\"] = getpass.getpass(\"Enter your Groq API Key: \")\n",- "\n",- "config_dict = {\n",- " \"embedding\": {\"provider\": \"sentence_transformers\", \"model\": \"all-MiniLM-L6-v2\"},\n",- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",- " \"inference\": {\"provider\": \"groq\", \"model\": \"llama-3.1-70b-versatile\"}\n",- "}\n",- "config = ConfigManager().load_from_dict(config_dict)\n",- "v_core = Semantica(config=config)\n",- "vs = VectorStore(backend=\"faiss\", dimension=384)\n",- "\n",- "# 2. FalkorDB Persistent Graph Store\n",- "graph_store = GraphStore(\n",- " backend=\"falkordb\",\n",- " host=\"localhost\",\n",- " port=6379,\n",- " graph_name=\"intelligence_graph\"\n",- ")\n",- "\n",- "try:\n",- " graph_store.connect()\n",- " print(\"Successfully connected to FalkorDB backend.\")\n",- " use_persistent = True\n",- "except Exception as e:\n",- " print(f\"FalkorDB connection failed: {e}. Falling back to in-memory mode.\")\n",- " use_persistent = False\n",+ "# Ensure Groq API Key is set if using Groq\n",+ "os.environ['GROQ_API_KEY'] = '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'\n","\n",- "# 3. Graph Builder with Persistence Support\n",- "gb = GraphBuilder(merge_entities=True, resolve_conflicts=True, graph_store=graph_store if use_persistent else None)\n",- "splitter = TextSplitter(method=\"recursive\", chunk_size=800, chunk_overlap=100)\n",- "normalizer = TextNormalizer()"+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu"]},{"cell_type": "markdown",- "id": "ingestion_section",+ "id": "094fb9f7","metadata": {},"source": [- "## 2. Real-Time Intelligence Ingestion\n",- "We pull live data from global news feeds to build our knowledge base."+ "## 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": "ingest_data",+ "execution_count": 2,+ "id": "1da63d04","metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/html": [+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>GraphBuilder</td><td>-</td><td>21.67s</td></tr><tr><td>π</td><td>Semantica is building</td><td>π§ kg</td><td>EntityResolver</td><td>-</td><td>11.02s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.03s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>EntityMerger</td><td>-</td><td>0.07s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.03s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is processing</td><td>π context</td><td>ContextRetriever</td><td>-</td><td>0.04s</td></tr><tr><td>β </td><td>Semantica is processing</td><td>π context</td><td>AgentMemory</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is embedding</td><td>πΎ embeddings</td><td>TextEmbedder</td><td>-</td><td>0.00s</td></tr></table></div>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {},+ "output_type": "display_data"+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Intelligence Knowledge Hub Populated with 27 reports.\n"+ ]+ }+ ],"source": [- "from semantica.ingest import FeedIngestor, WebIngestor\n",+ "from semantica.ingest import WebIngestor, FeedIngestor\n",+ "from semantica.normalize import TextNormalizer\n","\n",+ "normalizer = TextNormalizer()\n","all_content = []\n","\n",- "# 1. RSS Feed Ingestion\n",+ "# 1. Global News Feeds (RSS) - Using more robust and accessible feeds\n","feeds = [\n"," \"http://feeds.bbci.co.uk/news/world/rss.xml\",\n"," \"https://www.aljazeera.com/xml/rss/all.xml\",\n",- " \"https://rss.nytimes.com/services/xml/rss/nyt/World.xml\",\n",- " \"https://www.theguardian.com/world/rss\",\n",- " \"https://techcrunch.com/feed/\",\n",- " \"https://www.wired.com/feed/rss\",\n",- " \"https://feeds.feedburner.com/venturebeat/SBNp\",\n",- " \"https://www.kdnuggets.com/feed\",\n",- " \"https://towardsdatascience.com/feed\",\n",- " \"https://feeds.arstechnica.com/arstechnica/index\"\n",+ " \"https://news.google.com/rss/search?q=site%3Areuters.com&hl=en-US&gl=US&ceid=US%3Aen\" # Reuters workaround\n","]\n",- "\n","feed_ingestor = FeedIngestor()\n","for f in feeds:\n"," try:\n",- " print(f\"Ingesting from Feed: {f}\")\n"," data = feed_ingestor.ingest_feed(f)\n",- " for item in data.items[:5]:\n",+ " items = data.items[:10]\n",+ " for item in items:\n",+ " # Fallback chain: content -> description -> title\n"," text = item.content or item.description or item.title\n",- " if text: all_content.append(text)\n",+ " if text:\n",+ " all_content.append(text)\n"," except Exception as e:\n",- " print(f\"Failed to ingest {f}: {e}\")\n",+ " print(f\"Warning: Failed to ingest feed {f}: {e}\")\n","\n",- "# 2. Web Ingestion (Direct URL Scraping)\n",- "web_ingestor = WebIngestor()\n",+ "# 2. Strategic Overviews (Web) - Using pages with more permissive robots.txt\n","web_urls = [\n",- " \"https://en.wikipedia.org/wiki/Artificial_intelligence\",\n",- " \"https://en.wikipedia.org/wiki/Knowledge_graph\"\n",+ " \"https://www.cia.gov/the-world-factbook/\",\n",+ " \"https://www.cfr.org/backgrounders\" \n","]\n",- "\n",+ "web_ingestor = WebIngestor()\n","for url in web_urls:\n"," try:\n",- " print(f\"Ingesting from Web: {url}\")\n"," content = web_ingestor.ingest_url(url)\n",- " if content and content.text:\n",+ " if content.text:\n"," all_content.append(content.text)\n"," except Exception as e:\n",- " print(f\"Failed to ingest {url}: {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",- "chunks = []\n",- "for doc in clean_docs:\n",- " chunks.extend(splitter.split(doc))\n",+ "# Clean and normalize\n",+ "clean_docs = [normalizer.normalize(text) for text in all_content if len(text) > 100] # Increased threshold for higher quality\n",+ "print(f\"Intelligence Knowledge Hub Populated with {len(clean_docs)} reports.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "1404d812",+ "metadata": {},+ "source": [+ "## 2. Standard Vector RAG Pipeline\n",+ "Linear retrieval via semantic embedding overlap."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "f5759b37",+ "metadata": {},+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n",+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Vector RAG ready with 10 encoded fragments.\n"+ ]+ }+ ],+ "source": [+ "from semantica.core import Semantica\n",+ "from semantica.split import EntityAwareChunker\n",+ "from semantica.vector_store import VectorStore\n","\n",- "# Populate Stores\n",- "print(f\"Processing {len(chunks)} chunks...\")\n",- "embeddings = v_core.embedding_generator.generate_embeddings([str(c) for c in chunks])\n",- "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks])\n",+ "# v_core = Semantica(embedding={\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"})\n",+ "# Using framework defaults which utilize the core.config\n",+ "v_core = Semantica()\n",+ "\n",+ "# Using EntityAwareChunker for better intelligence-domain chunking\n",+ "splitter = EntityAwareChunker(chunk_size=600, chunk_overlap=50)\n",+ "chunks = []\n",+ "for doc in clean_docs[:10]:\n",+ " chunks.extend(splitter.chunk(doc))\n","\n",- "# Build Knowledge Graph (Automatically persists to FalkorDB if connected)\n",- "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:30]])\n",+ "# Initialize Vector Store\n",+ "vs = VectorStore(backend=\"faiss\", dimension=1536) \n",+ "# Use the core embedding generator\n",+ "embeddings = v_core.embedding_generator.generate_embeddings([str(c.text) for c in chunks[:15]])\n",+ "vs.store_vectors(vectors=embeddings, metadata=[{\"content\": str(c.text)} for c in chunks[:15]])\n","\n",- "print(f\"\\nSetup complete. Data ingested and Knowledge Graph built.\")"+ "print(f\"Vector RAG ready with {len(chunks[:15])} encoded fragments.\")"]},{"cell_type": "markdown",- "id": "refinement_intro",+ "id": "08ce3d9c","metadata": {},"source": [- "## 3. Knowledge Refinement\n",- "Deduplicating entities and resolving conflicting information for higher accuracy."+ "## 3. High-Fidelity GraphRAG Pipeline\n",+ "Synthesizing entities and relationships from fragmented reports."]},{"cell_type": "code",- "execution_count": null,- "id": "refinement_code",+ "execution_count": 4,+ "id": "6b1829f5","metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "GraphRAG Synthesis Complete: 21 entities, 0 relationships.\n"+ ]+ }+ ],"source": [- "from semantica.deduplication import DuplicateDetector, EntityMerger\n",- "from semantica.conflicts import ConflictDetector, ConflictResolver\n",+ "from semantica.kg import GraphBuilder\n",+ "from semantica.context import AgentContext\n","\n",- "# 1. Entity Resolution\n",- "detector = DuplicateDetector(threshold=0.85)\n",- "merger = EntityMerger()\n",- "duplicates = detector.detect_duplicates(kg['entities'])\n",- "kg_refined = merger.merge_entities(kg, duplicates)\n",+ "gb = GraphBuilder(merge_entities=True)\n",+ "# We process a subset for demonstration\n",+ "kg_data = gb.build(sources=[{\"text\": str(c.text)} for c in chunks[:10]])\n","\n",- "# 2. Conflict Detection\n",- "conflict_detector = ConflictDetector()\n",- "conflicts = conflict_detector.detect_value_conflicts(kg_refined['entities'], property_name=\"name\")\n",- "if conflicts:\n",- " print(f\"Detected {len(conflicts)} property conflicts.\")\n",- " resolver = ConflictResolver()\n",- " results = resolver.resolve_conflicts(conflicts, strategy=\"voting\")\n",- " print(f\"Successfully resolved {len(results)} conflicts.\")\n",+ "# Initialize AgentContext for GraphRAG\n",+ "# This combines Vector Store and Knowledge Graph for hybrid retrieval\n",+ "ctx = AgentContext(\n",+ " vector_store=vs,\n",+ " knowledge_graph=kg_data,\n",+ " use_graph_expansion=True,\n",+ " max_expansion_hops=2\n",+ ")\n","\n",- "print(\"Knowledge Graph Refined.\")"+ "print(f\"GraphRAG Synthesis Complete: {len(kg_data.get('entities', []))} entities, {len(kg_data.get('relationships', []))} relationships.\")"]},{"cell_type": "markdown",- "id": "rag_section",+ "id": "3992e7d9","metadata": {},"source": [- "## 4. Standard Vector RAG Answer\n",- "Standard RAG retrieves isolated chunks based on semantic similarity."+ "## 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": "rag_code",+ "execution_count": 5,+ "id": "6a9bf3e4","metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "--- Standard Vector Recall ---\n"+ ]+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\numpy\\linalg\\linalg.py:2582: RuntimeWarning: invalid value encountered in multiply\n",+ " s = (x.conj() * x).real\n",+ "C:\\Users\\Mohd Kaif\\semantica\\semantica\\vector_store\\vector_store.py:498: RuntimeWarning: invalid value encountered in divide\n",+ " similarities = np.dot(vectors, query_vector) / (vector_norms * query_norm)\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Recall: No content... (Score: nan)\n",+ "Recall: No content... (Score: nan)\n",+ "Recall: No content... (Score: nan)\n",+ "\n",+ "--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\n",+ "\n",+ "(LLM synthesis skipped: 'InferenceEngine' object has no attribute 'generate')\n"+ ]+ }+ ],"source": [- "q_vec = v_core.embedding_generator.generate_embeddings(query)\n",- "v_res = vs.search_vectors(q_vec, k=1)\n",+ "from semantica.reasoning import InferenceEngine\n",+ "\n",+ "user_query = \"Identify high-risk security escalations and their regional implications.\"\n","\n",- "print(\"--- VECTOR RAG FINAL ANSWER ---\")\n",- "if v_res:\n",- " print(v_res[0]['metadata']['text'])\n",- "else:\n",- " print(\"No relevant context found.\")"+ "print(\"--- Standard Vector Recall ---\")\n",+ "# Direct search in vector store\n",+ "v_res = vs.search(user_query, limit=3)\n",+ "for r in v_res:\n",+ " text = r.get('metadata', {}).get('content', 'No content')\n",+ " print(f\"Recall: {text[:120]}... (Score: {r['score']:.4f})\")\n",+ "\n",+ "print(\"\\n--- Graph Intelligence Reasoning (Hybrid Retrieval) ---\")\n",+ "# Use AgentContext for multi-hop retrieval\n",+ "graph_res = ctx.retrieve(user_query, max_results=3)\n",+ "\n",+ "for i, res in enumerate(graph_res):\n",+ " print(f\"Result {i+1}: {res['content'][:120]}...\")\n",+ " if res.get('related_entities'):\n",+ " print(f\" π Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}\")\n",+ "\n",+ "# Final Synthesis using InferenceEngine\n",+ "engine = InferenceEngine(provider=\"groq\", model=\"llama-3.1-70b-versatile\")\n",+ "context_text = \"\\n\".join([r['content'] for r in graph_res])\n",+ "prompt = f\"Based on the following intelligence context, {user_query}\\n\\nContext:\\n{context_text}\"\n",+ "\n",+ "# Note: Requires GROQ_API_KEY\n",+ "try:\n",+ " answer = engine.generate(prompt)\n",+ " print(\"\\n--- β¨ FINAL INTELLIGENCE SYNTHESIS ---\")\n",+ " print(answer)\n",+ "except Exception as e:\n",+ " print(f\"\\n(LLM synthesis skipped: {e})\")\n"]},{"cell_type": "markdown",- "id": "graphrag_section",+ "id": "f6d37cc8","metadata": {},"source": [- "## 5. Semantica GraphRAG Answer\n",- "GraphRAG uses multi-hop traversal via **FalkorDB** to synthesize a connected answer."+ "## 5. Visualizing the Intelligence Landscape\n",+ "Seeing the 'Bridges' between disconnected events."]},{"cell_type": "code",- "execution_count": null,- "id": "graphrag_code",+ "execution_count": 6,+ "id": "854a8576","metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\umap\\__init__.py:9: ImportWarning: Tensorflow not installed; ParametricUMAP will be unavailable\n",+ " warn(\n"+ ]+ },+ {+ "ename": "NameError",+ "evalue": "name 'kg' is not defined",+ "output_type": "error",+ "traceback": [+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",+ "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",+ "Cell \u001b[1;32mIn[6], line 6\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mmatplotlib\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mpyplot\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mplt\u001b[39;00m\n\u001b[0;32m 4\u001b[0m viz \u001b[38;5;241m=\u001b[39m KGVisualizer()\n\u001b[0;32m 5\u001b[0m viz\u001b[38;5;241m.\u001b[39mvisualize_network(\n\u001b[1;32m----> 6\u001b[0m \u001b[43mkg\u001b[49m,\n\u001b[0;32m 7\u001b[0m output\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mstatic\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 8\u001b[0m title\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIntelligence Connectivity Map\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 9\u001b[0m )\n\u001b[0;32m 10\u001b[0m plt\u001b[38;5;241m.\u001b[39mshow()\n",+ "\u001b[1;31mNameError\u001b[0m: name 'kg' is not defined"+ ]+ }+ ],"source": [- "from semantica.context import ContextRetriever\n",+ "from semantica.visualization import KGVisualizer\n",+ "import matplotlib.pyplot as plt\n","\n",- "# Use the persistent GraphStore if available, otherwise fallback to the in-memory dict\n",- "kg_backend = graph_store if use_persistent else kg_refined\n",- "\n",- "retriever = ContextRetriever(\n",- " vector_store=vs, \n",- " knowledge_graph=kg_backend, \n",- " use_graph_expansion=True,\n",- " max_expansion_hops=2\n",+ "viz = KGVisualizer()\n",+ "viz.visualize_network(\n",+ " kg,\n",+ " output=\"static\",\n",+ " title=\"Intelligence Connectivity Map\"\n",")\n",- "\n",- "g_res = retriever.retrieve(query, max_results=1)\n",- "\n",- "print(\"--- GRAPHRAG FINAL ANSWER ---\")\n",- "if g_res:\n",- " print(g_res[0].content)\n",- " if g_res[0].related_entities:\n",- " print(\"\\n--- CONNECTED ENTITIES DISCOVERED ---\")\n",- " for ent in g_res[0].related_entities[:5]:\n",- " print(f\"- {ent['content']} ({ent['type']}) via {ent['relationship']}\")\n",- "else:\n",- " print(\"No relevant multi-hop context found.\")"+ "plt.show()"]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "14f46e4d",+ "metadata": {},+ "outputs": [],+ "source": []}],"metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },"language_info": {- "name": "python"+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.9"}},"nbformat": 4,diff --git a/restructure_utf8.py b/restructure_utf8.pyindex ed2d0147..95266595 100644--- a/restructure_utf8.py+++ b/restructure_utf8.py@@ -81,22 +81,24 @@ nb.cells.append(nbf.v4.new_markdown_cell("""## 2. Standard Vector RAG PipelineLinear 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.split import EntityAwareChunkerfrom semantica.vector_store import VectorStore# v_core = Semantica(embedding={"provider": "openai", "model": "text-embedding-3-small"})# Using framework defaults which utilize the core.configv_core = Semantica()-splitter = TextSplitter(method="recursive", chunk_size=600, chunk_overlap=50)+# Using EntityAwareChunker for better intelligence-domain chunking+splitter = EntityAwareChunker(chunk_size=600, chunk_overlap=50)chunks = []for doc in clean_docs[:10]:- chunks.extend(splitter.split(doc))+ chunks.extend(splitter.chunk(doc))# Initialize Vector Storevs = 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]])+# Use the core embedding generator+embeddings = v_core.embedding_generator.generate_embeddings([str(c.text) for c in chunks[:15]])+vs.store_vectors(vectors=embeddings, metadata=[{"content": str(c.text)} for c in chunks[:15]])print(f"Vector RAG ready with {len(chunks[:15])} encoded fragments.")"""))@@ -105,13 +107,22 @@ nb.cells.append(nbf.v4.new_markdown_cell("""## 3. High-Fidelity GraphRAG PipelinSynthesizing entities and relationships from fragmented reports."""))nb.cells.append(nbf.v4.new_code_cell("""from semantica.kg import GraphBuilder-from semantica.deduplication import DuplicateDetector+from semantica.context import AgentContextgb = GraphBuilder(merge_entities=True)# We process a subset for demonstration-kg = gb.build(sources=[{"text": str(c)} for c in chunks[:10]])+kg_data = gb.build(sources=[{"text": str(c.text)} for c in chunks[:10]])++# Initialize AgentContext for GraphRAG+# This combines Vector Store and Knowledge Graph for hybrid retrieval+ctx = AgentContext(+ vector_store=vs,+ knowledge_graph=kg_data,+ use_graph_expansion=True,+ max_expansion_hops=2+)-print(f"GraphRAG Synthesis Complete: {len(kg.get('entities', []))} entities, {len(kg.get('relationships', []))} relationships.")"""))+print(f"GraphRAG Synthesis Complete: {len(kg_data.get('entities', []))} entities, {len(kg_data.get('relationships', []))} relationships.")"""))# Phase 4: Comparative Testnb.cells.append(nbf.v4.new_markdown_cell("""## 4. The Intelligence Challenge: Multi-Hop Inference@@ -121,35 +132,37 @@ Query: **"Identify high-risk security escalations and their regional implicationnb.cells.append(nbf.v4.new_code_cell("""from semantica.reasoning import InferenceEngine+user_query = "Identify high-risk security escalations and their regional implications."+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)+# Direct search in vector store+v_res = vs.search(user_query, limit=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}")"""))+ text = r.get('metadata', {}).get('content', 'No content')+ print(f"Recall: {text[:120]}... (Score: {r['score']:.4f})")++print("\\n--- Graph Intelligence Reasoning (Hybrid Retrieval) ---")+# Use AgentContext for multi-hop retrieval+graph_res = ctx.retrieve(user_query, max_results=3)++for i, res in enumerate(graph_res):+ print(f"Result {i+1}: {res['content'][:120]}...")+ if res.get('related_entities'):+ print(f" π Multi-hop connections: {[e['content'] for e in res['related_entities'][:3]]}")++# Final Synthesis using InferenceEngine+engine = InferenceEngine(provider="groq", model="llama-3.1-70b-versatile")+context_text = "\\n".join([r['content'] for r in graph_res])+prompt = f"Based on the following intelligence context, {user_query}\\n\\nContext:\\n{context_text}"++# Note: Requires GROQ_API_KEY+try:+ answer = engine.generate(prompt)+ print("\\n--- β¨ FINAL INTELLIGENCE SYNTHESIS ---")+ print(answer)+except Exception as e:+ print(f"\\n(LLM synthesis skipped: {e})")+"""))# Phase 5: Visualizationnb.cells.append(nbf.v4.new_markdown_cell("""## 5. Visualizing the Intelligence Landscapediff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex 970c4222..a95b4c57 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -290,6 +290,24 @@ class VectorStore:self.logger.info(f"Loaded vector store from {path}")+ def search(self, query: str, limit: int = 10, **options) -> List[Dict[str, Any]]:+ """+ Search for similar vectors by query string.++ Args:+ query: Query string+ limit: Number of results+ **options: Additional options++ Returns:+ List of results with scores+ """+ # Generate embedding for query+ query_vector = self.embed([query])[0]++ # Search by vector+ return self.search_vectors(query_vector=query_vector, k=limit, **options)+def search_vectors(self, query_vector: np.ndarray, k: int = 10, **options) -> List[Dict[str, Any]]: