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
docs(cookbook): make notebook 08 a real rerunnable end-to-end workflow
taoche5c366c6b7ea9
diff --git a/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb b/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynbindex f159efb6..65074f87 100644--- a/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb+++ b/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb@@ -10,7 +10,7 @@"\n","## Overview\n","\n",- "This notebook walks you through creating your first knowledge graph from a simple document. You'll learn the complete end-to-end workflow from ingesting a file to visualizing the resulting knowledge graph.\n",+ "This notebook walks you through creating your first knowledge graph from a simple document. You'll learn the complete end-to-end workflow from ingesting a file to visualizing the resulting knowledge graph β and every step consumes the real output of the step before it.\n","\n","> [!TIP]\n","> This is the perfect starting point if you are new to Semantica. No prior knowledge of knowledge graphs is required!\n",@@ -19,10 +19,10 @@"\n","### π― Learning Objectives\n","\n",- "- **Understand the Workflow**: Learn the `File β Parse β Extract β Graph` pipeline\n",+ "- **Understand the Workflow**: Learn the `File β Parse β Extract β Graph β Visualize` pipeline\n","- **Ingest Data**: Load documents using `FileIngestor`\n","- **Parse Content**: Extract text using `DocumentParser`\n",- "- **Extract Knowledge**: Identify entities using `NERExtractor`\n",+ "- **Extract Knowledge**: Identify entities and relations using `NERExtractor` and `RelationExtractor`\n","- **Build Graph**: Construct a graph using `GraphBuilder`\n","- **Visualize**: See your graph come to life with `KGVisualizer`\n","\n",@@ -40,71 +40,65 @@"\n","## π Simple End-to-End Workflow\n","\n",- "The complete workflow consists of four main steps:\n",+ "The complete workflow consists of five main steps:\n","\n","1. **π₯ Ingest** - Load data from files or other sources\n","2. **π Parse** - Extract and structure content from documents\n","3. **βοΈ Extract** - Identify entities and relationships\n","4. **πΈοΈ Build Graph** - Construct the knowledge graph\n",+ "5. **π Visualize** - Render and analyze the graph\n","\n",- "Each step is demonstrated in the code cells below.\n",+ "Each step is demonstrated in the code cells below, and each cell can be rerun on its own: the sample file is only removed by the optional cleanup cell at the very end.\n","\n","> [!TIP]\n","> **Alternative: Using Semantica Framework**\n",- "> \n",+ ">\n","> For a simpler, high-level approach, you can use the `Semantica` framework class which orchestrates all these steps:\n",- "> \n",+ ">\n","> ```python\n","> from semantica.core import Semantica\n",- "> \n",+ ">\n","> framework = Semantica()\n","> framework.initialize()\n",- "> \n",+ ">\n","> result = framework.build_knowledge_base(\n","> sources=[\"sample_document.txt\"],\n","> embeddings=True,\n","> graph=True\n","> )\n",- "> \n",+ ">\n","> framework.shutdown()\n","> ```\n",- "> \n",+ ">\n","> This notebook shows the step-by-step approach for learning. See [Core Module Usage Guide](../../../semantica/core/core_usage.md) for more details.\n","\n","---\n","\n","## π Step 1: Ingest a File\n","\n",- "In this step, we'll use `FileIngestor` to load a document. The ingestor supports various file formats including PDF, DOCX, TXT, and more.\n"+ "In this step, we'll use `FileIngestor` to load a document. The ingestor supports various file formats including PDF, DOCX, TXT, and more. Writing the sample file is idempotent, so this cell can be rerun at any time.\n"]},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": [- "!pip install semantica"- ]+ "!pip install semantica\n"+ ],+ "execution_count": null,+ "outputs": []},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": [- "from semantica.ingest import FileIngestor\n","from pathlib import Path\n","\n",- "# Initialize the ingestor\n",- "ingestor = FileIngestor()\n",+ "from semantica.ingest import FileIngestor\n","\n",- "# Create a sample document for demonstration\n",- "sample_text = \"\"\"\n",- "Apple Inc. is a technology company founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.\n",- "The company is headquartered in Cupertino, California.\n",- "Tim Cook is the current CEO of Apple Inc.\n",- "Apple designs and manufactures consumer electronics, software, and online services.\n",+ "sample_text = \"\"\"Apple Inc. is headquartered in Cupertino, California.\n",+ "In 1976, Steve Jobs founded Apple Inc.\n",+ "Tim Cook is the CEO of Apple Inc.\n","\"\"\"\n","\n","sample_file = Path(\"sample_document.txt\")\n",@@ -113,12 +107,14 @@"print(f\"File: {sample_file}\")\n","print(f\"Content length: {len(sample_text)} characters\")\n","\n",- "# Ingest the file\n",+ "ingestor = FileIngestor()\n","file_object = ingestor.ingest_file(sample_file, read_content=True)\n","print(f\" File name: {file_object.name}\")\n","print(f\" File type: {file_object.file_type}\")\n",- "print(f\" Content available: {file_object.content is not None}\")\n"- ]+ "print(f\" Content available: {file_object.content is not None}\")"+ ],+ "execution_count": null,+ "outputs": []},{"cell_type": "markdown",@@ -126,64 +122,58 @@"source": ["## π Step 2: Parse the Document\n","\n",- "After ingesting the file, we need to parse it to extract the text content. The `DocumentParser` handles various file formats and extracts structured content.\n"+ "After ingesting the file, we need to parse it to extract the text content. `DocumentParser.parse_document()` returns the extracted text under the `\"text\"` key.\n"]},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": ["from semantica.parse import DocumentParser\n","\n","parser = DocumentParser()\n",- "# Parse the document to extract text\n","parsed_document = parser.parse_document(str(sample_file))\n",- "parsed_content = parsed_document.get(\"content\", \"\")\n",- "print(f\" Parsed content length: {len(parsed_content) if parsed_content else 0} characters\")\n",- "print(f\" Preview: {parsed_content[:200] if parsed_content else 'N/A'}...\")"- ]+ "\n",+ "parsed_content = parsed_document.get(\"text\", \"\")\n",+ "assert parsed_content.strip(), \"Parsing produced no text β check the input file\"\n",+ "\n",+ "print(f\"Parsed content length: {len(parsed_content)} characters\")\n",+ "print(f\"Preview: {parsed_content[:120]}...\")"+ ],+ "execution_count": null,+ "outputs": []},{"cell_type": "markdown","metadata": {},"source": [- "## βοΈ Step 3: Extract Entities\n",- "\n",- "Now we'll extract entities from the parsed text using Named Entity Recognition (NER). This identifies people, organizations, locations, dates, and other entities in the text.\n",+ "## βοΈ Step 3: Extract Entities and Relations\n","\n",- "> [!NOTE]\n",- "> In a real scenario, you would use `NERExtractor` with an LLM or model backend. Here we simulate the output for demonstration purposes.\n"+ "Now we'll extract entities and relations from the parsed text. `NERExtractor` identifies people, organizations, locations and dates; `RelationExtractor` finds relations between those mentions. Both operate on the *parsed content from Step 2* β not on a copy of the raw string.\n"]},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": [- "from semantica.semantic_extract import NamedEntityRecognizer, NERExtractor\n",- "\n",- "ner = NamedEntityRecognizer()\n",- "extractor = NERExtractor()\n",- "\n",- "print(f\"\\nText: {parsed_content[:100]}...\")\n",- "\n",- "# Simulated extraction results\n",- "expected_entities = [\n",- " {\"text\": \"Apple Inc.\", \"type\": \"Organization\", \"start\": 0, \"end\": 10},\n",- " {\"text\": \"Steve Jobs\", \"type\": \"Person\", \"start\": 50, \"end\": 60},\n",- " {\"text\": \"Steve Wozniak\", \"type\": \"Person\", \"start\": 62, \"end\": 75},\n",- " {\"text\": \"Ronald Wayne\", \"type\": \"Person\", \"start\": 81, \"end\": 93},\n",- " {\"text\": \"1976\", \"type\": \"Date\", \"start\": 97, \"end\": 101},\n",- " {\"text\": \"Cupertino, California\", \"type\": \"Location\", \"start\": 130, \"end\": 151},\n",- " {\"text\": \"Tim Cook\", \"type\": \"Person\", \"start\": 153, \"end\": 161},\n",- "]\n",- "\n",- "for entity in expected_entities:\n",- " print(f\" - {entity['text']} ({entity['type']})\")\n"- ]+ "from semantica.semantic_extract import NERExtractor, RelationExtractor\n",+ "\n",+ "ner_extractor = NERExtractor()\n",+ "relation_extractor = RelationExtractor()\n",+ "\n",+ "mentions = ner_extractor.extract(parsed_content)\n",+ "relations = relation_extractor.extract(parsed_content, mentions)\n",+ "\n",+ "print(\"Entity mentions:\")\n",+ "for mention in mentions:\n",+ " print(f\" {mention.text!r:<13} {mention.label:<7} span=[{mention.start_char}:{mention.end_char}]\")\n",+ "\n",+ "print(\"\\nExtracted relations:\")\n",+ "for rel in relations:\n",+ " print(f\" {rel.subject.text!r} --{rel.predicate}--> {rel.object.text!r}\")"+ ],+ "execution_count": null,+ "outputs": []},{"cell_type": "markdown",@@ -191,58 +181,68 @@"source": ["## πΈοΈ Step 4: Build the Knowledge Graph\n","\n",- "Using the extracted entities and relationships, we'll construct a knowledge graph. The graph represents entities as nodes and relationships as edges.\n"+ "Using the extracted entities and relations, we construct a knowledge graph with `GraphBuilder`. Every mention gets a graph ID, and each edge is built from the actual `Relation.subject` / `Relation.object` endpoints.\n",+ "\n",+ "> [!NOTE]\n",+ "> The graph will contain one node per *mention*, so `Apple Inc.` appears three times. Merging duplicate mentions into one canonical entity is covered in [07_Building_Knowledge_Graphs.ipynb](./07_Building_Knowledge_Graphs.ipynb).\n"]},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": ["from semantica.kg import GraphBuilder\n",- "import networkx as nx\n","\n",- "builder = GraphBuilder()\n",+ "entities = []\n",+ "span_to_id = {}\n",+ "for i, mention in enumerate(mentions, 1):\n",+ " graph_id = f\"e{i}\"\n",+ " span_to_id[(mention.start_char, mention.end_char)] = graph_id\n",+ " entities.append({\n",+ " \"id\": graph_id,\n",+ " \"type\": mention.label,\n",+ " \"name\": mention.text,\n",+ " \"properties\": {},\n",+ " })\n",+ "\n",+ "relationships = []\n",+ "for rel in relations:\n",+ " source_id = span_to_id.get((rel.subject.start_char, rel.subject.end_char))\n",+ " target_id = span_to_id.get((rel.object.start_char, rel.object.end_char))\n",+ " if source_id is None or target_id is None:\n",+ " print(f\"Skipping relation with unmapped endpoint: \"\n",+ " f\"{rel.subject.text!r} --{rel.predicate}--> {rel.object.text!r}\")\n",+ " continue\n",+ " relationships.append({\n",+ " \"source\": source_id,\n",+ " \"target\": target_id,\n",+ " \"type\": rel.predicate,\n",+ " \"properties\": {},\n",+ " })\n","\n",- "# Prepare data for graph construction\n",- "entities_data = [\n",- " {\"id\": f\"entity_{i}\", \"name\": entity[\"text\"], \"type\": entity[\"type\"]}\n",- " for i, entity in enumerate(expected_entities)\n",- "]\n",- "\n",- "relationships_data = [\n",- " {\"source\": \"entity_0\", \"target\": \"entity_1\", \"type\": \"founded_by\"},\n",- " {\"source\": \"entity_0\", \"target\": \"entity_2\", \"type\": \"founded_by\"},\n",- " {\"source\": \"entity_0\", \"target\": \"entity_3\", \"type\": \"founded_by\"},\n",- " {\"source\": \"entity_0\", \"target\": \"entity_4\", \"type\": \"founded_in\"},\n",- " {\"source\": \"entity_0\", \"target\": \"entity_5\", \"type\": \"located_in\"},\n",- " {\"source\": \"entity_6\", \"target\": \"entity_0\", \"type\": \"ceo_of\"},\n",- "]\n",- "\n",- "# Build the graph using NetworkX\n",- "kg = nx.DiGraph()\n",- "\n",- "for entity in entities_data:\n",- " kg.add_node(entity[\"id\"], name=entity[\"name\"], type=entity[\"type\"])\n",- "\n",- "for rel in relationships_data:\n",- " source_name = entities_data[int(rel[\"source\"].split(\"_\")[1])][\"name\"]\n",- " target_name = entities_data[int(rel[\"target\"].split(\"_\")[1])][\"name\"]\n",- " kg.add_edge(rel[\"source\"], rel[\"target\"], type=rel[\"type\"])\n",- "\n",- "print(f\" Nodes (entities): {len(kg.nodes)}\")\n",- "print(f\" Edges (relationships): {len(kg.edges)}\")\n",- "\n",- "for node_id in kg.nodes():\n",- " node_data = kg.nodes[node_id]\n",- " print(f\" Node: {node_data['name']} ({node_data['type']})\")\n",- "\n",- "for source, target, data in kg.edges(data=True):\n",- " source_name = kg.nodes[source]['name']\n",- " target_name = kg.nodes[target]['name']\n",- " print(f\" {source_name} --[{data['type']}]--> {target_name}\")\n"- ]+ "builder = GraphBuilder()\n",+ "knowledge_graph = builder.build({\"entities\": entities, \"relationships\": relationships})\n",+ "\n",+ "id_to_name = {entity[\"id\"]: entity[\"name\"] for entity in entities}\n",+ "\n",+ "print(f\"Nodes (entities): {len(knowledge_graph['entities'])}\")\n",+ "for entity in knowledge_graph[\"entities\"]:\n",+ " print(f\" {entity['id']}: {entity['name']} ({entity['type']})\")\n",+ "\n",+ "print(f\"\\nEdges (relationships): {len(knowledge_graph['relationships'])}\")\n",+ "for relationship in knowledge_graph[\"relationships\"]:\n",+ " print(f\" {id_to_name[relationship['source']]} \"\n",+ " f\"--{relationship['type']}--> {id_to_name[relationship['target']]}\")\n",+ "\n",+ "edges = {\n",+ " (id_to_name[r[\"source\"]], r[\"type\"], id_to_name[r[\"target\"]])\n",+ " for r in knowledge_graph[\"relationships\"]\n",+ "}\n",+ "assert (\"Apple Inc.\", \"located_in\", \"Cupertino\") in edges\n",+ "assert (\"Tim Cook\", \"works_for\", \"Apple Inc.\") in edges"+ ],+ "execution_count": null,+ "outputs": []},{"cell_type": "markdown",@@ -250,49 +250,81 @@"source": ["## π Step 5: Visualize and Analyze\n","\n",- "Finally, we'll visualize the knowledge graph and analyze its structure. This helps you understand the relationships and entities in your data.\n"+ "Finally, we render the knowledge graph with `KGVisualizer` and look at its structure. `visualize_network()` accepts the `GraphBuilder` result directly and can save an interactive HTML file.\n"]},{"cell_type": "code",- "execution_count": null,"metadata": {},- "outputs": [],"source": ["from semantica.visualization import KGVisualizer\n","\n","visualizer = KGVisualizer()\n",- "\n",- "print(f\" Total entities: {len(kg.nodes)}\")\n",- "print(f\" Total relationships: {len(kg.edges)}\")\n",+ "fig = visualizer.visualize_network(\n",+ " knowledge_graph, output=\"html\", file_path=\"knowledge_graph.html\"\n",+ ")\n",+ "print(\"Saved interactive visualization to knowledge_graph.html\")\n","\n","entity_types = {}\n",- "for node_id in kg.nodes():\n",- " entity_type = kg.nodes[node_id]['type']\n",- " entity_types[entity_type] = entity_types.get(entity_type, 0) + 1\n",+ "for entity in knowledge_graph[\"entities\"]:\n",+ " entity_types[entity[\"type\"]] = entity_types.get(entity[\"type\"], 0) + 1\n","\n",- "for etype, count in entity_types.items():\n",- " print(f\" - {etype}: {count}\")\n",+ "print(\"\\nEntities by type:\")\n",+ "for entity_type, count in sorted(entity_types.items()):\n",+ " print(f\" - {entity_type}: {count}\")\n","\n",- "rel_types = {}\n",- "for _, _, data in kg.edges(data=True):\n",- " rel_type = data.get('type', 'unknown')\n",- " rel_types[rel_type] = rel_types.get(rel_type, 0) + 1\n",+ "relationship_types = {}\n",+ "for relationship in knowledge_graph[\"relationships\"]:\n",+ " relationship_types[relationship[\"type\"]] = (\n",+ " relationship_types.get(relationship[\"type\"], 0) + 1\n",+ " )\n","\n",- "for rtype, count in rel_types.items():\n",- " print(f\" - {rtype}: {count}\")\n",+ "print(\"\\nRelationships by type:\")\n",+ "for relationship_type, count in sorted(relationship_types.items()):\n",+ " print(f\" - {relationship_type}: {count}\")\n","\n",- "# Cleanup\n",- "if sample_file.exists():\n",- " sample_file.unlink()\n"+ "fig"+ ],+ "execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## π§Ή Optional: Clean Up\n",+ "\n",+ "Run this cell only when you are done with the notebook. Earlier cells read `sample_document.txt`, so they stay rerunnable until you delete it here.\n"]},{"cell_type": "code",+ "metadata": {},+ "source": [+ "for path in [sample_file, Path(\"knowledge_graph.html\")]:\n",+ " if path.exists():\n",+ " path.unlink()\n",+ " print(f\"Removed {path}\")"+ ],"execution_count": null,+ "outputs": []+ },+ {+ "cell_type": "markdown","metadata": {},- "outputs": [],- "source": []+ "source": [+ "## Summary\n",+ "\n",+ "You've built your first knowledge graph, end to end:\n",+ "\n",+ "- **FileIngestor** loaded the sample document\n",+ "- **DocumentParser** returned its text under the `\"text\"` key\n",+ "- **NERExtractor** / **RelationExtractor** produced real mentions and relations from that text\n",+ "- **GraphBuilder** turned them into a graph whose edges come from the actual relation endpoints\n",+ "- **KGVisualizer** rendered the result as an interactive network\n",+ "\n",+ "Next: merge duplicate mentions with `EntityResolver` in [07_Building_Knowledge_Graphs.ipynb](./07_Building_Knowledge_Graphs.ipynb), or explore graph metrics in the Graph Analytics notebook.\n"+ ]}],"metadata": {