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
Update GraphRAG notebook: Replace MCP with File/Repo ingestion and fix parsing logic
KaifAhmad1640315e28739
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex 365141b1..1eb7dc99 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -14,7 +14,7 @@"\n","**Key Features:**\n","\n",- "- **Real-World Data**: Uses actual data sources via MCP servers, web scraping, and RSS feeds (NO mock data)\n",+ "- **Real-World Data**: Uses actual data sources via Local Files, GitHub Repositories, Web Scraping, and RSS Feeds (NO mock data)\n","- **Complete Pipeline**: From data ingestion to LLM-powered question answering\n","- **Hybrid Retrieval**: Combines vector similarity search with knowledge graph traversal\n","- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",@@ -32,7 +32,7 @@"\n","### Pipeline Overview\n","\n",- "**Real-World Data Sources (MCP/Web/Feeds) \u2192 Parse \u2192 Extract Entities & Relationships \u2192 Build Knowledge Graph \u2192 Generate Embeddings \u2192 Vector Store \u2192 Hybrid Search \u2192 Context Retrieval \u2192 GraphRAG Query System \u2192 LLM Integration \u2192 Answer Generation**\n",+ "- **Real-World Data**: Uses actual data sources via Local Files, GitHub Repositories, Web Scraping, and RSS Feeds (NO mock data)\n","\n","---\n","\n",@@ -110,13 +110,14 @@"source": ["## Step 2: Ingest Real-World Data from Multiple Sources\n","\n",- "1. **MCP Servers** (Primary): Connect to real MCP servers providing news feeds, documentation, APIs\n",- "2. **Web Sources**: Scrape real web content from news sites and documentation\n",- "3. **RSS Feeds**: Ingest real RSS/Atom feeds from news sources\n",+ "1. **Local Files**: Ingest local documents and text files\n",+ "2. **Repositories**: Ingest code and documentation from GitHub repositories\n",+ "3. **Web Sources**: Scrape real web content from news sites and documentation\n",+ "4. **RSS Feeds**: Ingest real RSS/Atom feeds from news sources\n","\n",- "### 2.1: Connect to MCP Servers\n",+ "### 2.1: Ingest Local Files and Repositories\n","\n",- "Connect to real MCP servers via URL. MCP servers can provide resources (databases, files) and tools (APIs, queries).\n",+ "Ingest data from local file systems and remote code repositories.\n","\n"]},@@ -126,98 +127,50 @@"metadata": {},"outputs": [],"source": [- "from semantica.ingest import MCPIngestor\n",- "\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "# 1. Connect to Real MCP Server (e.g., Brave Search)\n",- "# Note: You must run the MCP server locally first. \n",- "# Command: npx @modelcontextprotocol/server-brave-search\n",- "# Then use the appropriate connection method. Since we cannot easily start it here,\n",- "# we will wrap it in a try-except block to gracefully handle its absence.\n",- "try:\n",- " # Note: Replace with your actual MCP server URL if running\n",- " # Standard python MCP servers or FastMCP often expose an SSE endpoint\n",- " mcp_ingestor.connect(\"brave_search_mcp\", url=\"http://localhost:8000/sse\") \n",- " print(\"Successfully connected to Brave Search MCP\")\n",- "except Exception as e:\n",- " print(f\"Note: Could not connect to local MCP server: {e}\")\n",- " print(\"Instructions: To use MCP, run a compatible server locally (e.g., npx @modelcontextprotocol/server-brave-search)\")\n",- " print(\"Continuing with Web and RSS sources only...\")\n",- "\n",- "connected_servers = mcp_ingestor.get_connected_servers()\n",- "print(f\"\\nConnected MCP Servers: {len(connected_servers)}\")\n",- "for server_name in connected_servers:\n",- " print(f\" - {server_name}\")\n",- "\n",- "if connected_servers:\n",- " for server_name in connected_servers:\n",- " try:\n",- " resources = mcp_ingestor.list_available_resources(server_name)\n",- " tools = mcp_ingestor.list_available_tools(server_name)\n",- " print(f\"\\n{server_name}:\")\n",- " print(f\" Resources: {len(resources)}\")\n",- " print(f\" Tools: {len(tools)}\")\n",- " if tools:\n",- " print(f\" Available Tools: {[t.name for t in tools]}\")\n",- " except Exception as e:\n",- " print(f\"Error inspecting {server_name}: {e}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### 2.2: Ingest Data from MCP Servers\n",- "\n",- "Ingest real data from MCP server resources and tools.\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, FeedIngestor\n",+ "from semantica.ingest import FileIngestor, RepoIngestor, WebIngestor, FeedIngestor\n",+ "import os\n","\n","all_documents = []\n","\n",- "# 1. Ingest via MCP Tools (e.g. Web Search)\n",- "if \"brave_search_mcp\" in connected_servers:\n",- " try:\n",- " print(f\"\\nPerforming Web Search via Brave MCP...\")\n",- " # Search for recent relevant topics\n",- " search_results = mcp_ingestor.ingest_tool_output(\n",- " \"brave_search_mcp\", \n",- " tool_name=\"brave_web_search\",\n",- " arguments={\"query\": \"latest advancements in GraphRAG and AI Agents\", \"count\": 2}\n",- " )\n",- " all_documents.append(search_results)\n",- " print(f\" Ingested search results via MCP\")\n",- " except Exception as e:\n",- " print(f\" Error using MCP tool: {e}\")\n",- "\n",- "# 2. Ingest other MCP resources\n",- "if connected_servers:\n",- " for server_name in connected_servers:\n",- " if server_name == \"brave_search_mcp\": continue # Already handled\n",- " try:\n",- " print(f\"\\nIngesting from {server_name}...\")\n",- " mcp_data = mcp_ingestor.ingest_all_resources(server_name)\n",- " \n",- " if isinstance(mcp_data, list):\n",- " all_documents.extend(mcp_data)\n",- " print(f\" Ingested {len(mcp_data)} resources\")\n",- " else:\n",- " all_documents.append(mcp_data)\n",- " print(f\" Ingested 1 resource\")\n",- " \n",- " except Exception as e:\n",- " print(f\" Error ingesting from {server_name}: {e}\")\n",+ "# 1. Ingest Local File\n",+ "file_ingestor = FileIngestor()\n",+ "# Ensure the sample directory exists\n",+ "sample_dir = os.path.join(os.getcwd(), \"data\")\n",+ "sample_file = os.path.join(sample_dir, \"sample_graphrag_paper.txt\")\n",+ "\n",+ "print(f\"Ingesting local file from {sample_file}...\")\n",+ "if os.path.exists(sample_file):\n",+ " file_docs = file_ingestor.ingest_file(sample_file)\n",+ " if isinstance(file_docs, list):\n",+ " all_documents.extend(file_docs)\n",+ " print(f\" Ingested {len(file_docs)} file document(s)\")\n",+ " else:\n",+ " all_documents.append(file_docs)\n",+ " print(f\" Ingested 1 file document\")\n",+ "else:\n",+ " print(f\" Warning: Sample file not found at {sample_file}. Please ensure it exists.\")\n",+ "\n",+ "# 2. Ingest GitHub Repository\n",+ "repo_ingestor = RepoIngestor()\n",+ "repo_url = \"https://github.com/psf/requests\" # Standard library, good example\n",+ "print(f\"\\nIngesting repository {repo_url}...\")\n","\n",- "print(f\"\\nTotal documents from MCP: {len(all_documents)}\")\n"+ "try:\n",+ " # Using depth=1 and filtering for texts to keep it light\n",+ " repo_docs = repo_ingestor.ingest_repository(\n",+ " repo_url, \n",+ " max_depth=1, \n",+ " include_extensions=[\"md\", \"rst\", \"txt\"]\n",+ " )\n",+ " \n",+ " if isinstance(repo_docs, list):\n",+ " all_documents.extend(repo_docs)\n",+ " print(f\" Ingested {len(repo_docs)} repo document(s)\")\n",+ " else:\n",+ " all_documents.append(repo_docs)\n",+ " print(f\" Ingested 1 repo document\")\n",+ "except Exception as e:\n",+ " print(f\" Error ingesting repo: {e}\")\n"]},{@@ -328,24 +281,61 @@"metadata": {},"outputs": [],"source": [- "from semantica.parse import DocumentParser, MCPParser\n",+ "from semantica.parse import DocumentParser\n","\n","document_parser = DocumentParser()\n",- "mcp_parser = MCPParser()\n","\n","parsed_documents = []\n","\n",+ "print(\"Parsing documents...\")\n","for doc in all_documents:\n"," try:\n",- " if hasattr(doc, 'source') and 'mcp' in doc.source.lower():\n",- " parsed = mcp_parser.parse(doc)\n",- " else:\n",+ " # Handle different document objects\n",+ " # 1. FileObject (from FileIngestor) -> Parse using path\n",+ " if hasattr(doc, 'path') and os.path.exists(doc.path):\n",+ " parsed = document_parser.parse(doc.path)\n",+ " if isinstance(parsed, list):\n",+ " parsed_documents.extend(parsed)\n",+ " else:\n",+ " parsed_documents.append(parsed)\n",+ " \n",+ " # 2. WebContent (from WebIngestor) -> Already has text\n",+ " elif hasattr(doc, 'text') and hasattr(doc, 'url'):\n",+ " # It's already parsed content, just use it\n",+ " # Ensure it has a 'content' attribute for downstream steps\n",+ " if not hasattr(doc, 'content') and hasattr(doc, 'text'):\n",+ " doc.content = doc.text\n",+ " parsed_documents.append(doc)\n",+ " \n",+ " # 3. FeedData (from FeedIngestor) -> Has items list\n",+ " elif hasattr(doc, 'items') and isinstance(doc.items, list):\n",+ " for item in doc.items:\n",+ " # Feed items usually have .content, .description, or .summary\n",+ " # We'll normalize to .content\n",+ " if hasattr(item, 'content'):\n",+ " pass # Good\n",+ " elif hasattr(item, 'description'):\n",+ " item.content = item.description\n",+ " elif hasattr(item, 'summary'):\n",+ " item.content = item.summary\n",+ " parsed_documents.append(item)\n",+ "\n",+ " # 4. Standard path string\n",+ " elif isinstance(doc, str) and os.path.exists(doc):\n"," parsed = document_parser.parse(doc)\n",+ " if isinstance(parsed, list):\n",+ " parsed_documents.extend(parsed)\n",+ " else:\n",+ " parsed_documents.append(parsed)\n"," \n",- " if isinstance(parsed, list):\n",- " parsed_documents.extend(parsed)\n"," else:\n",- " parsed_documents.append(parsed)\n",+ " # Fallback or already a usable document object\n",+ " if hasattr(doc, 'content') or hasattr(doc, 'text'):\n",+ " if not hasattr(doc, 'content'): doc.content = doc.text\n",+ " parsed_documents.append(doc)\n",+ " else:\n",+ " print(f\"Warning: Unknown document format: {type(doc)}\")\n",+ "\n"," except Exception as e:\n"," print(f\"Error parsing document: {e}\")\n"," continue\n",diff --git a/cookbook/use_cases/advanced_rag/data/sample_graphrag_paper.txt b/cookbook/use_cases/advanced_rag/data/sample_graphrag_paper.txtnew file mode 100644index 00000000..8c4a2d52--- /dev/null+++ b/cookbook/use_cases/advanced_rag/data/sample_graphrag_paper.txt@@ -0,0 +1,13 @@+Graph Retrieval-Augmented Generation (GraphRAG): A New Era for Intelligent Search++GraphRAG is an advanced technique that combines the retrieval capabilities of vector databases with the structural reasoning of knowledge graphs. Unlike traditional RAG, which relies solely on vector similarity, GraphRAG leverages the relationships between entities to provide more contextually accurate and comprehensive answers.++Key Components:+1. Knowledge Graph: A structured representation of data where nodes represent entities and edges represent relationships.+2. Vector Search: Finds semantically similar text chunks.+3. Graph Traversal: Navigates the knowledge graph to find related entities that might not be semantically similar but are structurally relevant.++Benefits:+- Improved Context: By following relationships, the system can understand the broader context of a query.+- Multi-hop Reasoning: Can answer complex questions that require connecting multiple pieces of information.+- Reduced Hallucinations: Grounding answers in a verified knowledge structure reduces the likelihood of generating false information.