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 Welcome notebook: validate pipeline, refine docs, and ensure full module coverage
KaifAhmad1c178b8deade0
diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynbindex b148995a..0dc746bd 100644--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb@@ -86,45 +86,73 @@"cell_type": "markdown","metadata": {},"source": [- "## Key Modules at a Glance\n",- "\n",- "Below is a conceptual overview of the core modules. Later cells show a small end-to-end example that stitches several of them together.\n",- "\n",- "- **Ingest**\n",- " - Components: `FileIngestor`, `WebIngestor`, `FeedIngestor`, `StreamIngestor`, `DBIngestor`, `EmailIngestor`, `RepoIngestor`, `MCPIngestor`\n",- " - Responsibility: Bring data from many sources into the pipeline\n",- "\n",- "- **Parse**\n",- " - Components: `DocumentParser`, format-specific parsers like `PDFParser`, `HTMLParser`, `JSONParser`, `ExcelParser`\n",- " - Responsibility: Turn raw content into structured document objects\n",- "\n",- "- **Normalize**\n",- " - Components: `TextNormalizer`, `TextCleaner`, `EntityNormalizer`, `DateNormalizer`, `NumberNormalizer`\n",- " - Responsibility: Clean text, standardize entities and values, prepare for extraction\n",- "\n",- "- **Semantic extract**\n",- " - Components: `NERExtractor`, `RelationExtractor`, `SemanticAnalyzer`, `SemanticNetworkExtractor`\n",- " - Responsibility: Identify entities and relationships that will become nodes and edges in the graph\n",- "\n",- "- **Knowledge graph (KG)**\n",- " - Components: `GraphBuilder`, `GraphAnalyzer`, `GraphValidator`, `EntityResolver`, `ConflictDetector`\n",- " - Responsibility: Build, analyze, and validate the knowledge graph\n",- "\n",- "- **Embeddings and vector store**\n",- " - Components: `EmbeddingGenerator`, `VectorStore`, `HybridSearch`\n",- " - Responsibility: Generate vector representations and enable semantic search\n",- "\n",- "- **Graph store**\n",- " - Components: `GraphStore`, adapters for backends like Neo4j or FalkorDB\n",- " - Responsibility: Persist and query graphs in external databases\n",- "\n",- "- **Reasoning and ontology**\n",- " - Components: `InferenceEngine`, `RuleManager`, `OntologyGenerator`, `OntologyValidator`\n",- " - Responsibility: Apply rules, infer new facts, and maintain formal ontologies\n",- "\n",- "- **Visualization**\n",- " - Components: `KGVisualizer`, `EmbeddingVisualizer`, `QualityVisualizer`, `AnalyticsVisualizer`\n",- " - Responsibility: Inspect, debug, and present graphs, embeddings, and quality metrics"+ "## 🧩 Semantica Modules Reference\n",+ "\n",+ "Semantica is modular by design. Here is a comprehensive guide to all available modules, grouped by functionality.\n",+ "\n",+ "### 📥 Ingestion & Parsing\n",+ "Modules that handle raw data input and structure.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`ingest`** | **Data Ingestion**<br>Connects to data sources. | • File, Web, Feed, Stream ingestion<br>• DB, Email, Repo, MCP support |\n",+ "| **`parse`** | **Document Parsing**<br>Parses raw content into structures. | • PDF, HTML, JSON, CSV, Excel<br>• Image & Code parsing |\n",+ "\n",+ "### ⚙️ Data Processing\n",+ "Modules that clean, normalize, and split data.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`normalize`** | **Data Normalization**<br>Cleans and standardizes text. | • Text cleaning & Language detection<br>• Entity, Date, Number normalization |\n",+ "| **`split`** | **Chunking**<br>Splits documents for RAG. | • Recursive character splitting<br>• Semantic & Token-based splitting |\n",+ "\n",+ "### 🧠 Extraction & Enrichment\n",+ "Modules that extract meaning, structure, and vectors from raw data.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`semantic_extract`** | **Information Extraction**<br>Extracts entities and relations. | • NER & Relation Extraction<br>• Event & Semantic Network detection |\n",+ "| **`context`** | **Agent Memory**<br>Manages state for AI agents. | • Long-term memory & history<br>• Context graph & RAG integration |\n",+ "\n",+ "### 🕸️ Knowledge Graph Core\n",+ "Modules for building, refining, and resolving knowledge graphs.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`kg`** | **Graph Construction**<br>Builds and analyzes graphs. | • Graph Building & Analysis<br>• Validation & Entity Resolution |\n",+ "| **`conflicts`** | **Conflict Resolution**<br>Resolves data contradictions. | • Source reliability scoring<br>• Truth discovery algorithms |\n",+ "| **`deduplication`** | **Entity Resolution**<br>Merges duplicate entities. | • Similarity-based blocking<br>• Clustering & Canonicalization |\n",+ "\n",+ "### 💾 Storage & Retrieval\n",+ "Modules for persisting and querying data.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`embeddings`** | **Vector Embeddings**<br>Generates semantic vectors. | • Text & Graph embeddings<br>• Multi-provider support (OpenAI, etc.) |\n",+ "| **`vector_store`** | **Vector Database**<br>Stores and searches vectors. | • Similarity search & Filtering<br>• Hybrid search (Vector + Keyword) |\n",+ "| **`graph_store`** | **Property Graph Store**<br>Persists graph data. | • Neo4j, FalkorDB adapters<br>• Cypher query support |\n",+ "| **`triplet_store`** | **RDF Store**<br>Persists semantic triples. | • SPARQL endpoints<br>• BlazeGraph, Jena, Virtuoso adapters |\n",+ "\n",+ "### 🔎 Reasoning & Analysis\n",+ "Modules for deriving new knowledge and evaluating quality.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`reasoning`** | **Inference Engine**<br>Derives new facts via rules. | • Datalog/Rule-based inference<br>• Forward/Backward chaining |\n",+ "| **`ontology`** | **Ontology Management**<br>Manages schema and definitions. | • Ontology generation from data<br>• Validation & Evolution |\n",+ "| **`visualization`** | **Visual Analytics**<br>Visualizes graphs and metrics. | • 2D/3D Graph visualization<br>• Interactive plots & dashboards |\n",+ "| **`evals`** | **Evaluation**<br>Benchmarks pipeline quality. | • RAG & Graph quality metrics<br>• Ground truth comparison |\n",+ "\n",+ "### 🛠️ Orchestration & Utils\n",+ "Modules for managing the framework and workflows.\n",+ "\n",+ "| Module | Description | Key Capabilities |\n",+ "| :--- | :--- | :--- |\n",+ "| **`core`** | **Framework Core**<br>Main entry point and config. | • Lifecycle management<br>• Plugin system & Configuration |\n",+ "| **`pipeline`** | **Workflow Orchestration**<br>Manages complex flows. | • DAG execution & Retries<br>• Error handling & Observability |\n",+ "| **`seed`** | **Data Seeding**<br>Initializes knowledge bases. | • Taxonomy & Ontology seeding<br>• Reference data loading |\n",+ "| **`export`** | **Data Export**<br>Exports data to files. | • JSON, CSV, RDF, GEXF export<br>• Report generation |\n",+ "| **`utils`** | **Utilities**<br>Common helper functions. | • Logging, Async, Hashing<br>• Text processing helpers |"]},{@@ -227,9 +255,9 @@"cell_type": "markdown","metadata": {},"source": [- "## Quick Start: Build a Tiny Knowledge Base\n",+ "## Setup: Create Sample Data\n","\n",- "The simplest way to use Semantica is the high-level `build` helper. It ingests data, runs a default pipeline, and returns a dictionary that includes the knowledge graph, embeddings, metadata, and statistics."+ "First, let's create a small sample document to work with."]},{@@ -238,7 +266,6 @@"metadata": {},"outputs": [],"source": [- "from semantica import build\n","from pathlib import Path\n","\n","docs_dir = Path(\"welcome_docs\")\n",@@ -249,9 +276,7 @@" \" Cupertino, California.\"\n",")\n","text_path.write_text(text_content, encoding=\"utf-8\")\n",- "\n",- "result = build(str(docs_dir), embeddings=False, graph=True)\n",- "sorted(result.keys())"+ "print(f\"Created sample document at {text_path}\")"]},{@@ -445,22 +470,6 @@"print(\"Graph exported to knowledge_graph.json\")"]},- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Other Specialized Modules\n",- "\n",- "Semantica includes many other specialized modules for advanced use cases:\n",- "\n",- "- **Context**: Manages agent memory, conversation history, and context graphs for AI agents.\n",- "- **Conflicts**: Detects and resolves conflicting information from different sources (e.g., different birth dates for the same person).\n",- "- **Deduplication**: Identifies and merges duplicate entities (e.g., \"Steve Jobs\" vs \"Stephen Jobs\").\n",- "- **Pipeline**: Orchestrates complex, multi-step workflows with retries and error handling.\n",- "- **Triplet Store**: Adapters for enterprise RDF stores like BlazeGraph, Jena, or Virtuoso.\n",- "- **Graph Store**: Adapters for Property Graph databases like Neo4j or FalkorDB."- ]- },{"cell_type": "markdown","metadata": {},diff --git a/semantica/__init__.py b/semantica/__init__.pyindex 5d1c7d7a..63603f5a 100644--- a/semantica/__init__.py+++ b/semantica/__init__.py@@ -191,63 +191,7 @@ class _SemanticaModules:# Create singleton instance for module access_modules = _SemanticaModules()-# Singleton Semantica instance for module-level build()-_semantica_instance: Optional[Semantica] = None---def _get_semantica_instance(- config: Optional[Union[Config, Dict[str, Any]]] = None, **kwargs-) -> Semantica:- """Get or create singleton Semantica instance."""- global _semantica_instance- if _semantica_instance is None:- _semantica_instance = Semantica(config=config, **kwargs)- return _semantica_instance---def build(- sources: Union[List[Union[str, Path]], str, Path],- config: Optional[Union[Config, Dict[str, Any]]] = None,- **kwargs,-) -> Dict[str, Any]:- """- Build knowledge base from data sources (module-level convenience function).-- This is a user-friendly wrapper around Semantica.build_knowledge_base()- that handles initialization automatically.-- Args:- sources: Data source(s) - can be a single path/URL or list of paths/URLs- config: Optional configuration object or dict- **kwargs: Additional processing options:- - embeddings: Whether to generate embeddings (default: True)- - graph: Whether to build knowledge graph (default: True)- - normalize: Whether to normalize data (default: True)- - pipeline: Custom pipeline configuration- - fail_fast: Whether to fail on first error (default: False)-- Returns:- Dictionary containing:- - knowledge_graph: Knowledge graph data- - embeddings: Embedding vectors- - metadata: Processing metadata- - statistics: Processing statistics- - results: Processing results-- Examples:- >>> from semantica import build- >>> result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)- >>> print(result["statistics"])- """- # Normalize sources to list- if isinstance(sources, (str, Path)):- sources = [sources]-- # Get or create Semantica instance- semantica = _get_semantica_instance(config=config, **kwargs)-- # Build knowledge base (auto-initializes if needed)- return semantica.build_knowledge_base(sources, **kwargs)+__all__ = [diff --git a/semantica/core/__init__.py b/semantica/core/__init__.pyindex 85315b3b..03a7e1c7 100644--- a/semantica/core/__init__.py+++ b/semantica/core/__init__.py@@ -86,72 +86,4 @@ __all__ = ["get_status","get_orchestration_method","list_available_methods",- # Convenience- "build",-]--def build(- sources: Union[str, List[Union[str, Path]]],- extract_entities: bool = True,- extract_relations: bool = True,- embeddings: bool = True,- graph: bool = True,- **options,-) -> Dict[str, Any]:- """- Build knowledge base from sources (module-level convenience function).-- This is a user-friendly wrapper that performs comprehensive knowledge base- construction including entity extraction, relation extraction, embeddings,- and knowledge graph building.-- Args:- sources: Input source or list of sources (files, URLs, streams)- extract_entities: Whether to extract named entities (default: True)- extract_relations: Whether to extract relationships (default: True)- embeddings: Whether to generate embeddings (default: True)- graph: Whether to build knowledge graph (default: True)- **options: Additional processing options-- Returns:- Dictionary containing:- - knowledge_graph: Knowledge graph data- - embeddings: Embedding vectors- - results: Processing results- - statistics: Processing statistics- - metadata: Processing metadata-- Examples:- >>> import semantica- >>> result = semantica.core.build(- ... sources=["doc1.pdf", "doc2.docx"],- ... extract_entities=True,- ... extract_relations=True,- ... embeddings=True,- ... graph=True- ... )- >>> print(f"Processed {result['statistics']['sources_processed']} sources")- """- # Normalize sources to list- if isinstance(sources, str):- sources = [sources]-- # Build pipeline configuration from options- pipeline_config = options.get("pipeline", {})- if extract_entities or extract_relations:- pipeline_config.setdefault("extract", {})- if extract_entities:- pipeline_config["extract"]["entities"] = True- if extract_relations:- pipeline_config["extract"]["relations"] = True-- # Build knowledge base- return build_knowledge_base(- sources=sources,- method=options.get("method", "default"),- embeddings=embeddings,- graph=graph,- pipeline=pipeline_config,- **{k: v for k, v in options.items() if k not in ["pipeline", "method"]},- )diff --git a/tests/core/test_core_integration.py b/tests/core/test_core_integration.pyindex 1fa85c90..33658531 100644--- a/tests/core/test_core_integration.py+++ b/tests/core/test_core_integration.py@@ -1,6 +1,5 @@import pytest-from semantica import build as module_buildfrom semantica.core import Semanticafrom semantica.core.methods import (initialize_framework,@@ -88,11 +87,4 @@ def test_core_methods_build_knowledge_base_end_to_end(tmp_path):assert result["results"][0]["success"] is True-def test_module_build_end_to_end_default_pipeline(tmp_path):- source_path = tmp_path / "sample_e2e_module_build.txt"- source_path.write_text("Sample data for end-to-end test.")- result = module_build(str(source_path), embeddings=False, graph=False)- stats = result["statistics"]- assert stats["sources_processed"] == 1- assert len(result["results"]) == 1- assert result["results"][0]["success"] is True+