Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Enhance GraphRAG notebook: integrated all Semantica modules with real data sources
KaifAhmad1e96bd62ebfe3
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 4123d115..0ba90e52 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -1,367 +1,259 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# GraphRAG\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a **production-grade GraphRAG pipeline** using the `Semantica` framework. We go beyond simple tutorials to show how to build, analyze, and query a rich knowledge base using advanced graph algorithms and hybrid retrieval strategies.\n",- "\n",- "### π― What You Will Learn\n",- "\n",- "1. **Orchestration**: Using `Semantica` core to manage the full data lifecycle.\n",- "2. **Advanced Analysis**: Using `GraphAnalyzer`, `CentralityCalculator`, and `CommunityDetector` to understand data structure.\n",- "3. **Ontology Generation**: Automatically deriving a schema (classes & properties) from unstructured text.\n",- "4. **Hybrid Search**: Combining Vector Similarity with Graph Traversal for superior context.\n",- "\n",- "---"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# π οΈ Dependencies\n",- "!pip install -qU semantica networkx matplotlib plotly pandas"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 1. Professional Setup & Imports\n",- "\n",- "We organize imports by their functional role in the Semantica ecosystem."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "import json\n",- "import pandas as pd\n",- "\n",- "# --- Core Framework ---\n",- "from semantica.core import Semantica, ConfigManager\n",- "\n",- "# --- Knowledge Graph & Analytics ---\n",- "from semantica.kg import (\n",- " GraphBuilder, \n",- " GraphAnalyzer, \n",- " CentralityCalculator, \n",- " CommunityDetector\n",- ")\n",- "\n",- "# --- Ontology & Schema ---\n",- "from semantica.ontology import OntologyGenerator\n",- "\n",- "# --- Visualization ---\n",- "from semantica.visualization import KGVisualizer\n",- "\n",- "print(\"β Semantica Enterprise Modules Loaded.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 2. Realistic Data Simulation\n",- "\n",- "Instead of \"Hello World\", let's use a dense technical text. We'll simulate ingesting a research paper abstract on **\"Graph Neural Networks for Knowledge Graph Completion\"**. This provides rich entities (Models, Metrics, Concepts) and relationships."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "research_paper_text = \"\"\"\n",- "Title: Learning Attention-based Embeddings for Relation Prediction in Knowledge Graphs.\n",- "Abstract:\n",- "Knowledge Graphs (KGs) are collections of structured facts, often represented as triplets (head, relation, tail).\n",- "However, most real-world KGs like Freebase, DBPedia, and YAGO are incomplete.\n",- "Link Prediction is the task of inferring missing facts based on existing ones.\n",- "We propose a new model, Graph Attention Network for Knowledge Graphs (GAT-KG), which utilizes a multi-head attention mechanism.\n",- "Unlike TransE or DistMult which rely on translational assumptions, GAT-KG captures the structural information of the local neighborhood.\n",- "Our encoder aggregates messages from neighbors, assigning different attention weights to different relationships.\n",- "The decoder uses a standard ConvKB layer to score the plausibility of triplets.\n",- "We evaluate our method on standard benchmarks: FB15k-237 and WN18RR.\n",- "Results show that GAT-KG outperforms state-of-the-art baselines like RotatE and TuckER by 5% in Hits@10.\n",- "Ablation studies confirm that the attention mechanism is crucial for handling sparse graphs.\n",- "\"\"\"\n",- "\n",- "data_dir = os.path.join(os.getcwd(), \"data\")\n",- "os.makedirs(data_dir, exist_ok=True)\n",- "source_path = os.path.join(data_dir, \"gnn_research.txt\")\n",- "\n",- "with open(source_path, \"w\", encoding=\"utf-8\") as f:\n",- " f.write(research_paper_text)\n",- "\n",- "print(f\"π Research paper saved to: {source_path}\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 3. Configuration Management\n",- "\n",- "We configure the system for **precision**. \n",- "* `entity_resolution_strategy: fuzzy`: Handles minor typos (e.g., \"Conv-KB\" vs \"ConvKB\").\n",- "* `extraction`: We specify a capable LLM model to ensure we catch complex technical terms."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "config_data = {\n",- " \"project_name\": \"ResearchGraph\",\n",- " \"embedding\": {\n",- " \"provider\": \"openai\",\n",- " \"model\": \"text-embedding-3-small\"\n",- " },\n",- " \"knowledge_graph\": {\n",- " \"backend\": \"networkx\",\n",- " \"merge_entities\": True,\n",- " \"entity_resolution_strategy\": \"fuzzy\",\n",- " \"similarity_threshold\": 0.85\n",- " },\n",- " \"extraction\": {\n",- " \"model\": \"gpt-4o\",\n",- " \"temperature\": 0.0\n",- " }\n",- "}\n",- "\n",- "config = ConfigManager().load_from_dict(config_data)\n",- "semantica = Semantica(config=config)\n",- "semantica.initialize()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 4. Building the Knowledge Base\n",- "\n",- "We execute the orchestrated pipeline. This single call replaces manual parsing, cleaning, chunking, NER, RE, and embedding generation."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "print(\"π Building Knowledge Base from Research Paper...\")\n",- "\n",- "result = semantica.build_knowledge_base(\n",- " sources=[source_path],\n",- " embeddings=True,\n",- " graph=True,\n",- " normalize=True\n",- ")\n",- "\n",- "kg = result[\"knowledge_graph\"]\n",- "print(f\"\\nβ Extraction Complete.\")\n",- "print(f\"Nodes: {kg.number_of_nodes()} | Edges: {kg.number_of_edges()}\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 5. Advanced Graph Analytics\n",- "\n",- "A knowledge graph is more than just storage; it's a structure we can analyze to find insights.\n",- "\n",- "### A. Centrality (Finding Key Concepts)\n",- "Who are the \"VIPs\" in this paper? We use Degree Centrality to find the most connected entities."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calc = CentralityCalculator()\n",- "centrality_scores = centrality_calc.calculate_degree_centrality(kg)\n",- "\n",- "# Convert to DataFrame for nice display\n",- "df_centrality = pd.DataFrame(centrality_scores.get(\"rankings\", []))\n",- "if not df_centrality.empty:\n",- " print(\"π Top 5 Most Central Concepts:\")\n",- " print(df_centrality.head(5)[[\"node\", \"score\"]].to_string(index=False))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### B. Community Detection (Topic Modeling)\n",- "Can we group these entities into topics? We use the **Louvain Algorithm** to detect communities within the graph."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "detector = CommunityDetector()\n",- "communities_result = detector.detect_communities(kg, algorithm=\"louvain\")\n",- "communities = communities_result.get(\"communities\", [])\n",- "\n",- "print(f\"π Detected {len(communities)} distinct communities (topics).\")\n",- "\n",- "for i, comm in enumerate(communities[:3]): # Show first 3\n",- " print(f\"\\nGroup {i+1}: {', '.join(list(comm)[:5])}...\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 6. Ontology Generation\n",- "\n",- "One of Semantica's most powerful features is **Reverse Engineering the Schema**. We can look at the graph we just built and ask: \"What is the underlying data model?\""- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_gen = OntologyGenerator()\n",- "ontology = ontology_gen.generate_from_graph(kg)\n",- "\n",- "print(\"𧬠Inferred Ontology Classes:\")\n",- "if \"classes\" in ontology:\n",- " for cls in ontology[\"classes\"][:5]:\n",- " print(f\" - {cls.get('name')}: {cls.get('description', 'No description inferred')}\")\n",- "else:\n",- " print(\" (Ontology generation requires sufficient data volume for inference)\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 7. Hybrid GraphRAG Inference\n",- "\n",- "Finally, we use the system to answer a complex question. We simulate the logic of a Hybrid Search:\n",- "1. **Vector**: Find the relevant text chunk.\n",- "2. **Graph**: Find the *neighbors* of the key entities to understand the context (e.g., what benchmarks were used?)\n",- "3. **Synthesis**: (Conceptually) combine these for the LLM."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "query = \"What benchmarks were used to evaluate GAT-KG?\"\n",- "print(f\"β Query: '{query}'\")\n",- "\n",- "# 1. Vector Search\n",- "vector_store = semantica.vector_store\n",- "embedding_gen = semantica.embedding_generator\n",- "q_vec = embedding_gen.generate_embeddings(query, data_type=\"text\")\n",- "vec_results = vector_store.search(q_vec, k=1)\n",- "\n",- "print(\"\\nπΉ [Vector Retrieval] Found Context:\")\n",- "top_chunk = vec_results[0].get('metadata', {}).get('text', '') if vec_results else \"No match\"\n",- "print(f\" \\\"{top_chunk[:100]}...\\\"\")\n",- "\n",- "# 2. Graph Traversal\n",- "print(\"\\nπΈ [Graph Retrieval] Exploring Neighborhoods:\")\n",- "# Find 'GAT-KG' in the graph and see what it connects to\n",- "target_node = None\n",- "for node in kg.nodes():\n",- " if \"GAT-KG\" in str(node):\n",- " target_node = node\n",- " break\n",- "\n",- "if target_node:\n",- " neighbors = list(kg[target_node])\n",- " print(f\" Entity '{target_node}' is connected to:\")\n",- " for n in neighbors:\n",- " relation = kg[target_node][n].get('type', 'related_to')\n",- " print(f\" --[{relation}]--> {n}\")\n",- "else:\n",- " print(\" (Entity 'GAT-KG' not explicitly found in graph nodes)\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 8. Visualization\n",- "\n",- "We visualize the final graph structure."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "viz = KGVisualizer()\n",- "\n",- "import matplotlib.pyplot as plt\n",- "import networkx as nx\n",- "\n",- "plt.figure(figsize=(14, 10))\n",- "pos = nx.spring_layout(kg, k=0.8, seed=42)\n",- "\n",- "# Draw with more style\n",- "nx.draw_networkx_nodes(kg, pos, node_size=1500, node_color=\"#6a0dad\", alpha=0.8) # Semantica Purple\n",- "nx.draw_networkx_edges(kg, pos, width=1.5, alpha=0.4, edge_color=\"gray\", arrows=True)\n",- "nx.draw_networkx_labels(kg, pos, font_size=9, font_color=\"white\", font_weight=\"bold\")\n",- "\n",- "edge_labels = nx.get_edge_attributes(kg, 'type')\n",- "nx.draw_networkx_edge_labels(kg, pos, edge_labels=edge_labels, font_size=7)\n",- "\n",- "plt.title(\"Research Paper Knowledge Graph\", fontsize=20)\n",- "plt.axis('off')\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.11.0"- }- },- "nbformat": 4,- "nbformat_minor": 2-}+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# End-to-End Advanced GraphRAG with Semantica\n",+ "\n",+ "## Overview\n",+ "\n",+ "This notebook provides a comprehensive, \"production-grade\" walkthrough of the **Semantica** framework. We will build a complete **GraphRAG** (Graph-Restricted Retrieval Augmented Generation) pipeline using diverse real-world data sources.\n",+ "\n",+ "### π Key Modules Used\n",+ "\n",+ "* **`semantica.ingest`**: Ingestion from Web, RSS, and Git.\n",+ "* **`semantica.normalize`**: Cleaning and standardizing raw text.\n",+ "* **`semantica.split`**: Semantic document chunking.\n",+ "* **`semantica.kg`**: KG construction and graph analytics.\n",+ "* **`semantica.vector_store`**: Vector similarity search.\n",+ "* **`semantica.reasoning`**: Advanced graph-based inference.\n",+ "* **`semantica.visualization`**: Interactive and static KG viz.\n",+ "* **`semantica.export`**: Data persistence and sharing.\n",+ "\n",+ "### π― Objective\n",+ "\n",+ "Build a queryable knowledge base about **Python Development & AI News** by aggregating data from:\n",+ "1. **Web**: Python.org\n",+ "2. **RSS**: BBC Technology News\n",+ "3. **Repo**: The requests library"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Installation & Setup\n",+ "!pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu tiktoken"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 1. Core Configuration\n",+ "\n",+ "We start by initializing the global `Semantica` configuration."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\n",+ "from semantica.core import Semantica, ConfigManager\n",+ "\n",+ "config = {\n",+ " \"project_name\": \"PythonAI_FullPipeline\",\n",+ " \"embedding\": {\"provider\": \"openai\", \"model\": \"text-embedding-3-small\"},\n",+ " \"extraction\": {\"model\": \"gpt-4o-mini\", \"temperature\": 0.0},\n",+ " \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 1536}\n",+ "}\n",+ "\n",+ "sem = Semantica(config=ConfigManager().load_from_dict(config))\n",+ "print(\"β Semantica Core Initialized.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 2. Ingestion & Normalization\n",+ "\n",+ "Fetching real-world data and cleaning it immediately using the `normalize` module."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.ingest import WebIngestor, FeedIngestor, ingest\n",+ "from semantica.normalize import TextNormalizer\n",+ "\n",+ "normalizer = TextNormalizer()\n",+ "\n",+ "# π Fetch Data\n",+ "web_docs = WebIngestor().ingest(\"https://www.python.org/about/\", method=\"url\")\n",+ "feed_docs = FeedIngestor().ingest(\"http://feeds.bbci.co.uk/news/technology/rss.xml\")[:3] # Sample 3\n",+ "repo_docs = ingest(\"https://raw.githubusercontent.com/psf/requests/main/README.md\", source_type=\"web\")\n",+ "\n",+ "# π§Ή Clean Data\n",+ "raw_texts = [d.content if hasattr(d, 'content') else str(d) for d in web_docs + feed_docs + repo_docs]\n",+ "clean_texts = [normalizer.normalize(t) for t in raw_texts if t]\n",+ "\n",+ "print(f\"β Ingested and Normalized {len(clean_texts)} documents.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 3. Semantic Splitting\n",+ "\n",+ "Breaking large documents into contextually aware chunks."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.split import TextSplitter\n",+ "\n",+ "splitter = TextSplitter(method=\"recursive\", chunk_size=800, chunk_overlap=150)\n",+ "chunks = []\n",+ "for text in clean_texts:\n",+ " chunks.extend(splitter.split(text))\n",+ "\n",+ "print(f\"β Generated {len(chunks)} Chunks.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 4. Knowledge Graph & Storage\n",+ "\n",+ "Building the structural (Graph) and semantic (Vector) layers."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphBuilder\n",+ "from semantica.vector_store import VectorStore\n",+ "\n",+ "# ποΈ Graph\n",+ "gb = GraphBuilder(merge_entities=True)\n",+ "kg = gb.build(sources=[{\"text\": str(c)} for c in chunks[:5]]) # Limited for demo\n",+ "\n",+ "# πΎ Vectors\n",+ "vs = VectorStore(backend=\"faiss\", dimension=1536)\n",+ "embeddings = sem.embedding_generator.generate_embeddings([str(c) for c in chunks[:5]])\n",+ "vs.store_vectors(vectors=embeddings, metadata=[{\"text\": str(c)} for c in chunks[:5]])\n",+ "\n",+ "print(f\"β KG Built ({kg.number_of_nodes()} nodes). Vector Store Populated.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 5. Graph Analytics & Viz\n",+ "\n",+ "Understanding the data through graph theory."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import CentralityCalculator\n",+ "from semantica.visualization import KGVisualizer\n",+ "\n",+ "centrality = CentralityCalculator().calculate_degree_centrality(kg)\n",+ "print(f\"π Top Node: {max(centrality, key=centrality.get)}\")\n",+ "\n",+ "KGVisualizer().visualize_network(kg, layout=\"spring\", output=\"static\")\n",+ "import matplotlib.pyplot as plt\n",+ "plt.show()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 6. Advanced Reasoning\n",+ "\n",+ "Using the `reasoning` module to perform complex multi-hop inference over the graph."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.reasoning import GraphReasoner\n",+ "\n",+ "reasoner = GraphReasoner(graph=kg)\n",+ "query = \"How does Python relate to the latest tech trends?\"\n",+ "\n",+ "# Perform multi-hop reasoning over the KG\n",+ "reasoning_result = reasoner.reason(query, depth=2)\n",+ "print(f\"π§ Reasoning Results:\\n{reasoning_result[:300]}...\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 7. Context & Export\n",+ "\n",+ "Wrapping context for an agent and exporting the final Knowledge Graph."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.context import AgentContext\n",+ "from semantica.export import GraphExporter\n",+ "\n",+ "# π€ Context\n",+ "context = AgentContext(vector_store=vs, knowledge_graph=kg)\n",+ "\n",+ "# π€ Export\n",+ "exporter = GraphExporter()\n",+ "exporter.export_to_json(kg, \"python_tech_graph.json\")\n",+ "\n",+ "print(\"β Context Ready. Knowledge Graph Exported to JSON.\")"+ ]+ }+ ],+ "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