Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs: premium redesign β€” Mintlify v4, dark/cream theme, full module coverage

KaifAhmad1946a1089c81b
diff --git a/docs/CodeExamples.md b/docs/CodeExamples.md
index a9a652ee..ea70d78a 100644
--- a/docs/CodeExamples.md
+++ b/docs/CodeExamples.md
@@ -1,4 +1,10 @@
-## πŸš€ Quick Start
+---
+title: "Code Examples"
+description: "Comprehensive code examples for all Semantica modules, processors, and integrations."
+icon: "code"
+---
+
+## Quick Start
### πŸ“¦ Installation Options
diff --git a/docs/MIGRATION_V2.md b/docs/MIGRATION_V2.md
index 5bfaf8be..413806c2 100644
--- a/docs/MIGRATION_V2.md
+++ b/docs/MIGRATION_V2.md
@@ -1,3 +1,9 @@
+---
+title: "Deduplication V2 Migration"
+description: "Migration guide for the Deduplication V2 engine with blocking_v2 and semantic_v2 strategies."
+icon: "arrows-rotate"
+---
+
## Semantica Deduplication V2: Migration & Performance Guide
Welcome to the Deduplication V2 engine!! This release specifically targets severe CI delays and production bottlenecks caused by massive knowledge graph deduplication workloads. By introducing smarter candidate generation, fast-fail prefilters, and semantic triplet canonicalization, we have reduced worst-case execution times by up to **80%**.
diff --git a/docs/architecture.md b/docs/architecture.md
index 8b73ab40..6c4d0a72 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,58 +1,86 @@
-# Architecture
+---
+title: "Architecture"
+description: "Three-layer, modular architecture designed for independent component use, clean separation of concerns, and extensibility."
+icon: "building"
+---
-Semantica is built around a three-layer, modular architecture designed for independent use of components, clean separation of concerns, and extensibility at each layer.
+Semantica is built around a three-layer modular architecture. Import only what you need β€” nothing forces a full stack.
---
-## System Overview
-
-```mermaid
-graph TB
- A[Data Ingestion Layer] --> B[Semantic Processing Layer]
- B --> C[Application Layer]
+## Three-Layer Architecture
- A1[Files Β· Web Β· APIs Β· Streams] --> A
- B1[Parse Β· Normalize Β· Extract Β· Build] --> B
- C1[GraphRAG Β· AI Agents Β· Analytics] --> C
+```text
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Layer 1: Data Ingestion β”‚
+β”‚ Files Β· Web Β· APIs Β· Databases Β· Streams β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ Layer 2: Semantic Processing β”‚
+β”‚ Parse Β· Normalize Β· Extract Β· Build Β· QA β”‚
+β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
+β”‚ Layer 3: Application β”‚
+β”‚ GraphRAG Β· AI Agents Β· Analytics Β· Export Β· Visualization β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
----
+<Tabs>
-## Three-Layer Architecture
+<Tab title="Layer 1 β€” Ingestion">
-### 1. Data Ingestion Layer
+Loads data from any source into the pipeline.
-Responsible for loading data from any source into the pipeline.
+| Source | Module | Notes |
+|--------|--------|-------|
+| PDF, DOCX, PPTX, HTML, JSON, CSV | `ingest.FileIngestor` | Supports archives, recursive scan |
+| Parquet | `ingest.ParquetIngestor` | PyArrow, Hive-style partitions (v0.5.0) |
+| XML | `ingest.XMLIngestor` | XXE-safe lxml, XSD/DTD validation (v0.5.0) |
+| Web pages | `ingest.WebIngestor` | Configurable depth, link filtering |
+| SQL / Snowflake | `ingest.DBIngestor` / `ingest.SnowflakeIngestor` | Custom SQL, schema introspection |
+| Kafka / streams | `ingest.StreamIngestor` | Real-time feed ingestion |
+| MCP | `ingest.MCPIngestor` | Model Context Protocol sources |
-- **File formats** β€” PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives
-- **Web** β€” crawl via `WebIngestor` with configurable depth
-- **Databases** β€” SQL, NoSQL, Snowflake via `DBIngestor` / `SnowflakeIngestor`
-- **Streams** β€” Kafka, real-time feeds
+</Tab>
-### 2. Semantic Processing Layer
+<Tab title="Layer 2 β€” Semantic Processing">
The core intelligence engine β€” transforms raw data into structured knowledge.
-- Document parsing and normalization
-- Entity and relationship extraction (NER, LLM-typed, rule-based)
-- Embedding generation
-- Knowledge graph construction with entity merging
-- Deduplication, conflict detection, and validation
+| Step | Module | What it does |
+|------|--------|-------------|
+| Parse | `parse.DocumentParser` / `parse.DoclingParser` | Text + layout extraction, table detection |
+| Normalize | `normalize` | Canonical forms, date/name standardization, encoding fix |
+| Extract | `semantic_extract` | NER, relation extraction, event extraction, triplets |
+| Build | `kg.GraphBuilder` | Entity merging, edge construction, graph assembly |
+| Embed | `embeddings` | Sentence-Transformers, FastEmbed, OpenAI, BGE |
+| QA | `deduplication`, `conflicts` | Duplicate detection, conflict resolution, validation |
+| Temporal | `kg.TemporalKnowledgeGraph` | `valid_from`/`valid_until`, Allen interval algebra (v0.4.0) |
-### 3. Application Layer
+</Tab>
+
+<Tab title="Layer 3 β€” Application">
Consumes the knowledge graph for downstream use cases.
-- GraphRAG β€” graph-grounded retrieval for LLMs
-- AI agent context and decision tracking
-- Multi-agent pipelines
-- Analytics, visualization, and export
+| Use Case | Module | Description |
+|----------|--------|-------------|
+| GraphRAG | `context.AgentContext` | Graph-grounded retrieval for LLMs |
+| Agent memory | `context.ContextGraph` | Persistent semantic memory across agent runs |
+| Decision tracking | `context.AgentContext` | Record, trace, and audit every agent decision |
+| Ontology Hub | `explorer` | Visual editor, SHACL Studio, alignment UI (v0.5.0) |
+| Multi-agent | `integrations.agno` | Shared context, team-level memory, KG toolkit |
+| Visualization | `visualization` | Interactive HTML graphs, embedding plots, temporal views |
+| Export | `export` | RDF, Parquet, ArangoDB AQL, OWL, CSV |
+| Reasoning | `reasoning` | Forward chaining, Rete, Datalog, SPARQL, abductive |
+
+</Tab>
+
+</Tabs>
---
## Data Flow
-```
+```text
Ingest β†’ raw data from sources
Parse β†’ structured text extraction
Normalize β†’ canonical forms, date/name standardization
@@ -69,58 +97,103 @@ Deliver β†’ GraphRAG, agents, export, visualization
| Layer | Modules |
|-------|---------|
-| **Ingestion** | `ingest`, `parse`, `split`, `normalize` |
-| **Semantic** | `semantic_extract`, `kg`, `ontology`, `reasoning` |
-| **Storage** | `embeddings`, `vector_store`, `graph_store`, `triplet_store` |
-| **Quality** | `deduplication`, `conflicts` |
-| **Context** | `context`, `provenance`, `change_management` |
-| **Output** | `export`, `visualization`, `pipeline` |
-
-For full module documentation, see the [Modules Guide](modules.md).
+| Ingestion | `ingest`, `parse`, `split`, `normalize` |
+| Semantic | `semantic_extract`, `kg`, `ontology`, `reasoning` |
+| Storage | `embeddings`, `vector_store`, `graph_store`, `triplet_store` |
+| Quality | `deduplication`, `conflicts` |
+| Context | `context`, `provenance`, `change_management` |
+| Output | `export`, `visualization`, `pipeline` |
---
## Extension Points
-### Custom Ingestor
+<CodeGroup>
-```python
+```python Custom Ingestor
from semantica.ingest import BaseIngestor
class CustomIngestor(BaseIngestor):
- def ingest(self, source):
- # Return a list of document dicts
- ...
+ def ingest(self, source: str) -> list[dict]:
+ # Return a list of document dicts with 'text', 'metadata', 'source'
+ return [{"text": "...", "metadata": {}, "source": source}]
```
-### Custom Extractor
-
-```python
+```python Custom Extractor
from semantica.semantic_extract import BaseExtractor
class CustomExtractor(BaseExtractor):
- def extract(self, text):
- # Return a list of entity dicts
- ...
+ def extract(self, text: str) -> list[dict]:
+ # Return a list of entity dicts with 'text', 'type', 'confidence'
+ return [{"text": "...", "type": "CUSTOM_TYPE", "confidence": 0.9}]
```
+```python Custom Plugin
+from semantica.core import PluginRegistry, BasePlugin
+
+class MyPlugin(BasePlugin):
+ name = "my_plugin"
+
+ def process(self, graph, config):
+ # Modify the graph in place
+ return graph
+
+PluginRegistry.register(MyPlugin)
+```
+
+</CodeGroup>
+
---
## Design Decisions
-**Modularity** β€” every component can be used standalone. Import only what you need; the framework never forces a full stack.
+<AccordionGroup>
-**Pluggability** β€” extend any layer without modifying core code. Custom ingestors, extractors, validators, and exporters all follow the same base class pattern.
+<Accordion title="Modularity β€” use only what you need" icon="puzzle-piece">
+Every component works standalone. `NERExtractor` can be used without a graph store. `VectorStore` can be used without decision tracking. The framework never forces a full stack instantiation.
+</Accordion>
-**Configuration over convention** β€” centralized config with environment variable overrides for deployment flexibility.
+<Accordion title="Pluggability β€” extend without modifying core" icon="plug">
+Custom ingestors, extractors, validators, and exporters follow the same base class pattern. Register them via `PluginRegistry` and they participate in the full pipeline with no changes to core code.
+</Accordion>
-**Provenance by default** β€” lineage tracking is built into graph construction, not bolted on. Every node traces back to a source document.
+<Accordion title="Provenance by default" icon="link">
+Lineage tracking is built into graph construction at the lowest level. Every node and edge carries a `source_id` pointing back to the originating document, extraction method, and timestamp. There is no opt-in required.
+</Accordion>
+
+<Accordion title="Configuration over convention" icon="sliders">
+Centralized `ConfigManager` with environment variable overrides. No magic defaults β€” all behavior is explicit and overridable. Suitable for multi-environment deployments.
+</Accordion>
+
+</AccordionGroup>
---
## Performance Characteristics
-- **Parallel execution** β€” `PipelineBuilder` supports configurable worker counts per stage
-- **Delta processing** β€” incremental graph updates without full recompute
-- **Streaming ingestion** β€” process large corpora without loading everything into memory
-- **Backend flexibility** β€” swap in-memory NetworkX for Neo4j/FalkorDB at scale with no API changes
+| Characteristic | Mechanism |
+|----------------|-----------|
+| **Parallel execution** | `Pipeline(workers=N)` with configurable workers per stage |
+| **Delta processing** | Incremental graph updates β€” no full recompute on new data |
+| **Streaming ingestion** | Process large corpora without loading everything into memory |
+| **Backend flexibility** | Swap in-memory NetworkX for Neo4j/FalkorDB with no API changes |
+| **Deduplication v2** | `blocking_v2`, `hybrid_v2`, `semantic_v2` β€” up to 7x faster than v1 |
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Modules" icon="cubes" href="modules">
+ Full module documentation with code examples.
+ </Card>
+ <Card title="Deep Dive" icon="microscope" href="deep-dive">
+ Internals, algorithms, and advanced extension patterns.
+ </Card>
+ <Card title="Pipeline Reference" icon="gear" href="reference/pipeline">
+ Pipeline orchestration, workers, and retry policies.
+ </Card>
+ <Card title="Core Reference" icon="network-wired" href="reference/core">
+ Framework lifecycle, plugin registry, and configuration.
+ </Card>
+</CardGroup>
diff --git a/docs/arrow_exporter.md b/docs/arrow_exporter.md
index 64437a88..fee500dd 100644
--- a/docs/arrow_exporter.md
+++ b/docs/arrow_exporter.md
@@ -1,4 +1,8 @@
-# Apache Arrow Exporter
+---
+title: "Apache Arrow Exporter"
+description: "High-performance columnar export for knowledge graphs, entities, and relationships using Apache Arrow IPC format."
+icon: "file-arrow-down"
+---
## Overview
diff --git a/docs/citation.md b/docs/citation.md
index f7b1580c..efa88a37 100644
--- a/docs/citation.md
+++ b/docs/citation.md
@@ -1,6 +1,10 @@
-# Citation
+---
+title: "Citation"
+description: "How to cite Semantica in academic papers and research."
+icon: "quote-left"
+---
-How to cite Semantica in academic papers and research.
+> Use Semantica in your research? Here's how to cite it.
---
@@ -8,32 +12,42 @@ How to cite Semantica in academic papers and research.
```bibtex
@software{semantica2026,
- title = {Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering},
- author = {Hawksight AI},
- year = {2026},
- url = {https://github.com/Hawksight-AI/semantica},
- version = {0.2.7},
- doi = {10.5281/zenodo.XXXXXXX}
+ title = {Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering},
+ author = {Hawksight AI},
+ year = {2026},
+ url = {https://github.com/Hawksight-AI/semantica},
+ version = {0.5.0},
+ doi = {10.5281/zenodo.XXXXXXX}
}
```
-### APA
-Hawksight AI. (2026). *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering* (Version 0.2.7) [Computer software]. https://github.com/Hawksight-AI/semantica
+---
+
+## APA
+
+Hawksight AI. (2026). *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering* (Version 0.5.0) \[Computer software\]. https://github.com/Hawksight-AI/semantica
+
+---
+
+## MLA
+
+Hawksight AI. *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering*. Version 0.5.0, GitHub, 2026, https://github.com/Hawksight-AI/semantica.
-### MLA
-Hawksight AI. *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering*. Version 0.2.7, GitHub, 2026, https://github.com/Hawksight-AI/semantica.
+---
-### Chicago
-Hawksight AI. *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering*. Version 0.2.7. GitHub, 2026. https://github.com/Hawksight-AI/semantica.
+## Chicago
-### IEEE
-Hawksight AI, "Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering," Version 0.2.7, GitHub, 2026. [Online]. Available: https://github.com/Hawksight-AI/semantica
+Hawksight AI. *Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering*. Version 0.5.0. GitHub, 2026. https://github.com/Hawksight-AI/semantica.
---
-## Acknowledgment
+## IEEE
-If you use Semantica in your work:
+Hawksight AI, "Semantica: An Open Source Framework for Semantic Layers and Knowledge Engineering," Version 0.5.0, GitHub, 2026. \[Online\]. Available: https://github.com/Hawksight-AI/semantica
+
+---
+
+## Acknowledgment Text
> "This work uses Semantica (Hawksight AI, 2026), an open-source framework for semantic layer construction and knowledge engineering."
@@ -41,8 +55,17 @@ If you use Semantica in your work:
## Share Your Research
-Published research using Semantica? [Let us know](https://github.com/Hawksight-AI/semantica/issues) - we may feature your work!
+Published research using Semantica? [Let us know](https://github.com/Hawksight-AI/semantica/issues) β€” we may feature your work.
---
-**License**: MIT - See [License](license.md) for details
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="License" icon="file-contract" href="license">
+ MIT License details.
+ </Card>
+ <Card title="Community" icon="users" href="community">
+ Connect with the Semantica community.
+ </Card>
+</CardGroup>
diff --git a/docs/community-projects.md b/docs/community-projects.md
index ba5cd6ed..b3e41cf2 100644
--- a/docs/community-projects.md
+++ b/docs/community-projects.md
@@ -1,20 +1,27 @@
-# Community Projects
+---
+title: "Community Projects"
+description: "Projects and integrations built by the Semantica community."
+icon: "people-group"
+---
-Projects and integrations from the Semantica community.
+> Projects and integrations from the Semantica community.
-!!! tip "Showcase Your Project"
- Have a project using Semantica? [Submit it here](https://github.com/Hawksight-AI/semantica/issues/new)
+<Tip>
+Have a project using Semantica? [Submit it on GitHub](https://github.com/Hawksight-AI/semantica/issues/new) β€” we'd love to feature it here.
+</Tip>
---
-## πŸš€ Projects Using Semantica
+## Projects Using Semantica
-**Research & Academia**
-- Academic research and scientific literature analysis
-- Biomedical analysis and drug discovery
+### Research and Academia
+
+- Academic literature analysis and citation graph construction
+- Biomedical analysis and drug discovery knowledge graphs
- Social network analysis and community detection
-**Enterprise & Industry**
+### Enterprise and Industry
+
- Business intelligence and corporate knowledge bases
- Cybersecurity and threat intelligence
- Healthcare and medical record processing
@@ -22,34 +29,19 @@ Projects and integrations from the Semantica community.
---
-## πŸ”Œ Integrations
+## Integrations
-### Vector Databases
-- Weaviate
-- Qdrant
-- FAISS
-- Milvus
+**Vector Databases** β€” Weaviate, Qdrant, FAISS, Milvus, Pinecone, pgvector
-### Graph Databases
-- Neo4j
-- FalkorDB
+**Graph Databases** β€” Neo4j, FalkorDB, Apache AGE
-### LLM Providers
-- OpenAI
-- Google Gemini
-- Groq
-- Anthropic
-- Ollama
-- HuggingFace
+**LLM Providers** β€” OpenAI, Anthropic, Groq, Google Gemini, Ollama, HuggingFace, DeepSeek, Novita AI
-### NLP Libraries
-- spaCy
-- NLTK
-- Sentence Transformers
+**NLP Libraries** β€” spaCy, NLTK, Sentence Transformers
---
-## πŸ› οΈ Community Extensions
+## Community Extensions
- Custom entity extractors for domain-specific use cases
- Specialized export formats for various industries
@@ -58,19 +50,15 @@ Projects and integrations from the Semantica community.
---
-## 🀝 How to Contribute
-
-1. **Code**: Fork, create branch, submit PR
-2. **Documentation**: Fix typos, add examples, improve clarity
-3. **Community**: Answer questions, share experiences
-4. **Testing**: Write tests, report bugs
-
-See our [Contributing Guide](https://github.com/Hawksight-AI/semantica/blob/main/CONTRIBUTING.md)
-
----
+## How to Contribute
-## πŸ“ž Resources
+See the [Contributing Guide](contributing) for full details.
-- [GitHub Repository](https://github.com/Hawksight-AI/semantica)
-- [GitHub Issues](https://github.com/Hawksight-AI/semantica/issues)
-- [Contributing Guide](https://github.com/Hawksight-AI/semantica/blob/main/CONTRIBUTING.md)
+<CardGroup cols={2}>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ Submit code, docs, or tests.
+ </Card>
+ <Card title="GitHub Issues" icon="circle-dot" href="https://github.com/Hawksight-AI/semantica/issues">
+ Report bugs or request features.
+ </Card>
+</CardGroup>
diff --git a/docs/community.md b/docs/community.md
index 5b7290bd..60615715 100644
--- a/docs/community.md
+++ b/docs/community.md
@@ -1,73 +1,76 @@
-ο»Ώ# Community
-
-**Connect with the Semantica community for support, collaboration, and learning.**
-
+---
+title: "Community"
+description: "Get help, connect with contributors, and share what you build with Semantica."
+icon: "users"
---
-## Get Help & Support
+> Connect with the Semantica community for support, collaboration, and learning.
-### GitHub Issues
-- **[Report Issues](https://github.com/Hawksight-AI/semantica/issues)** - Bug reports and feature requests
-- **[Pull Requests](https://github.com/Hawksight-AI/semantica/pulls)** - Code contributions
-- **[Discussions](https://github.com/Hawksight-AI/semantica/discussions)** - Questions and ideas
+---
-### Security Issues
-- **[Report Security](https://github.com/Hawksight-AI/semantica/security/advisories/new)** - Security vulnerabilities
+## Get Help
+
+<CardGroup cols={2}>
+ <Card title="GitHub Issues" icon="circle-dot" href="https://github.com/Hawksight-AI/semantica/issues">
+ Bug reports and feature requests.
+ </Card>
+ <Card title="GitHub Discussions" icon="comments" href="https://github.com/Hawksight-AI/semantica/discussions">
+ Questions, ideas, and community conversation.
+ </Card>
+ <Card title="Pull Requests" icon="code-pull-request" href="https://github.com/Hawksight-AI/semantica/pulls">
+ Code contributions and reviews.
+ </Card>
+ <Card title="Security Issues" icon="shield" href="https://github.com/Hawksight-AI/semantica/security/advisories/new">
+ Report vulnerabilities privately.
+ </Card>
+</CardGroup>
---
## Community Guidelines
-### Our Values
-- **Respect** - Treat everyone with kindness
-- **Inclusion** - Welcome all backgrounds and experience levels
-- **Collaboration** - Work together to build great things
-- **Learning** - Share knowledge and help others grow
+We follow the [Contributor Covenant Code of Conduct](https://github.com/Hawksight-AI/semantica/blob/main/CODE_OF_CONDUCT.md). Our community values:
-### Code of Conduct
-We follow the [Contributor Covenant Code of Conduct](https://github.com/Hawksight-AI/semantica/blob/main/CODE_OF_CONDUCT.md).
+- **Respect** β€” Treat everyone with kindness and patience
+- **Inclusion** β€” Welcome all backgrounds and experience levels
+- **Collaboration** β€” Work together toward better solutions
+- **Learning** β€” Share knowledge openly and help others grow
-### Reporting Issues
-If you experience unacceptable behavior, please:
-1. Document what happened
-2. Create an issue with "[CoC]" prefix
-3. We'll investigate and respond appropriately
+If you experience unacceptable behavior, open an issue with a `[CoC]` prefix. We investigate every report.
---
-## Contributing
+## Ways to Contribute
-### Ways to Contribute
-- **Code** - Fix bugs, add features, improve documentation
-- **Documentation** - Improve guides, fix typos, add examples
-- **Testing** - Report issues, write tests, validate fixes
-- **Community** - Help others, share knowledge, provide feedback
+- **Code** β€” Fix bugs, add features, improve performance
+- **Documentation** β€” Fix typos, improve guides, add examples
+- **Testing** β€” Report issues, write tests, validate fixes
+- **Community** β€” Answer questions, review PRs, share your work
-### Getting Started
-1. **Fork** the repository
-2. **Create** a feature branch
-3. **Make** your changes
-4. **Test** your changes
-5. **Submit** a pull request
+See the [Contributing Guide](contributing) for full details.
---
## Stay Connected
-### Follow the Project
-- **[GitHub](https://github.com/Hawksight-AI/semantica)** - Source code and releases
-- **[PyPI](https://pypi.org/project/semantica/)** - Package information and downloads
-
-### Share Your Work
-- **Blog Posts** - Write about your Semantica projects
-- **Tutorials** - Create guides and examples
-- **Projects** - Share what you've built with Semantica
+- **[GitHub](https://github.com/Hawksight-AI/semantica)** β€” Source code, releases, roadmap
+- **[PyPI](https://pypi.org/project/semantica/)** β€” Package downloads
---
-## Need Help?
-
-- **[Getting Started](getting-started.md)** - Quick start guide
-- **[FAQ](faq.md)** - Frequently asked questions
-- **[Contributing Guide](contributing.md)** - How to contribute
-- **[GitHub Issues](https://github.com/Hawksight-AI/semantica/issues)** - Ask questions
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ Step-by-step guide for submitting PRs.
+ </Card>
+ <Card title="FAQ" icon="circle-question" href="faq">
+ Common questions answered.
+ </Card>
+ <Card title="Getting Started" icon="play" href="getting-started">
+ New to Semantica? Start here.
+ </Card>
+ <Card title="Governance" icon="scale-balanced" href="governance">
+ How the project is run.
+ </Card>
+</CardGroup>
diff --git a/docs/concepts.md b/docs/concepts.md
index e40e868c..58dc0ec6 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -1,9 +1,12 @@
-# Core Concepts
-
-The fundamental ideas behind Semantica β€” explained plainly.
+---
+title: "Core Concepts"
+description: "The fundamental ideas behind Semantica β€” knowledge graphs, reasoning, provenance, and temporal intelligence explained."
+icon: "book-open"
+---
-!!! tip "New here?"
- Start with [Getting Started](getting-started.md) for hands-on examples, then come back to this page for deeper understanding.
+<Tip>
+ New here? Start with [Getting Started](getting-started) for hands-on examples, then come back here for deeper understanding.
+</Tip>
---
@@ -109,7 +112,7 @@ ontology = {
}
```
-Semantica can auto-generate ontologies from your knowledge graph, or import existing OWL/RDF/Turtle ontologies.
+Semantica can auto-generate ontologies from your knowledge graph, or import existing OWL/RDF/Turtle ontologies. The **Ontology Hub** (v0.5.0) provides a visual editor, SHACL Studio, alignment authoring, and a health dashboard.
---
@@ -123,18 +126,58 @@ Known: Apple Inc. is headquartered in Cupertino
Inferred: Steve Jobs has a connection to Cupertino
```
-Supported engines: forward chaining, Rete network, deductive, abductive, and SPARQL reasoning β€” all producing **explainable inference paths**, not black-box conclusions.
+Supported engines:
+
+| Engine | Description |
+|--------|-------------|
+| Forward chaining | Applies rules repeatedly until no new facts can be derived |
+| Rete network | Efficient pattern matching for large rule sets |
+| Deductive | Classical deductive reasoning |
+| Abductive | Infers the most likely explanation |
+| SPARQL | Query-based inference over RDF graphs |
+| Datalog | Recursive Horn clause rules with fixpoint semantics (v0.4.0) |
+
+All engines produce **explainable inference paths**, not black-box conclusions.
---
-## Temporal Graphs
+## Temporal Intelligence (v0.4.0)
Knowledge changes over time. Temporal graphs attach `valid_from` / `valid_until` windows to nodes and edges, enabling point-in-time queries and historical analysis.
+```python
+from semantica.kg import TemporalKnowledgeGraph
+from datetime import datetime
+
+tkg = TemporalKnowledgeGraph()
+tkg.add_node("ceo_role", valid_from=datetime(2020, 1, 1), valid_until=datetime(2023, 6, 1))
+
+# Query the graph as it existed on a specific date
+snapshot = tkg.at(datetime(2021, 6, 15))
+```
+
+Features: Allen interval algebra (all 13 relations), OWL-Time export, `recorded_at` stamping, temporal provenance.
+
Common uses: tracking company leadership changes, policy evolution, research timelines, financial instrument histories.
---
+## Distance Intelligence (v0.5.0)
+
+Explore the semantic neighborhood of any entity in your graph.
+
+```python
+from semantica.kg import DistanceCalculator
+
+calc = DistanceCalculator(graph)
+neighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)
+matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])
+```
+
+Features: NΓ—N distance matrices, ego-mode visualization, distance band classification (`near` / `mid` / `far`), embedding cache optimization.
+
+---
+
## Deduplication & Entity Resolution
Real-world data contains the same entity under many names β€” "Apple", "Apple Inc.", "Apple Computer Inc." Semantica's deduplication pipeline detects these, merges attributes, resolves conflicts, and preserves the original source provenance.
@@ -152,7 +195,26 @@ Every fact in Semantica links back to:
- The ontology rules applied
- The reasoning steps that produced any inference
-This is W3C PROV-O compliant lineage β€” suitable for regulated industries that require audit trails.
+This is W3C PROV-O compliant lineage β€” suitable for regulated industries that require audit trails (HIPAA, SOX, GDPR, FDA 21 CFR Part 11).
+
+---
+
+## Decision Intelligence
+
+Every agent decision is a first-class object in Semantica β€” recorded, causally linked, and searchable by precedent.
+
+```python
+decision_id = context.record_decision(
+ category="model_selection",
+ scenario="Choose LLM for production pipeline",
+ reasoning="GPT-4 benchmark advantage justifies 3x cost increase",
+ outcome="selected_gpt4",
+ confidence=0.91,
+)
+
+precedents = context.find_precedents("model selection reasoning", limit=5)
+influence = context.analyze_decision_influence(decision_id)
+```
---
@@ -166,7 +228,17 @@ Resolution strategies: prefer most recent, prefer most reliable source, majority
## Next Steps
-- [Quickstart Tutorial](quickstart.md) β€” build a full pipeline with code
-- [Modules Guide](modules.md) β€” every module explained
-- [Use Cases](use-cases.md) β€” real-world domain examples
-- [API Reference](reference/core.md) β€” complete technical reference
+<CardGroup cols={2}>
+ <Card title="Quickstart Tutorial" icon="play" href="quickstart">
+ Build a full pipeline with code.
+ </Card>
+ <Card title="Modules Guide" icon="puzzle-piece" href="modules">
+ Every module explained.
+ </Card>
+ <Card title="Use Cases" icon="briefcase" href="use-cases">
+ Real-world domain examples.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/context">
+ Complete technical reference.
+ </Card>
+</CardGroup>
diff --git a/docs/contributing.md b/docs/contributing.md
index 4b6f0e67..b9b18865 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -1,20 +1,24 @@
-# Contributing
+---
+title: "Contributing"
+description: "How to contribute code, documentation, tests, and community support to Semantica."
+icon: "code-pull-request"
+---
-Contributions of all kinds are welcome β€” code, documentation, tests, and community support.
+> Contributions of all kinds are welcome β€” code, documentation, tests, and community support.
---
## Quick Start
```bash
-# Fork the repo, then:
+# Fork the repo on GitHub, then:
git clone https://github.com/your-username/semantica.git
cd semantica
pip install -e ".[dev]"
pytest
```
-First time? Look for [`good-first-issue`](https://github.com/Hawksight-AI/semantica/labels/good-first-issue) labels for beginner-friendly tasks.
+New to the project? Look for [`good-first-issue`](https://github.com/Hawksight-AI/semantica/labels/good-first-issue) labels.
---
@@ -28,40 +32,40 @@ First time? Look for [`good-first-issue`](https://github.com/Hawksight-AI/semant
**Documentation**
- Fix typos, improve clarity, add examples
- Write tutorials or domain-specific cookbook notebooks
-- Keep API reference up to date
+- Keep the API reference up to date
**Testing**
-- Add test coverage for untested modules
+- Add coverage for untested modules
- Reproduce and confirm reported bugs
- Improve test reliability
**Community**
- Answer questions in issues and discussions
- Review pull requests
-- Share Semantica in your blog posts or talks
+- Share Semantica in blog posts or talks
---
## Reporting Issues
-### Bug Reports
-
-Include: what happened, steps to reproduce, expected behavior, and your environment (Python version, OS, Semantica version).
-
-### Feature Requests
+**Bug reports** β€” include: what happened, steps to reproduce, expected behavior, and your environment (Python version, OS, Semantica version).
-Include: your use case, what you'd like Semantica to do, and how it benefits others.
+**Feature requests** β€” include: your use case, what you'd like Semantica to do, and how it benefits others.
---
-## Pull Request Guidelines
+## Pull Request Checklist
Before submitting:
- [ ] Tests pass locally (`pytest`)
-- [ ] New features are documented with examples
+
+- [ ] New features have documentation with examples
+
- [ ] Code follows project style (Black, isort, flake8)
+
- [ ] Commit messages are clear and descriptive
+
- [ ] No unresolved merge conflicts
---
@@ -74,21 +78,20 @@ cd semantica
pip install -e ".[dev]"
```
-Code style tools used: **Black** (formatting), **isort** (imports), **flake8** (linting).
-
-Run the full test suite:
+Code style: **Black** (formatting), **isort** (imports), **flake8** (linting).
```bash
-pytest
+pytest # full test suite
+black semantica/ tests/ # format
+isort semantica/ tests/ # sort imports
+flake8 semantica/ # lint
```
---
-## Community
+## Code of Conduct
-Please follow the [Code of Conduct](https://github.com/Hawksight-AI/semantica/blob/main/CODE_OF_CONDUCT.md). Be respectful, patient, and constructive.
-
-All contributors are recognized in release notes and the GitHub contributors list.
+Please follow the [Code of Conduct](https://github.com/Hawksight-AI/semantica/blob/main/CODE_OF_CONDUCT.md). Be respectful, patient, and constructive. All contributors are recognized in release notes and the GitHub contributors list.
---
@@ -97,3 +100,16 @@ All contributors are recognized in release notes and the GitHub contributors lis
- [GitHub Issues](https://github.com/Hawksight-AI/semantica/issues)
- [GitHub Discussions](https://github.com/Hawksight-AI/semantica/discussions)
- [Discord](https://discord.gg/sV34vps5hH)
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Community" icon="users" href="community">
+ Community guidelines and values.
+ </Card>
+ <Card title="Governance" icon="scale-balanced" href="governance">
+ How decisions are made.
+ </Card>
+</CardGroup>
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 95defb06..2d2232a9 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -1,162 +1,105 @@
-# Semantica Cookbook
-
-Interactive Jupyter notebooks covering everything from your first knowledge graph to production GraphRAG systems.
+---
+title: "Cookbook"
+description: "Interactive Jupyter notebooks covering everything from your first knowledge graph to production GraphRAG systems."
+icon: "flask"
+---
-!!! tip "Where to start"
- - **New to Semantica** β€” begin with [Core Tutorials](#core-tutorials)
- - **Building an application** β€” see [Advanced Concepts](#advanced-concepts) or [Industry Use Cases](#industry-use-cases)
- - **Need installation help** β€” see the [Installation Guide](installation.md)
+<Tip>
+ **Where to start:**
+ - **New to Semantica** β€” begin with [Core Tutorials](#core-tutorials)
+ - **Building an application** β€” see [Advanced Concepts](#advanced-concepts) or [Industry Use Cases](#industry-use-cases)
+ - **Need installation help** β€” see the [Installation Guide](installation)
+</Tip>
-!!! note "Prerequisites"
- Python 3.8+, Jupyter, and an OpenAI API key (for most examples).
+<Note>
+ Prerequisites: Python 3.8+, Jupyter, and an API key for your preferred LLM provider.
+</Note>
---
## Featured Recipes
-<div class="grid cards" markdown>
-
-- :material-graph: **Your First Knowledge Graph**
- ---
+<CardGroup cols={2}>
+ <Card title="Your First Knowledge Graph" icon="diagram-project" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb">
Go from raw text to a queryable knowledge graph in 20 minutes.
- **Topics**: Extraction, Graph Construction, Visualization Β· **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb)
-
-- :material-robot: **GraphRAG Complete**
- ---
+ **Topics:** Extraction, Graph Construction, Visualization Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="GraphRAG Complete" icon="robot" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb">
Build a production-ready Graph Retrieval Augmented Generation system with hybrid retrieval and logical inference.
- **Topics**: RAG, LLMs, Vector Search, Graph Traversal Β· **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)
-
-- :material-scale-balance: **RAG vs. GraphRAG Comparison**
- ---
+ **Topics:** RAG, LLMs, Vector Search, Graph Traversal Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="RAG vs. GraphRAG Comparison" icon="scale-balanced" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb">
Side-by-side benchmark of standard RAG vs. GraphRAG on real-world data.
- **Topics**: RAG, GraphRAG, Benchmarking, Reasoning Gap Β· **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)
-
-- :material-shield-alert: **Real-Time Anomaly Detection**
- ---
+ **Topics:** RAG, GraphRAG, Benchmarking Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Real-Time Anomaly Detection" icon="shield-halved" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb">
Detect anomalies in streaming data using dynamic knowledge graphs.
- **Topics**: Streaming, Security, Dynamic Graphs Β· **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
-
-</div>
+ **Topics:** Streaming, Security, Dynamic Graphs Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
---
-## Core Tutorials {#core-tutorials}
+## Core Tutorials
Essential guides to master the Semantica framework.
-<div class="grid cards" markdown>
-
-- :material-hand-wave: **Welcome to Semantica**
- ---
- An interactive introduction to the framework's core philosophy and all modules including ingestion, parsing, extraction, knowledge graphs, embeddings, and more.
-
- **Topics**: Framework Overview, Architecture, All Modules
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)
-
-- :material-database-import: **Data Ingestion**
- ---
- Techniques for loading data from multiple sources using FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, RepoIngestor, EmailIngestor, DBIngestor, and MCPIngestor.
-
- **Topics**: File Ingestion, Web Scraping, Database Integration, Streams, Feeds, Repositories, Email, MCP
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/02_Data_Ingestion.ipynb)
-
-- :material-file-document-outline: **Document Parsing**
- ---
+<CardGroup cols={2}>
+ <Card title="Welcome to Semantica" icon="hands" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb">
+ An interactive introduction to the framework's core philosophy and all modules.
+
+ **Topics:** Framework Overview, Architecture Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Data Ingestion" icon="database" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/02_Data_Ingestion.ipynb">
+ Loading data from files, web, databases, streams, feeds, repositories, email, and MCP.
+
+ **Topics:** FileIngestor, WebIngestor, DBIngestor, Streams Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Document Parsing" icon="file-lines" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/03_Document_Parsing.ipynb">
Extracting clean text from complex formats like PDF, DOCX, and HTML.
-
- **Topics**: OCR, PDF Parsing, Text Extraction
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/03_Document_Parsing.ipynb)
-
-- :material-broom: **Data Normalization**
- ---
+
+ **Topics:** OCR, PDF Parsing, Text Extraction Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Data Normalization" icon="broom" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/04_Data_Normalization.ipynb">
Pipelines for cleaning, normalizing, and preparing text.
-
- **Topics**: Text Cleaning, Unicode, Formatting
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/04_Data_Normalization.ipynb)
-
-- :material-account-search: **Entity Extraction**
- ---
+
+ **Topics:** Text Cleaning, Unicode, Formatting Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Entity Extraction" icon="magnifying-glass" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/05_Entity_Extraction.ipynb">
Using NER to identify people, organizations, and custom entities.
-
- **Topics**: NER, Spacy, LLM Extraction
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/05_Entity_Extraction.ipynb)
-
-- :material-relation-many-to-many: **Relation Extraction**
- ---
+
+ **Topics:** NER, spaCy, LLM Extraction Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Relation Extraction" icon="arrows-split-up-and-left" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/06_Relation_Extraction.ipynb">
Discovering and classifying relationships between entities.
-
- **Topics**: Relation Classification, Dependency Parsing
-
- **Difficulty**: Beginner
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/06_Relation_Extraction.ipynb)
-
-- :material-vector-square: **Embedding Generation**
- ---
+
+ **Topics:** Relation Classification, Dependency Parsing Β· **Difficulty:** Beginner
+ </Card>
+ <Card title="Embedding Generation" icon="vector-square" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/12_Embedding_Generation.ipynb">
Creating and managing vector embeddings for semantic search.
-
- **Topics**: Embeddings, OpenAI, HuggingFace
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/12_Embedding_Generation.ipynb)
-
-- :material-database-search: **Vector Store**
- ---
+
+ **Topics:** Embeddings, OpenAI, HuggingFace Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Vector Store" icon="database" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/13_Vector_Store.ipynb">
Setting up vector stores for similarity search and retrieval.
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/13_Vector_Store.ipynb)
-- :material-database-settings: **Graph Store**
- ---
+ **Difficulty:** Intermediate
+ </Card>
+ <Card title="Graph Store" icon="server" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Graph_Store.ipynb">
Persisting knowledge graphs in Neo4j or FalkorDB.
-
- **Topics**: Neo4j, Cypher, Persistence
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Graph_Store.ipynb)
-
-- :material-sitemap: **Ontology**
- ---
+
+ **Topics:** Neo4j, Cypher, Persistence Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb">
Defining domain schemas and ontologies to structure your data.
-
- **Topics**: OWL, RDF, Schema Design
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb)
-</div>
+ **Topics:** OWL, RDF, Schema Design Β· **Difficulty:** Intermediate
+ </Card>
+</CardGroup>
---
@@ -164,314 +107,183 @@ Essential guides to master the Semantica framework.
Deep dive into advanced features, customization, and complex workflows.
-<div class="grid cards" markdown>
-
-- :material-flask: **Advanced Extraction**
- ---
+<CardGroup cols={2}>
+ <Card title="Advanced Extraction" icon="flask" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/01_Advanced_Extraction.ipynb">
Custom extractors, LLM-based extraction, and complex pattern matching.
-
- **Topics**: Custom Models, Regex, LLMs
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/01_Advanced_Extraction.ipynb)
-
-- :material-chart-network: **Advanced Graph Analytics**
- ---
+
+ **Topics:** Custom Models, Regex, LLMs Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Advanced Graph Analytics" icon="chart-network" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb">
Centrality, community detection, and pathfinding algorithms.
-
- **Topics**: PageRank, Louvain, Shortest Path
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb)
-
-- :material-brain: **Advanced Context Engineering**
- ---
- Build a production-grade memory system for AI agents using persistent Vector (FAISS) and Graph (Neo4j) stores.
-
- **Topics**: Agent Memory, GraphRAG, Entity Injection, Lifecycle Management
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb)
-
-- :material-monitor-dashboard: **Complete Visualization Suite**
- ---
- Creating interactive, publication-ready visualizations of your graphs.
-
- **Topics**: PyVis, NetworkX, D3.js
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)
-
-- :material-scale-balance: **Conflict Resolution**
- ---
+
+ **Topics:** PageRank, Louvain, Shortest Path Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Advanced Context Engineering" icon="brain" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb">
+ Production-grade memory system for AI agents using FAISS and Neo4j.
+
+ **Topics:** Agent Memory, GraphRAG, Entity Injection Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Complete Visualization Suite" icon="chart-bar" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb">
+ Interactive, publication-ready visualizations of your graphs.
+
+ **Topics:** PyVis, NetworkX, D3.js Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Conflict Resolution" icon="scale-balanced" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb">
Strategies for handling contradictory information from multiple sources.
-
- **Topics**: Truth Discovery, Voting, Confidence
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb)
-
-- :material-export: **Multi-Format Export**
- ---
+
+ **Topics:** Truth Discovery, Voting, Confidence Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Multi-Format Export" icon="file-export" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb">
Exporting to RDF, OWL, JSON-LD, and NetworkX formats.
-
- **Topics**: Serialization, Interoperability
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)
-
-- :material-source-merge: **Multi-Source Integration**
- ---
+
+ **Topics:** Serialization, Interoperability Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Multi-Source Integration" icon="code-merge" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb">
Merging data from disparate sources into a unified graph.
-
- **Topics**: Entity Resolution, Merging, Fusion
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)
-
-- :material-pipe: **Pipeline Orchestration**
- ---
+
+ **Topics:** Entity Resolution, Merging, Fusion Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Pipeline Orchestration" icon="gear" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/07_Pipeline_Orchestration.ipynb">
Building robust, automated data processing pipelines.
-
- **Topics**: Workflows, Automation, Error Handling
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/07_Pipeline_Orchestration.ipynb)
-
-- :material-brain: **Reasoning and Inference**
- ---
+
+ **Topics:** Workflows, Automation, Error Handling Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Reasoning and Inference" icon="brain" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb">
Using logical reasoning to infer new knowledge from existing facts.
-
- **Topics**: Logic Rules, Inference Engines
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb)
-- :material-layers: **Semantic Layer Construction**
- ---
- Building a semantic layer over your data warehouse or lake.
-
- **Topics**: Semantic Layer, Data Warehouse
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/09_Semantic_Layer_Construction.ipynb)
-
-- :material-clock-outline: **Temporal Knowledge Graphs**
- ---
+
+ **Topics:** Logic Rules, Inference Engines Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Temporal Knowledge Graphs" icon="clock" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/10_Temporal_Knowledge_Graphs.ipynb">
Modeling and querying data that changes over time.
-
- **Topics**: Time Series, Temporal Logic
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/10_Temporal_Knowledge_Graphs.ipynb)
-</div>
+ **Topics:** Time Series, Temporal Logic, Allen Algebra Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
---
-## Industry Use Cases {#industry-use-cases}
-
-Real-world examples and end-to-end applications across various industries.
+## Industry Use Cases
### Biomedical
-<div class="grid cards" markdown>
-
-- :material-pill: **Drug Discovery Pipeline**
- ---
+<CardGroup cols={2}>
+ <Card title="Drug Discovery Pipeline" icon="pills" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb">
Accelerating drug discovery by connecting genes, proteins, and drugs using PubMed RSS feeds, entity-aware chunking, GraphRAG, and vector similarity search.
-
- **Topics**: Bioinformatics, KG Construction, GraphRAG, Vector Search
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb)
-
-- :material-dna: **Genomic Variant Analysis**
- ---
- Analyzing genomic variants and their implications for disease using bioRxiv RSS feeds, temporal knowledge graphs, deduplication, and pathway analysis.
-
- **Topics**: Genomics, Variant Calling, Temporal KGs, Graph Analytics
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb)
-
-</div>
+
+ **Topics:** Bioinformatics, KG Construction, GraphRAG Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Genomic Variant Analysis" icon="dna" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb">
+ Analyzing genomic variants and their implications using bioRxiv RSS feeds, temporal KGs, deduplication, and pathway analysis.
+
+ **Topics:** Genomics, Temporal KGs, Graph Analytics Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
### Finance
-<div class="grid cards" markdown>
-
-- :material-finance: **Financial Data Integration MCP**
- ---
- Merging financial data from Alpha Vantage API, MCP servers, RSS feeds, and market feeds with seed data integration.
-
- **Topics**: Finance, Data Fusion, MCP Integration, Real-Time Ingestion
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)
-
-- :material-incognito: **Fraud Detection**
- ---
- Identifying fraudulent activities and patterns in transaction networks using temporal knowledge graphs, conflict detection, and pattern recognition.
-
- **Topics**: Anomaly Detection, Graph Mining, Temporal Analysis, Pattern Detection
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb)
-
-</div>
+<CardGroup cols={2}>
+ <Card title="Financial Data Integration (MCP)" icon="chart-line" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb">
+ Merging financial data from Alpha Vantage API, MCP servers, RSS feeds, and market feeds.
+
+ **Topics:** Finance, Data Fusion, MCP Integration Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Fraud Detection" icon="user-secret" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb">
+ Identifying fraudulent activities in transaction networks using temporal KGs, conflict detection, and pattern recognition.
+
+ **Topics:** Anomaly Detection, Graph Mining, Temporal Analysis Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
### Blockchain
-<div class="grid cards" markdown>
-
-- :material-bitcoin: **DeFi Protocol Intelligence**
- ---
- Analyzing decentralized finance protocols and transaction flows using CoinDesk RSS feeds, ontology-aware chunking, conflict detection, and ontology generation.
-
- **Topics**: Blockchain, DeFi, Smart Contracts, Ontology, Conflict Resolution
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb)
-
-- :material-network: **Transaction Network Analysis**
- ---
- Mapping and analyzing blockchain transaction networks using blockchain APIs, deduplication, and network pattern detection.
-
- **Topics**: Blockchain Analytics, Network Analysis, Deduplication, Pattern Detection
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb)
-
-</div>
+<CardGroup cols={2}>
+ <Card title="DeFi Protocol Intelligence" icon="bitcoin-sign" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb">
+ Analyzing decentralized finance protocols and transaction flows using CoinDesk RSS feeds, ontology-aware chunking, and conflict detection.
+
+ **Topics:** Blockchain, DeFi, Smart Contracts, Ontology Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Transaction Network Analysis" icon="network-wired" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb">
+ Mapping and analyzing blockchain transaction networks using deduplication and network pattern detection.
+
+ **Topics:** Blockchain Analytics, Network Analysis Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
### Cybersecurity
-<div class="grid cards" markdown>
-
-- :material-shield-alert: **Real-Time Anomaly Detection**
- ---
- Detecting anomalies in real-time network traffic streams using CVE RSS feeds, Kafka streams, temporal knowledge graphs, and sentence chunking.
-
- **Topics**: Network Security, Streaming, Temporal KGs, Pattern Detection
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
-
-- :material-robot-angry: **Threat Intelligence Hybrid RAG**
- ---
- Combining enhanced GraphRAG with threat intelligence for security insights using security RSS feeds, entity-aware chunking, deduplication, and temporal knowledge graphs.
-
- **Topics**: Threat Intelligence, GraphRAG, Security, Hybrid Retrieval
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)
-
-</div>
+<CardGroup cols={2}>
+ <Card title="Real-Time Anomaly Detection" icon="shield-halved" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb">
+ Detecting anomalies in real-time network traffic streams using CVE RSS feeds, Kafka streams, and temporal KGs.
+
+ **Topics:** Network Security, Streaming, Temporal KGs Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Threat Intelligence Hybrid RAG" icon="robot" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb">
+ Combining enhanced GraphRAG with threat intelligence for security insights.
+
+ **Topics:** Threat Intelligence, GraphRAG, Hybrid Retrieval Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
### Intelligence
-<div class="grid cards" markdown>
-
-- :material-account-network: **Criminal Network Analysis**
- ---
- Analyze criminal networks with graph analytics and key player detection using OSINT RSS feeds, deduplication, and network centrality analysis.
-
- **Topics**: Forensics, Social Network Analysis, Deduplication, Graph Analytics
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
-
-- :material-file-search: **Intelligence Analysis Orchestrator Worker**
- ---
- Comprehensive intelligence analysis using pipeline orchestrator with multiple RSS feeds, conflict detection, and multi-source integration.
-
- **Topics**: Intelligence Analysis, Pipeline Orchestration, Multi-Source Integration, Conflict Resolution
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
-
-</div>
-
-### Renewable Energy
-
-<div class="grid cards" markdown>
-
-- :material-wind-turbine: **Energy Market Analysis**
- ---
- Analyzing trends and pricing in the renewable energy market using energy RSS feeds, EIA API, temporal knowledge graphs, TemporalPatternDetector, and seed data integration.
-
- **Topics**: Energy, Time Series, Temporal Analysis, Trend Prediction
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)
-
-</div>
-
-### Supply Chain
-
-<div class="grid cards" markdown>
-
-- :material-truck-delivery: **Supply Chain Data Integration**
- ---
- Integrating supply chain data to optimize logistics and reduce risk using logistics RSS feeds, deduplication, and multi-source relationship mapping.
-
- **Topics**: Logistics, Risk Management, Data Integration, Deduplication
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb)
-
-</div>
+<CardGroup cols={2}>
+ <Card title="Criminal Network Analysis" icon="users" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb">
+ Analyze criminal networks with graph analytics and key player detection using OSINT RSS feeds and network centrality analysis.
+
+ **Topics:** Forensics, Social Network Analysis Β· **Difficulty:** Advanced
+ </Card>
+ <Card title="Intelligence Analysis Orchestrator" icon="file-magnifying-glass" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb">
+ Comprehensive intelligence analysis using pipeline orchestrator with multiple RSS feeds and multi-source integration.
+
+ **Topics:** Intelligence Analysis, Pipeline Orchestration Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
+
+### Renewable Energy & Supply Chain
+
+<CardGroup cols={2}>
+ <Card title="Energy Market Analysis" icon="wind" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb">
+ Analyzing trends and pricing in the renewable energy market using EIA API, temporal KGs, and TemporalPatternDetector.
+
+ **Topics:** Energy, Time Series, Temporal Analysis Β· **Difficulty:** Intermediate
+ </Card>
+ <Card title="Supply Chain Data Integration" icon="truck" href="https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb">
+ Integrating supply chain data to optimize logistics and reduce risk.
+
+ **Topics:** Logistics, Risk Management, Deduplication Β· **Difficulty:** Advanced
+ </Card>
+</CardGroup>
---
## How to Run
-To run these notebooks locally:
-
-1. **Install Semantica from PyPI** (recommended):
+<Steps>
+ <Step title="Install Semantica">
```bash
pip install semantica[all]
pip install jupyter
```
-
-2. **Or install from source** (for development):
+ </Step>
+ <Step title="Clone the repository (optional, for source install)">
```bash
git clone https://github.com/Hawksight-AI/semantica.git
cd semantica
- pip install -e .[all]
+ pip install -e ".[all]"
pip install jupyter
```
-
-3. **Launch Jupyter**:
+ </Step>
+ <Step title="Launch Jupyter">
```bash
jupyter notebook
```
+ </Step>
+</Steps>
-!!! tip "Using Docker"
- You can also run the cookbook using Docker:
- ```bash
- docker run -p 8888:8888 hawksight/semantica-cookbook
- ```
+<Tip>
+ You can also run the cookbook using Docker:
+
+ ```bash
+ docker run -p 8888:8888 hawksight/semantica-cookbook
+ ```
+</Tip>
diff --git a/docs/deep-dive.md b/docs/deep-dive.md
index 3a6ea484..8c67ad49 100644
--- a/docs/deep-dive.md
+++ b/docs/deep-dive.md
@@ -1,59 +1,31 @@
-# Deep Dive
+---
+title: "Deep Dive"
+description: "Internals, advanced concepts, and extension points for contributors and power users."
+icon: "microscope"
+---
-Internals, advanced concepts, and extension points for contributors and power users.
+> Internals, advanced concepts, and extension points for contributors and power users.
-!!! tip "Just getting started?"
- Read [Architecture](architecture.md) for a higher-level overview first.
+<Tip>
+New to Semantica? Read the [Architecture](architecture) overview first for a higher-level picture.
+</Tip>
---
## Pipeline Internals
-The full data flow through a Semantica pipeline:
-
-```mermaid
-graph TB
- A[Data Sources] --> B[Ingestion Layer]
- B --> C[Parsing Layer]
- C --> D[Extraction Layer]
- D --> E[Normalization Layer]
- E --> F[Conflict Resolution]
- F --> G[Knowledge Graph Builder]
- G --> H[Embedding Generator]
- H --> I[Export Layer]
-
- D --> D1[Entity Extractor]
- D --> D2[Relationship Extractor]
- D --> D3[Triplet Extractor]
-
- G --> G1[Graph Validator]
- G --> G2[Graph Analyzer]
-
- H --> H1[Text Embeddings]
- H --> H2[Graph Embeddings]
-```
-
-### Sequence Diagram
-
-```mermaid
-sequenceDiagram
- participant User
- participant Semantica
- participant Ingestor
- participant Parser
- participant Extractor
- participant Resolver
- participant GraphBuilder
- participant Exporter
-
- User->>Semantica: build_knowledge_base(sources)
- Semantica->>Ingestor: ingest(sources)
- Ingestor->>Parser: parse(documents)
- Parser->>Extractor: extract(text)
- Extractor->>Resolver: resolve_conflicts(entities)
- Resolver->>GraphBuilder: build_graph(resolved_data)
- GraphBuilder->>Exporter: export(graph)
- Exporter->>User: return result
+Full data flow through a Semantica pipeline:
+
+```text
+Data Sources
+ └─ Ingestion Layer (FileIngestor, WebIngestor, SnowflakeIngestor, StreamIngestor)
+ └─ Parsing Layer (DocumentParser, DoclingParser, OCR)
+ └─ Extraction (NER β†’ Entity Linking β†’ Validation)
+ └─ Normalization
+ └─ Conflict Resolution
+ └─ Knowledge Graph Builder
+ └─ Embedding Generator
+ └─ Export Layer
```
---
@@ -62,26 +34,20 @@ sequenceDiagram
### Ingestion Layer
-Handles input from any source:
-
-- **FileIngestor** β€” PDF, DOCX, HTML, JSON, CSV, archives
+- **FileIngestor** β€” PDF, DOCX, HTML, JSON, CSV, TXT, Parquet (v0.5.0), XML (v0.5.0), archives
- **WebIngestor** β€” URL crawling and scraping
-- **DBIngestor** / **SnowflakeIngestor** β€” SQL databases
+- **SnowflakeIngestor** β€” SQL databases and cloud warehouses
- **StreamIngestor** β€” Kafka and real-time feeds
### Parsing Layer
-Converts raw data to structured text:
-
- Text and metadata extraction from documents
- OCR for scanned content
-- Layout analysis (via Docling for tables and columns)
+- Layout analysis via Docling (tables, columns, headers)
### Extraction Layer
-Core semantic processing pipeline:
-
-```
+```text
text β†’ Tokenization β†’ NER β†’ Entity Linking β†’ Entity Validation
```
@@ -89,43 +55,37 @@ Components: Named Entity Recognition, Relationship Extraction, Triplet Extractio
### Normalization Layer
-Standardizes extracted data: entity names, date formats, numbers, encodings, and language normalization.
+Standardizes entity names, date formats, numbers, encodings, and language. Includes the v0.5.0 cp1252 encoding fix for Windows environments.
### Conflict Resolution
-Handles contradictory facts from multiple sources:
-
-```mermaid
-graph LR
- A[Multiple Sources] --> B[Conflict Detection]
- B --> C{Resolution Strategy}
- C --> D[Voting]
- C --> E[Credibility Weighted]
- C --> F[Most Recent]
- C --> G[Highest Confidence]
- D --> H[Resolved Entity]
- E --> H
- F --> H
- G --> H
-```
+Multiple source facts that contradict each other are resolved using one of four strategies:
+
+| Strategy | Behavior |
+|----------|----------|
+| `voting` | Most common value wins |
+| `credibility_weighted` | Higher-credibility source wins |
+| `most_recent` | Latest timestamp wins |
+| `highest_confidence` | Highest extraction confidence wins |
### Knowledge Graph Builder
- Entity resolution across sources
-- Edge creation (typed relationships)
+- Edge creation with typed relationships
- Property assignment with confidence scores
- Graph validation and quality checks
### Embedding Generator
-- Text embeddings (Sentence-Transformers, FastEmbed, OpenAI, BGE)
-- Graph embeddings (Node2Vec, GraphSAGE)
+- Text embeddings: Sentence-Transformers, FastEmbed, OpenAI, BGE
+- Graph embeddings: Node2Vec, GraphSAGE
+- Distance caching for Distance Intelligence (v0.5.0)
---
## Advanced Concepts
-### Entity Resolution Algorithm
+### Entity Resolution
```python
def resolve_entities(entities, threshold=0.85):
@@ -144,12 +104,13 @@ def resolve_entities(entities, threshold=0.85):
### Relationship Inference
-Semantica's reasoning engines can derive implicit relationships:
+Semantica's reasoning engines derive implicit relationships:
- **Transitive** — if A→B and B→C, infer A→C
-- **Temporal** β€” before, after, during from timestamped facts
+- **Temporal** β€” before/after/during from timestamped facts (Allen Interval Algebra)
- **Causal** β€” IF/THEN rules via `Reasoner`
- **Hierarchical** β€” subclass/instance inference via `OntologyReasoner`
+- **Datalog** β€” recursive rules with termination guarantee (v0.4.0)
### Batch Processing for Large Datasets
@@ -173,8 +134,10 @@ def process_large_dataset(sources, batch_size=100):
from semantica.core import Plugin
class CustomPlugin(Plugin):
+ def initialize(self):
+ ...
+
def process(self, data):
- # Your custom processing logic
return processed_data
```
@@ -219,17 +182,27 @@ Extension hooks: plugin registration, custom extractor registration, custom expo
**Why modular architecture?** Each component is independently testable and swappable. You can use `NERExtractor` alone without pulling in graph storage or pipelines.
-**Why built-in conflict resolution?** Multi-source data always has contradictions. Ignoring them produces garbage graphs. Explicit resolution strategies give you control over data quality.
+**Why built-in conflict resolution?** Multi-source data always has contradictions. Ignoring them produces low-quality graphs. Explicit strategies give you control over data quality.
-**Why W3C PROV-O for provenance?** It's an industry standard with tooling support. Using a custom format would make lineage data non-portable.
+**Why W3C PROV-O for provenance?** It's an industry standard with broad tooling support. A custom format would make lineage data non-portable.
-**Why multiple reasoning engines?** Different problems need different reasoning: forward chaining for rule application, SPARQL for graph queries, abductive for hypothesis generation. No single engine fits all cases.
+**Why multiple reasoning engines?** Different problems need different reasoning: forward chaining for rule application, SPARQL for graph queries, abductive for hypothesis generation, Datalog for recursive rules.
---
-## Further Reading
-
-- [Architecture](architecture.md) β€” high-level three-layer overview
-- [Modules](modules.md) β€” every module with code examples
-- [API Reference](reference/core.md) β€” complete technical reference
-- [Contributing](contributing.md) β€” how to extend the framework
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Modules" icon="cubes" href="modules">
+ Every module with code examples.
+ </Card>
+ <Card title="Core Module" icon="gear" href="reference/core">
+ Framework orchestration internals.
+ </Card>
+ <Card title="Pipeline" icon="arrows-turn-to-dots" href="reference/pipeline">
+ Pipeline DSL and execution model.
+ </Card>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ How to extend the framework.
+ </Card>
+</CardGroup>
diff --git a/docs/docs.json b/docs/docs.json
new file mode 100644
index 00000000..498a22c1
--- /dev/null
+++ b/docs/docs.json
@@ -0,0 +1,262 @@
+{
+ "$schema": "https://mintlify.com/docs.json",
+ "theme": "maple",
+ "name": "Semantica",
+ "description": "The Accountability and Context Layer for AI β€” Context Graphs Β· Decision Intelligence Β· Full Provenance",
+ "colors": {
+ "primary": "#059669",
+ "light": "#10B981",
+ "dark": "#047857"
+ },
+ "favicon": "/assets/img/Semantica Logo.png",
+ "logo": {
+ "light": "/assets/img/Semantica Logo.png",
+ "dark": "/assets/img/Semantica Logo.png"
+ },
+ "font": {
+ "headings": {
+ "family": "Lexend"
+ },
+ "body": {
+ "family": "Inter"
+ }
+ },
+ "appearance": {
+ "default": "dark"
+ },
+ "background": {
+ "color": {
+ "dark": "#0A0A0A",
+ "light": "#FAF7F0"
+ }
+ },
+ "chat": {
+ "enabled": true
+ },
+ "feedback": {
+ "thumbsRating": true,
+ "suggestEdit": true,
+ "raiseIssue": true
+ },
+ "metadata": {
+ "og:title": "Semantica β€” Accountability & Context Layer for AI",
+ "og:description": "Build explainable, auditable knowledge graphs with full provenance. Open source. MIT licensed.",
+ "og:image": "/assets/img/Semantica Logo.png",
+ "twitter:card": "summary_large_image",
+ "twitter:site": "@BuildSemantica"
+ },
+ "navigation": {
+ "tabs": [
+ {
+ "tab": "Documentation",
+ "groups": [
+ {
+ "group": "Overview",
+ "pages": [
+ "index"
+ ]
+ },
+ {
+ "group": "Core Concepts",
+ "pages": [
+ "concepts",
+ "modules",
+ "use-cases",
+ "glossary"
+ ]
+ },
+ {
+ "group": "Guides",
+ "pages": [
+ "examples",
+ "architecture",
+ "deep-dive",
+ "learning-more"
+ ]
+ },
+ {
+ "group": "Integrations",
+ "pages": [
+ "integrations/agno",
+ "integrations/docling",
+ "integrations/snowflake"
+ ]
+ },
+ {
+ "group": "Graph Stores",
+ "pages": [
+ "graph_stores/apache_age"
+ ]
+ },
+ {
+ "group": "Vector Stores",
+ "pages": [
+ "vector_store_usage",
+ "vector_stores/pgvector"
+ ]
+ }
+ ]
+ },
+ {
+ "tab": "Quick Start",
+ "groups": [
+ {
+ "group": "Get Started",
+ "pages": [
+ "installation",
+ "quickstart",
+ "getting-started"
+ ]
+ }
+ ]
+ },
+ {
+ "tab": "API Reference",
+ "groups": [
+ {
+ "group": "Context & Knowledge",
+ "pages": [
+ "reference/context",
+ "reference/kg",
+ "reference/semantic_extract",
+ "reference/reasoning",
+ "reference/ontology"
+ ]
+ },
+ {
+ "group": "Storage",
+ "pages": [
+ "reference/vector_store",
+ "reference/graph_store",
+ "reference/triplet_store"
+ ]
+ },
+ {
+ "group": "Data Pipeline",
+ "pages": [
+ "reference/ingest",
+ "reference/parse",
+ "reference/split",
+ "reference/normalize",
+ "reference/embeddings",
+ "reference/pipeline"
+ ]
+ },
+ {
+ "group": "Quality & Provenance",
+ "pages": [
+ "reference/deduplication",
+ "reference/conflicts",
+ "reference/provenance",
+ "reference/change_management"
+ ]
+ },
+ {
+ "group": "Output",
+ "pages": [
+ "reference/export",
+ "reference/visualization",
+ "reference/explorer"
+ ]
+ },
+ {
+ "group": "Utilities",
+ "pages": [
+ "reference/llms",
+ "reference/seed",
+ "reference/evals",
+ "reference/utils",
+ "reference/core",
+ "reference/mcp_server"
+ ]
+ }
+ ]
+ },
+ {
+ "tab": "Cookbook",
+ "groups": [
+ {
+ "group": "Cookbook",
+ "pages": [
+ "cookbook"
+ ]
+ }
+ ]
+ },
+ {
+ "tab": "FAQ",
+ "groups": [
+ {
+ "group": "FAQ",
+ "pages": [
+ "faq"
+ ]
+ },
+ {
+ "group": "Community",
+ "pages": [
+ "community",
+ "community-projects",
+ "contributing",
+ "governance",
+ "citation",
+ "license"
+ ]
+ }
+ ]
+ }
+ ],
+ "global": {
+ "anchors": [
+ {
+ "anchor": "Discord",
+ "href": "https://discord.gg/sV34vps5hH",
+ "icon": "discord"
+ },
+ {
+ "anchor": "GitHub",
+ "href": "https://github.com/Hawksight-AI/semantica",
+ "icon": "github"
+ },
+ {
+ "anchor": "PyPI",
+ "href": "https://pypi.org/project/semantica/",
+ "icon": "python"
+ },
+ {
+ "anchor": "Follow on X",
+ "href": "https://x.com/BuildSemantica",
+ "icon": "x-twitter"
+ }
+ ]
+ }
+ },
+ "navbar": {
+ "links": [
+ {
+ "label": "GitHub",
+ "href": "https://github.com/Hawksight-AI/semantica"
+ },
+ {
+ "label": "Discord",
+ "href": "https://discord.gg/sV34vps5hH"
+ }
+ ],
+ "primary": {
+ "type": "button",
+ "label": "pip install semantica",
+ "href": "https://pypi.org/project/semantica/"
+ }
+ },
+ "search": {
+ "prompt": "Search docs...",
+ "location": "topbar"
+ },
+ "footer": {
+ "socials": {
+ "github": "https://github.com/Hawksight-AI/semantica",
+ "discord": "https://discord.gg/sV34vps5hH",
+ "x": "https://x.com/BuildSemantica"
+ }
+ }
+}
diff --git a/docs/examples.md b/docs/examples.md
index 7f2c6bfa..b9b8170f 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -1,6 +1,10 @@
-# Examples
+---
+title: "Examples"
+description: "Code examples organized by complexity β€” beginner through production."
+icon: "code"
+---
-Code examples organized by complexity. For interactive notebooks, see the [Cookbook](cookbook.md).
+> Code examples organized by complexity. For interactive notebooks, see the [Cookbook](cookbook).
---
@@ -19,8 +23,8 @@ parser = DocumentParser()
ner = NERExtractor()
rel = RelationExtractor()
-sources = ingestor.ingest("data/sample.pdf")
-parsed = parser.parse(sources[0])
+sources = ingestor.ingest("data/sample.pdf")
+parsed = parser.parse(sources[0])
entities = ner.extract(parsed)
relationships = rel.extract(parsed, entities=entities)
@@ -46,18 +50,14 @@ for entity in entities:
# 1976: DATE
```
-### Custom NER Configuration
+### Custom NER with LLM
```python
from semantica.semantic_extract import NERExtractor
+from semantica.llms import OpenAI
-ner = NERExtractor(
- method="llm",
- provider="openai",
- model="gpt-4",
- confidence_threshold=0.8,
- temperature=0.0,
-)
+llm = OpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"))
+ner = NERExtractor(method="llm", llm_provider=llm, confidence_threshold=0.8)
entities = ner.extract("Your document text here...")
```
@@ -96,7 +96,7 @@ print(f"Unified graph: {len(kg.nodes)} nodes, {len(kg.edges)} edges")
```python
from semantica.conflicts import ConflictDetector, ConflictResolver
-detector = ConflictDetector()
+detector = ConflictDetector()
conflicts = detector.detect_conflicts(all_entities)
resolver = ConflictResolver(default_strategy="voting")
@@ -105,7 +105,16 @@ resolved = resolver.resolve_conflicts(conflicts)
print(f"Detected {len(conflicts)} conflicts, resolved {len(resolved)}")
```
-### Persistent Storage (Neo4j)
+### Parquet and XML Ingestion (v0.5.0)
+
+```python
+from semantica.ingest import ParquetIngestor, XMLIngestor
+
+parquet_data = ParquetIngestor().ingest("data/records.parquet")
+xml_data = XMLIngestor(safe_mode=True).ingest("data/feed.xml")
+```
+
+### Persistent Storage β€” Neo4j
```python
from semantica.graph_store import GraphStore
@@ -128,24 +137,6 @@ store.create_relationship(
store.close()
```
-### FalkorDB (High-Speed Queries)
-
-```python
-from semantica.graph_store import GraphStore
-
-store = GraphStore(
- backend="falkordb",
- host="localhost",
- port=6379,
- graph_name="knowledge_graph",
-)
-store.connect()
-results = store.execute_query(
- "MATCH (n)-[r]->(m) WHERE n.name CONTAINS 'AI' RETURN n"
-)
-store.close()
-```
-
---
## Advanced
@@ -173,7 +164,29 @@ for fact in inferred:
results = context.retrieve("What technologies are used in this project?")
```
-[Full GraphRAG tutorial](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) Β· [RAG vs. GraphRAG comparison](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)
+### Temporal Knowledge Graph (v0.4.0)
+
+```python
+from semantica.kg import TemporalKnowledgeGraph
+
+tkg = TemporalKnowledgeGraph()
+tkg.add_temporal_fact("Apple", "CEO", "Tim Cook", valid_from="2011-08-24")
+tkg.add_temporal_fact("Apple", "CEO", "Steve Jobs", valid_from="1997-09-16", valid_to="2011-08-24")
+
+ceo_2005 = tkg.query_at("Apple", "CEO", timestamp="2005-01-01")
+```
+
+### Distance Intelligence (v0.5.0)
+
+```python
+from semantica.kg import DistanceCalculator
+
+calc = DistanceCalculator(kg)
+dist = calc.calculate("Apple Inc.", "Microsoft")
+
+print(f"Distance: {dist.score:.3f} β€” Band: {dist.band}")
+similar = calc.find_similar("Apple Inc.", radius=0.3)
+```
---
@@ -182,31 +195,20 @@ results = context.retrieve("What technologies are used in this project?")
### Batch Processing (Large Datasets)
```python
+from semantica.pipeline import Pipeline
from semantica.ingest import FileIngestor
from semantica.parse import DocumentParser
-from semantica.semantic_extract import NERExtractor, RelationExtractor
+from semantica.semantic_extract import NERExtractor
from semantica.kg import GraphBuilder
-ingestor = FileIngestor()
-parser = DocumentParser()
-ner = NERExtractor()
-rel = RelationExtractor()
-builder = GraphBuilder()
-
-sources = [f"data/doc_{i}.pdf" for i in range(1000)]
-batch_size = 50
-
-for i in range(0, len(sources), batch_size):
- batch = sources[i : i + batch_size]
- all_entities, all_rels = [], []
-
- for path in batch:
- parsed = parser.parse(ingestor.ingest(path)[0])
- all_entities.extend(ner.extract(parsed))
- all_rels.extend(rel.extract(parsed, entities=all_entities))
+pipeline = Pipeline(workers=4)
+pipeline.add_step("ingest", FileIngestor())
+pipeline.add_step("parse", DocumentParser())
+pipeline.add_step("extract", NERExtractor(), parallel=True, batch_size=50)
+pipeline.add_step("build", GraphBuilder())
- kg = builder.build(entities=all_entities, relationships=all_rels)
- print(f"Batch {i // batch_size + 1}: {len(kg.nodes)} nodes")
+result = pipeline.run("data/")
+print(f"Processed: {result.processed_count}, Failed: {result.failed_count}")
```
### Real-Time Streaming
@@ -233,12 +235,19 @@ for batch in stream.stream(batch_size=100):
---
-## More Resources
-
-- [Quickstart Tutorial](quickstart.md) β€” step-by-step first pipeline
-- [Cookbook](cookbook.md) β€” interactive Jupyter notebooks
-- [Use Cases](use-cases.md) β€” domain-specific examples
-- [API Reference](reference/core.md) β€” complete API documentation
-
-!!! info "Have an example to share?"
- [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Quickstart" icon="play" href="quickstart">
+ Step-by-step first pipeline tutorial.
+ </Card>
+ <Card title="Cookbook" icon="book-open" href="cookbook">
+ Interactive Jupyter notebook tutorials.
+ </Card>
+ <Card title="Use Cases" icon="briefcase" href="use-cases">
+ Domain-specific examples.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/core">
+ Complete API documentation.
+ </Card>
+</CardGroup>
diff --git a/docs/faq.md b/docs/faq.md
index ff5bfc31..57025a07 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -1,149 +1,241 @@
-# Frequently Asked Questions
-
-Common questions about Semantica. Use Ctrl+F to find what you need.
-
+---
+title: "FAQ"
+description: "Common questions about Semantica β€” installation, features, integrations, and troubleshooting."
+icon: "circle-question"
---
-## General
+<AccordionGroup>
-### What is Semantica?
+## General
+<Accordion title="What is Semantica?" icon="info-circle">
Semantica is an open-source framework for building context graphs and decision intelligence layers for AI. It transforms unstructured data β€” documents, APIs, databases β€” into structured knowledge graphs with full provenance tracking, making AI systems explainable and auditable.
+</Accordion>
-### What can I build with Semantica?
+<Accordion title="What can I build with Semantica?" icon="hammer">
- Knowledge graphs from documents and multi-source data
- GraphRAG systems with graph-grounded retrieval
- AI agents with structured decision history and semantic memory
- Compliance-ready pipelines with W3C PROV-O lineage
-### What makes Semantica different from other frameworks?
+</Accordion>
+
+<Accordion title="What makes Semantica different from LangChain or LlamaIndex?" icon="scale-balanced">
+Most frameworks stop at retrieval or generation. Semantica adds an **accountability layer**: every decision is recorded, every fact links to a source, and every reasoning step is explainable. It's designed for environments where you need to audit *why* an AI reached a conclusion β€” not just what it said.
+</Accordion>
-Most frameworks stop at retrieval or generation. Semantica adds an **accountability layer**: every decision is recorded, every fact links to a source, and every reasoning step is explainable. It's designed for environments where you need to audit why an AI reached a conclusion.
+<Accordion title="Is Semantica free?" icon="tag">
+Yes β€” MIT licensed, no vendor lock-in. Some features require third-party API keys (e.g., OpenAI embeddings), but Semantica itself is always free.
+</Accordion>
-### Is Semantica free?
+<Accordion title="What's the latest version?" icon="star">
-Yes β€” MIT licensed, no vendor lock-in. Some features require third-party API keys (e.g., OpenAI embeddings), but Semantica itself is free.
+**v0.5.0** β€” released May 2026. Highlights: Ontology Hub, Distance Intelligence, Parquet/XML ingestion, 12 security fixes, Graph Explorer redesign.
+
+```bash
+pip install --upgrade semantica
+```
+
+</Accordion>
+
+</AccordionGroup>
---
+<AccordionGroup>
+
## Installation
-### How do I install Semantica?
+<Accordion title="How do I install Semantica?" icon="download">
```bash
pip install semantica
```
-See [Installation](installation.md) for virtual environment setup, optional extras, and troubleshooting.
+See [Installation](installation) for virtual environment setup, optional extras (`[gpu]`, `[all]`, provider-specific), and troubleshooting.
+</Accordion>
-### What Python version do I need?
+<Accordion title="What Python version do I need?" icon="python">
+Python **3.8 or higher**. Python 3.11+ is recommended for best performance.
+</Accordion>
-Python 3.8 or higher. Python 3.11+ is recommended for best performance.
+<Accordion title="The [all] extra fails on Windows" icon="windows">
+This was a known bug β€” fixed in **v0.5.0**. Upgrade:
-### What are the system requirements?
+```bash
+pip install --upgrade semantica
+```
+</Accordion>
-- Python 3.8+
-- 4 GB RAM minimum; 16 GB+ recommended for larger graphs
-- Optional GPU for embedding generation and ML inference
+<Accordion title="What are the system requirements?" icon="server">
----
+| Requirement | Minimum | Recommended |
+|-------------|---------|-------------|
+| Python | 3.8 | 3.11+ |
+| RAM | 4 GB | 16 GB+ |
+| GPU | Optional | CUDA for embeddings / ML |
-## Getting Started
+</Accordion>
-### Where do I start?
+</AccordionGroup>
-1. [Installation](installation.md) β€” get set up
-2. [Getting Started](getting-started.md) β€” core concepts and first example
-3. [Quickstart Tutorial](quickstart.md) β€” full step-by-step pipeline
-4. [Cookbook](cookbook.md) β€” interactive Jupyter notebooks
+---
-### What data sources does Semantica support?
+<AccordionGroup>
-- **Files** β€” PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives
-- **Web** β€” crawl with `WebIngestor`, RSS feeds
-- **Databases** β€” PostgreSQL, MySQL, Snowflake via `DBIngestor` / `SnowflakeIngestor`
-- **Streams** β€” Kafka, real-time ingestion
-- **Media** β€” image OCR, audio/video metadata
+## Data & Features
----
+<Accordion title="What data sources does Semantica support?" icon="database">
-## Features
+| Category | Sources |
+|----------|---------|
+| **Files** | PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, Parquet (v0.5.0), XML (v0.5.0), archives |
+| **Web** | `WebIngestor` crawl, RSS feeds |
+| **Databases** | PostgreSQL, MySQL, Snowflake via `DBIngestor` / `SnowflakeIngestor` |
+| **Streams** | Kafka, real-time ingestion |
+| **Protocols** | MCP (Model Context Protocol) |
-### Can I use my own models?
+</Accordion>
-Yes. Semantica supports custom entity extraction models, embedding models, LLM providers (via LiteLLM β€” 100+ models), and custom pipeline processors.
+<Accordion title="Can I use my own models?" icon="robot">
+Yes. Semantica supports custom entity extraction models, embedding models, LLM providers via LiteLLM (100+ models), and custom pipeline processors via the `PluginRegistry`.
+</Accordion>
-### Does Semantica support GPUs?
+<Accordion title="Does Semantica support GPUs?" icon="bolt">
+Yes. When available, GPUs are used automatically for embedding generation, ML model inference, and vector operations.
-Yes. When available, GPUs are used automatically for embedding generation, ML model inference, and vector operations. Install `semantica[gpu]` for CUDA support.
+```bash
+pip install "semantica[gpu]"
+```
+</Accordion>
-### How does Semantica handle large datasets?
+<Accordion title="How does Semantica handle large datasets?" icon="layer-group">
- **Batching** β€” process documents in configurable chunks
-- **Parallel processing** β€” `PipelineBuilder` supports configurable worker counts
+- **Parallel processing** β€” `Pipeline` supports configurable worker counts
- **Delta processing** β€” update graphs incrementally without full recompute
- **Graph backends** β€” swap in-memory NetworkX for Neo4j, FalkorDB, or Apache AGE at scale
+</Accordion>
+
+<Accordion title="What is Temporal Intelligence? (v0.4.0)" icon="clock">
+`TemporalKnowledgeGraph` attaches `valid_from`/`valid_until` to nodes and edges. Supports point-in-time queries, all 13 Allen interval algebra relations, and OWL-Time export.
+
+```python
+from semantica.kg import TemporalKnowledgeGraph
+
+tkg = TemporalKnowledgeGraph()
+tkg.add_temporal_triple("A", "caused", "B", valid_from="2024-01", valid_until="2024-06")
+snapshot = tkg.query_at_time("2024-03")
+```
+</Accordion>
+
+<Accordion title="What is the Ontology Hub? (v0.5.0)" icon="sitemap">
+A visual browser UI for the full ontology lifecycle β€” visual editor, SHACL Studio, alignment authoring, health dashboard, and version control. Launch via `semantica.explorer`.
+</Accordion>
+
+<Accordion title="What is Distance Intelligence? (v0.5.0)" icon="compass">
+Semantic neighborhood exploration for any graph node: NΓ—N distance matrices, ego-mode visualization, distance band classification (`near`/`mid`/`far`), and embedding cache optimization.
+</Accordion>
+
+<Accordion title="My NER extractor silently falls back to pattern mode on a custom gateway" icon="triangle-exclamation">
+Fixed in **v0.5.0**. The `response_format=json_object` parameter is now conditionally omitted for incompatible gateways, and a plain `generate()` + JSON parsing fallback is used automatically. Upgrade to fix.
+</Accordion>
+
+</AccordionGroup>
+
---
-## Technical
+<AccordionGroup>
-### What graph databases are supported?
+## Technical
+<Accordion title="What graph databases are supported?" icon="diagram-project">
Neo4j, FalkorDB, Apache AGE (PostgreSQL), Amazon Neptune, and in-memory NetworkX for development.
+</Accordion>
-### What export formats are available?
-
+<Accordion title="What export formats are available?" icon="file-export">
RDF (Turtle, JSON-LD, N-Triples, XML), Apache Parquet, ArangoDB AQL, CSV, YAML, and OWL ontologies.
+</Accordion>
+
+<Accordion title="What vector stores are supported?" icon="server">
+FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, and in-memory.
+</Accordion>
+
+<Accordion title="What LLM providers are supported?" icon="microchip">
+Groq, OpenAI, Anthropic, Google Gemini, Ollama (local), DeepSeek, Novita AI, LiteLLM (100+ models), and any OpenAI-compatible gateway.
+</Accordion>
-### Is Semantica production-ready?
+<Accordion title="Is Semantica production-ready?" icon="shield-check">
+Yes. v0.5.0 ships with:
-Yes. v0.3.0 ships with 886+ passing tests, `PipelineValidator`, `FailureHandler` with exponential backoff, W3C PROV-O provenance, and change management with checksums. See [What's New](index.md#whats-new-in-v030) for details.
+- 1,000+ passing tests
+- `PipelineValidator` and `FailureHandler` with exponential backoff
+- W3C PROV-O provenance tracking
+- Change management with SHA-256 checksums
+- 12 security vulnerability fixes (eval injection, pickle deserialization, SQL injection, XXE, SSRF, ReDoS, path traversal, and more)
+</Accordion>
+
+</AccordionGroup>
---
-## Troubleshooting
+<AccordionGroup>
-### Import error: `ModuleNotFoundError: No module named 'semantica'`
+## Troubleshooting
-Ensure you have the correct Python environment active, then:
+<Accordion title="ModuleNotFoundError: No module named 'semantica'" icon="xmark-circle">
+Ensure you have the correct Python environment active:
```bash
pip list | grep semantica
pip install --upgrade semantica
```
+</Accordion>
-### Installation fails with dependency errors
+<Accordion title="Installation fails with dependency errors" icon="xmark-circle">
```bash
pip install --upgrade pip wheel
pip install semantica
```
+</Accordion>
-### Memory errors during processing
-
+<Accordion title="Memory errors during processing" icon="memory">
Reduce batch sizes, enable streaming ingestion, or switch to a persistent graph backend (Neo4j, FalkorDB).
+</Accordion>
-### Slow embedding or inference
-
-Install GPU support (`pip install semantica[gpu]`) and ensure CUDA is available on your system.
-
----
+<Accordion title="Slow embedding or inference" icon="gauge-high">
+Install GPU support and ensure CUDA is available:
-## Support
+```bash
+pip install "semantica[gpu]"
+```
+</Accordion>
-### Where can I get help?
+<Accordion title="Unicode / cp1252 crash on Windows" icon="windows">
+Fixed in **v0.5.0**. Upgrade:
-- [Discord](https://discord.gg/sV34vps5hH) β€” community chat and support
-- [GitHub Issues](https://github.com/Hawksight-AI/semantica/issues) β€” bug reports and feature requests
-- [GitHub Discussions](https://github.com/Hawksight-AI/semantica/discussions) β€” questions and ideas
+```bash
+pip install --upgrade semantica
+```
+</Accordion>
-### How do I report a bug?
+</AccordionGroup>
-1. Search [existing issues](https://github.com/Hawksight-AI/semantica/issues) first
-2. Open a new issue with: description, reproduction steps, expected vs actual behavior, and your environment (Python version, OS, Semantica version)
+---
-### How do I contribute?
+## Support
-See the [Contributing Guide](contributing.md).
+<CardGroup cols={3}>
+ <Card title="Discord" icon="discord" href="https://discord.gg/sV34vps5hH">
+ Community chat and live support.
+ </Card>
+ <Card title="GitHub Issues" icon="github" href="https://github.com/Hawksight-AI/semantica/issues">
+ Bug reports and feature requests.
+ </Card>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ Help improve Semantica.
+ </Card>
+</CardGroup>
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 06c4443b..793d85f1 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -1,18 +1,31 @@
-# Getting Started
-
-**Semantica** is the context and intelligence layer for AI β€” turning raw data into explainable, auditable knowledge graphs for high-stakes domains.
+---
+title: "Getting Started"
+description: "The context and intelligence layer for AI β€” turning raw data into explainable, auditable knowledge graphs."
+icon: "rocket"
+---
-!!! tip "Just here for code?"
- Jump straight to the [Quick Start](#quick-start) or explore the [Cookbook](cookbook.md) for interactive notebooks.
+<Tip>
+ Just here for code? Jump straight to the [Quickstart Tutorial](quickstart) or explore the [Cookbook](cookbook) for interactive notebooks.
+</Tip>
---
## What You Can Build
-- **GraphRAG Systems** β€” enhanced retrieval with semantic graph reasoning
-- **AI Agents** β€” accountable agents with structured decision history and memory
-- **Knowledge Graphs** β€” production-ready semantic knowledge bases
-- **Compliance-Ready AI** β€” auditable systems with full W3C PROV-O provenance
+<CardGroup cols={2}>
+ <Card title="GraphRAG Systems" icon="diagram-project">
+ Enhanced retrieval with semantic graph reasoning β€” ground LLM responses in traceable, structured knowledge.
+ </Card>
+ <Card title="Accountable AI Agents" icon="robot">
+ Agents with structured decision history, causal chains, and precedent search. Every choice is recorded and auditable.
+ </Card>
+ <Card title="Production Knowledge Graphs" icon="sitemap">
+ Build, validate, and maintain enterprise-grade semantic knowledge bases from multi-source data.
+ </Card>
+ <Card title="Compliance-Ready AI" icon="shield-check">
+ W3C PROV-O provenance on every fact. HIPAA, SOX, GDPR, FDA 21 CFR Part 11 infrastructure built in.
+ </Card>
+</CardGroup>
---
@@ -39,21 +52,47 @@ print(semantica.__version__)
## Quick Start
-```python
+<CodeGroup>
+
+```python Knowledge Graph
+from semantica.ingest import FileIngestor
+from semantica.parse import DocumentParser
+from semantica.semantic_extract import NERExtractor, RelationExtractor
+from semantica.kg import GraphBuilder
+
+# Ingest β†’ Parse β†’ Extract β†’ Build
+ingestor = FileIngestor()
+sources = ingestor.ingest("data/sample.pdf")
+
+parser = DocumentParser()
+parsed = parser.parse(sources[0])
+
+ner = NERExtractor()
+entities = ner.extract(parsed)
+
+rel = RelationExtractor()
+relationships = rel.extract(parsed, entities=entities)
+
+graph = GraphBuilder(merge_entities=True).build(
+ entities=entities, relationships=relationships
+)
+print(f"{len(graph.nodes)} nodes, {len(graph.edges)} edges")
+```
+
+```python Agent Context
from semantica.context import AgentContext, ContextGraph
from semantica.vector_store import VectorStore
context = AgentContext(
vector_store=VectorStore(backend="faiss", dimension=768),
- vector_store=VectorStore(backend="inmemory"),
knowledge_graph=ContextGraph(advanced_analytics=True),
decision_tracking=True,
)
-# Store a memory
+# Store a memory with provenance
context.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%")
-# Record a decision
+# Record a decision with causal chain
decision_id = context.record_decision(
category="model_selection",
scenario="Choose LLM for production pipeline",
@@ -66,6 +105,33 @@ decision_id = context.record_decision(
precedents = context.find_precedents("model selection", limit=5)
```
+```python GraphRAG
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.reasoning import ReasoningEngine
+
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+)
+
+# Load your knowledge graph
+context.load_graph("company_kg.json")
+
+# Multi-hop GraphRAG query
+result = context.query(
+ "What companies were founded by people who worked at Apple?",
+ mode="graphrag",
+ reasoning=True,
+)
+
+# Every claim links back to a source node
+for claim in result.claims:
+ print(f"{claim.text} β†’ source: {claim.source_node}")
+```
+
+</CodeGroup>
+
---
## Core Architecture
@@ -85,15 +151,33 @@ Semantica uses a modular, layered architecture β€” import only what you need.
## Next Steps
-- [Core Concepts](concepts.md) β€” knowledge graphs, ontologies, reasoning explained
-- [Quickstart Tutorial](quickstart.md) β€” build a full pipeline step by step
-- [Cookbook](cookbook.md) β€” 14 domain-specific Jupyter notebook tutorials
-- [API Reference](reference/core.md) β€” complete module documentation
+<CardGroup cols={2}>
+ <Card title="Core Concepts" icon="book-open" href="concepts">
+ Knowledge graphs, ontologies, and reasoning explained in depth.
+ </Card>
+ <Card title="Quickstart Tutorial" icon="play" href="quickstart">
+ Full 6-step pipeline with `<Steps>` walkthrough.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ 40+ domain-specific Jupyter notebook tutorials.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/context">
+ Complete module documentation for every class and method.
+ </Card>
+</CardGroup>
---
## Help
-- [Discord Community](https://discord.gg/sV34vps5hH) β€” ask questions, share projects
-- [GitHub Issues](https://github.com/Hawksight-AI/semantica/issues) β€” report bugs or request features
-- [FAQ](faq.md) β€” common questions answered
+<CardGroup cols={3}>
+ <Card title="Discord" icon="discord" href="https://discord.gg/sV34vps5hH">
+ Ask questions, share projects, get community support.
+ </Card>
+ <Card title="GitHub Issues" icon="github" href="https://github.com/Hawksight-AI/semantica/issues">
+ Report bugs or request features.
+ </Card>
+ <Card title="FAQ" icon="circle-question" href="faq">
+ Common questions answered.
+ </Card>
+</CardGroup>
diff --git a/docs/glossary.md b/docs/glossary.md
index 4b42ad31..3908f369 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -1,222 +1,174 @@
-# Glossary
-
-Reference of terms and concepts used throughout Semantica.
+---
+title: "Glossary"
+description: "Reference of terms and concepts used throughout Semantica."
+icon: "book"
+---
-!!! tip "Finding a term"
- Use Ctrl+F to search this page.
+<Tip>
+ Use Ctrl+F to search this page.
+</Tip>
---
## Core Concepts
-### **Agent**
-An autonomous AI system that can perceive its environment, reason about information, and take actions to achieve specific goals. In Semantica, agents use knowledge graphs for memory and reasoning.
+**Agent** β€” An autonomous AI system that can perceive its environment, reason about information, and take actions to achieve specific goals. In Semantica, agents use knowledge graphs for memory and reasoning.
-### **Entity**
-A distinct object or concept in the real world, such as a person, place, organization, or event. Entities are the fundamental building blocks of knowledge graphs.
+**Entity** β€” A distinct object or concept in the real world, such as a person, place, organization, or event. Entities are the fundamental building blocks of knowledge graphs.
-### **Knowledge Graph (KG)**
-A structured representation of knowledge using entities (nodes) and relationships (edges). KGs enable reasoning, querying, and semantic analysis of data.
+**Knowledge Graph (KG)** β€” A structured representation of knowledge using entities (nodes) and relationships (edges). KGs enable reasoning, querying, and semantic analysis of data.
-### **Relationship**
-A connection between two entities that describes how they relate to each other (e.g., "works_for", "located_in", "founded_by").
+**Relationship** β€” A connection between two entities that describes how they relate to each other (e.g., `works_for`, `located_in`, `founded_by`).
-### **Semantic**
-Relating to meaning in language or logic. Semantic understanding goes beyond keywords to comprehend context and intent.
+**Semantic** β€” Relating to meaning in language or logic. Semantic understanding goes beyond keywords to comprehend context and intent.
---
## Data Processing
-### **Ingestion**
-The process of loading data from various sources (files, databases, APIs, streams) into a system for processing.
+**Ingestion** β€” The process of loading data from various sources (files, databases, APIs, streams) into a system for processing.
-### **Normalization**
-The process of standardizing data into a consistent format (e.g., converting dates to ISO format, standardizing entity names).
+**Normalization** β€” The process of standardizing data into a consistent format (e.g., converting dates to ISO format, standardizing entity names).
-### **Parsing**
-Extracting structured information from unstructured or semi-structured documents like PDFs, Word documents, or web pages.
+**Parsing** β€” Extracting structured information from unstructured or semi-structured documents like PDFs, Word documents, or web pages.
-### **Chunking**
-Breaking down large documents into smaller, manageable pieces while preserving context and meaning.
+**Chunking** β€” Breaking down large documents into smaller, manageable pieces while preserving context and meaning.
---
## Artificial Intelligence
-### **LLM (Large Language Model)**
-A type of artificial intelligence model trained on vast amounts of text data, capable of understanding and generating human-like text.
+**LLM (Large Language Model)** β€” A type of artificial intelligence model trained on vast amounts of text data, capable of understanding and generating human-like text.
-### **RAG (Retrieval Augmented Generation)**
-A technique that enhances LLM responses by retrieving relevant information from a knowledge base before generating an answer.
+**RAG (Retrieval Augmented Generation)** β€” A technique that enhances LLM responses by retrieving relevant information from a knowledge base before generating an answer.
-### **GraphRAG (Graph-Augmented Retrieval Augmented Generation)**
-An advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
+**GraphRAG (Graph-Augmented Retrieval Augmented Generation)** β€” An advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
-### **Inference**
-The process of deriving new facts or conclusions from existing knowledge using logical rules.
+**Inference** β€” The process of deriving new facts or conclusions from existing knowledge using logical rules.
---
## Knowledge Graph Components
-### **Node**
-A vertex in a graph representing an entity or concept.
+**Node** β€” A vertex in a graph representing an entity or concept.
+
+**Edge** β€” A connection between two nodes representing a relationship.
+
+**Property** β€” An attribute or characteristic of an entity or relationship (e.g., name, date, confidence score).
-### **Edge**
-A connection between two nodes representing a relationship.
+**Triplet** β€” A basic unit of knowledge in RDF, consisting of a subject, predicate, and object (e.g., `<Apple_Inc> <founded_by> <Steve_Jobs>`).
-### **Property**
-An attribute or characteristic of an entity or relationship (e.g., name, date, confidence score).
+**Temporal Graph** β€” A knowledge graph that tracks changes over time, allowing queries about the state of the graph at specific time points. Semantica's temporal model uses `valid_from`/`valid_until` on nodes and edges.
-### **Triplet**
-A basic unit of knowledge in RDF, consisting of a subject, predicate, and object (e.g., `<Apple_Inc> <founded_by> <Steve_Jobs>`).
+**BiTemporalFact** β€” A fact with both a valid time (when it was true in the world) and a transaction time (when it was recorded in the system).
-### **Temporal Graph**
-A knowledge graph that tracks changes over time, allowing queries about the state of the graph at specific time points.
+**Allen Interval Algebra** β€” A system of 13 relations for temporal ordering of intervals (before, after, meets, overlaps, during, starts, finishes, equals, and their inverses). Supported since v0.4.0.
---
## Entity Recognition & Extraction
-### **Named Entity Recognition (NER)**
-The process of identifying and classifying named entities in text into predefined categories such as persons, organizations, locations, dates, and more.
+**Named Entity Recognition (NER)** β€” The process of identifying and classifying named entities in text into predefined categories such as persons, organizations, locations, dates, and more.
-### **Relationship Extraction**
-The task of identifying and extracting semantic relationships between entities in text.
+**Relationship Extraction** β€” The task of identifying and extracting semantic relationships between entities in text.
-### **Entity Resolution**
-The process of determining when two entity mentions refer to the same real-world entity, also known as entity linking or deduplication.
+**Entity Resolution** β€” The process of determining when two entity mentions refer to the same real-world entity, also known as entity linking or deduplication.
-### **Coreference Resolution**
-The task of determining when two or more expressions in text refer to the same entity (e.g., "Apple" and "the company" referring to Apple Inc.).
+**Coreference Resolution** β€” The task of determining when two or more expressions in text refer to the same entity (e.g., "Apple" and "the company" referring to Apple Inc.).
-### **Event Detection**
-The task of identifying and classifying events (e.g., acquisitions, partnerships, announcements) in text.
+**Event Detection** β€” The task of identifying and classifying events (e.g., acquisitions, partnerships, announcements) in text.
---
## Ontology & Schema
-### **Ontology**
-A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).
+**Ontology** β€” A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).
-### **Class**
-In ontologies, a category or type of entity (e.g., `Person`, `Organization`, `Location`).
+**Ontology Hub** β€” Semantica's v0.5.0 visual browser UI for the full ontology lifecycle: visual editor, SHACL Studio, alignment authoring, health dashboard, and version control.
-### **Axiom**
-A statement or rule that is accepted as true without proof, used in ontologies to define logical constraints and relationships.
+**Class** β€” In ontologies, a category or type of entity (e.g., `Person`, `Organization`, `Location`).
-### **OWL (Web Ontology Language)**
-A W3C standard language for defining and instantiating ontologies on the web.
+**Axiom** β€” A statement or rule that is accepted as true without proof, used in ontologies to define logical constraints and relationships.
-### **Property**
-In ontologies, a relationship or attribute that connects entities or describes their characteristics.
+**OWL (Web Ontology Language)** β€” A W3C standard language for defining and instantiating ontologies on the web.
+
+**SHACL (Shapes Constraint Language)** β€” A W3C standard for validating RDF graphs against a set of shapes (constraints). Semantica can auto-generate and validate SHACL shapes.
+
+**SKOS (Simple Knowledge Organization System)** β€” A W3C standard for representing controlled vocabularies, taxonomies, and thesauri.
---
## Data Storage & Retrieval
-### **Embedding**
-A dense vector representation of text, images, or other data that captures semantic meaning in a continuous vector space. Used for similarity search and semantic matching.
+**Embedding** β€” A dense vector representation of text, images, or other data that captures semantic meaning in a continuous vector space. Used for similarity search and semantic matching.
-### **Vector Store**
-A database optimized for storing and searching high-dimensional vectors, used for semantic similarity search.
+**Vector Store** β€” A database optimized for storing and searching high-dimensional vectors, used for semantic similarity search.
-### **Triplet Store**
-A database designed specifically for storing and querying RDF triplets.
+**Triplet Store** β€” A database designed specifically for storing and querying RDF triplets.
-### **Graph Database**
-A database designed specifically for storing and querying graph-structured data.
+**Graph Database** β€” A database designed specifically for storing and querying graph-structured data.
-### **Hybrid Search**
-A search strategy that combines multiple retrieval methods, typically vector search and keyword search, to improve accuracy.
+**Hybrid Search** β€” A search strategy that combines multiple retrieval methods, typically vector search and keyword search, to improve accuracy.
---
## Graph Analytics
-### **Centrality**
-A measure of the importance or influence of a node in a graph. Common centrality metrics include PageRank, betweenness centrality, and closeness centrality.
+**Centrality** β€” A measure of the importance or influence of a node in a graph. Common metrics include PageRank, betweenness, and closeness centrality.
-### **PageRank**
-An algorithm used to measure the importance of nodes in a graph based on the structure of incoming links.
+**PageRank** β€” An algorithm used to measure the importance of nodes in a graph based on the structure of incoming links.
-### **Community Detection**
-The process of identifying groups or clusters of densely connected nodes in a graph.
+**Community Detection** β€” The process of identifying groups or clusters of densely connected nodes in a graph.
-### **Graph Analytics**
-The application of graph algorithms (e.g., centrality, community detection) to gain insights from the structure of a knowledge graph.
+**Distance Intelligence** β€” Semantica's v0.5.0 feature for semantic neighborhood exploration: NΓ—N distance matrices, ego-mode visualization, and distance band classification.
+
+**Distance Band** β€” A classification of a node's proximity to a target: `near`, `mid`, or `far`, based on semantic embedding distance thresholds.
---
## Query Languages
-### **Cypher**
-A declarative query language for graph databases, particularly Neo4j.
+**Cypher** β€” A declarative query language for graph databases, particularly Neo4j.
+
+**SPARQL** β€” A query language for RDF data, similar to SQL for relational databases.
-### **SPARQL**
-A query language for RDF data, similar to SQL for relational databases.
+**RDF (Resource Description Framework)** β€” A W3C standard for representing information about resources in the form of subject-predicate-object triplets.
-### **RDF (Resource Description Framework)**
-A W3C standard for representing information about resources in the form of subject-predicate-object triplets.
+**Datalog** β€” A declarative logic programming language used for knowledge base queries. Semantica's DatalogEngine supports recursive Horn clause rules with bottom-up semi-naive fixpoint semantics (v0.4.0).
---
## Data Quality
-### **Conflict Resolution**
-The process of handling contradictory information from multiple sources in a knowledge graph.
+**Conflict Resolution** β€” The process of handling contradictory information from multiple sources in a knowledge graph.
-### **Deduplication**
-The process of identifying and removing duplicate records or entities from a dataset.
+**Deduplication** β€” The process of identifying and removing duplicate records or entities from a dataset.
-### **Data Provenance**
-Information about the origin, history, and lineage of data, including sources, timestamps, and transformations.
+**Data Provenance** β€” Information about the origin, history, and lineage of data, including sources, timestamps, and transformations.
+
+**W3C PROV-O** β€” The W3C standard ontology for provenance. Semantica tracks lineage across all 17 modules in a PROV-O compliant format.
---
## Technical Terms
-### **API (Application Programming Interface)**
-A set of functions and protocols that allow different software applications to communicate with each other.
-
-### **OCR (Optical Character Recognition)**
-Technology that converts images of text (e.g., scanned documents, photos) into machine-readable text.
-
-### **Pipeline**
-A sequence of data processing steps that transform raw data into a desired output format.
-
-### **Vector**
-A mathematical representation of data as an array of numbers, used in embeddings to capture semantic meaning.
-
-### **Visualization**
-The graphical representation of data, such as knowledge graphs, embeddings, or analytics.
-
-### **Web Scraping**
-The automated process of extracting data from websites.
-
----
+**API (Application Programming Interface)** β€” A set of functions and protocols that allow different software applications to communicate with each other.
-## Semantica-Specific Terms
+**OCR (Optical Character Recognition)** β€” Technology that converts images of text (e.g., scanned documents, photos) into machine-readable text.
-### **Semantic Layer**
-An abstraction layer that provides a unified, business-friendly view of data by adding context, relationships, and meaning to raw data.
+**Pipeline** β€” A sequence of data processing steps that transform raw data into a desired output format.
-### **Semantic Network**
-A knowledge representation that uses a graph structure to represent concepts and their relationships.
+**Vector** β€” A mathematical representation of data as an array of numbers, used in embeddings to capture semantic meaning.
-### **Change Management**
-The process of tracking and managing changes to knowledge graphs over time, including version control and audit trails.
+**XXE (XML External Entity)** β€” A security vulnerability in XML parsers. Semantica's `XMLIngestor` (v0.5.0) uses an XXE-safe lxml backend.
-### **Provenance Tracking**
-W3C PROV-O compliant tracking of data lineage and source attribution.
+**SSRF (Server-Side Request Forgery)** β€” A security vulnerability where a server can be induced to make requests to unintended destinations. Semantica validates `base_url` at construction time to prevent SSRF.
---
## See Also
-- [Core Concepts](concepts.md) β€” deeper explanation of key ideas
-- [Getting Started](getting-started.md) β€” first steps
-- [Modules Guide](modules.md) β€” every module explained
-- [API Reference](reference/) β€” technical reference
+- [Core Concepts](concepts) β€” deeper explanation of key ideas
+- [Getting Started](getting-started) β€” first steps
+- [Modules Guide](modules) β€” every module explained
+- [API Reference](reference/context) β€” technical reference
diff --git a/docs/governance.md b/docs/governance.md
index 8702acc6..8708f070 100644
--- a/docs/governance.md
+++ b/docs/governance.md
@@ -1,18 +1,19 @@
-# Governance
-
-Project governance model for Semantica.
+---
+title: "Governance"
+description: "Project governance model β€” roles, decision process, release cadence, and code review guidelines."
+icon: "scale-balanced"
+---
-!!! info "Open Source"
- Semantica is maintained by Hawksight AI with community contributions.
+> Semantica is maintained by Hawksight AI with community contributions under an open governance model.
---
-## πŸ‘₯ Roles
+## Roles
**Maintainers** (Hawksight AI team)
- Review and merge pull requests
- Manage releases and code quality
-- Community management and project direction
+- Set project direction and community standards
**Contributors**
- Submit code, documentation, and bug reports
@@ -25,71 +26,82 @@ Project governance model for Semantica.
---
-## πŸ”„ Decision Process
+## Decision Process
### Code Changes
-1. Proposal via GitHub Issues
-2. Community discussion
-3. Implementation (PR)
-4. Review by maintainers
-5. Approval (at least 1 maintainer)
-6. Merge after CI passes
+
+<Steps>
+ <Step title="Proposal">Open a GitHub Issue describing the change.</Step>
+ <Step title="Discussion">Community discussion on approach and scope.</Step>
+ <Step title="Implementation">Submit a pull request with the change.</Step>
+ <Step title="Review">At least one maintainer reviews the PR.</Step>
+ <Step title="Merge">Merged after CI passes and maintainer approval.</Step>
+</Steps>
### Major Decisions
-- RFC in GitHub Issues
-- 1 week minimum discussion
+
+- RFC posted in GitHub Issues
+- Minimum 1-week community discussion period
- Maintainers decide based on community feedback and technical feasibility
---
-## πŸ“¦ Releases
+## Releases
-### Versioning (Semantic Versioning)
-- **MAJOR**: Breaking changes
-- **MINOR**: New features (backward compatible)
-- **PATCH**: Bug fixes (backward compatible)
+Semantica follows **Semantic Versioning** (`MAJOR.MINOR.PATCH`):
-### Schedule
-- **Major**: Quarterly or as needed
-- **Minor**: Monthly or when ready
-- **Patch**: As bugs are fixed
+| Level | Trigger | Cadence |
+|-------|---------|---------|
+| MAJOR | Breaking changes | Quarterly or as needed |
+| MINOR | New features (backward compatible) | Monthly or when ready |
+| PATCH | Bug fixes (backward compatible) | As bugs are fixed |
---
-## πŸ” Code Review
+## Code Review
+
+**Review criteria:** functionality, code quality, tests, documentation, performance, security.
-**Criteria**: Functionality, code quality, tests, documentation, performance, security
+**Timeline:** initial review within 48 hours; follow-up within 7 days.
-**Timeline**: Initial review within 48 hours, follow-up within 7 days
+**Guidelines for reviewers:** be constructive, explain reasoning, suggest alternatives.
-**Guidelines**:
-- Reviewers: Be constructive, explain reasoning
-- Contributors: Address comments, ask questions, be open to feedback
+**Guidelines for contributors:** address comments promptly, ask questions when unclear, be open to feedback.
---
-## πŸ’¬ Communication
+## Communication
-- **GitHub Issues**: Bug reports, features, questions
-- **GitHub PRs**: Code contributions
-- **GitHub Security Advisories**: [Report security issues](https://github.com/Hawksight-AI/semantica/security/advisories/new)
+- **GitHub Issues** β€” bug reports, feature requests, questions
+- **GitHub PRs** β€” code contributions
+- **GitHub Discussions** β€” community conversation
+- **Security Advisories** β€” [report security issues privately](https://github.com/Hawksight-AI/semantica/security/advisories/new)
---
-## 🎯 Project Goals
+## Project Goals
-1. **Usability** - Easy to use and understand
-2. **Reliability** - Production-ready quality
-3. **Performance** - Efficient and scalable
-4. **Extensibility** - Easy to extend
-5. **Community** - Welcoming and inclusive
+1. **Usability** β€” Easy to use and understand
+2. **Reliability** β€” Production-ready quality
+3. **Performance** β€” Efficient and scalable
+4. **Extensibility** β€” Easy to extend with plugins and custom modules
+5. **Community** β€” Welcoming and inclusive
---
-## πŸ“„ License
+## License
-MIT License - See [LICENSE](https://github.com/Hawksight-AI/semantica/blob/main/LICENSE)
+MIT License β€” see [LICENSE](https://github.com/Hawksight-AI/semantica/blob/main/LICENSE) and the [License page](license).
---
-**Contact**: [GitHub Issues](https://github.com/Hawksight-AI/semantica/issues)
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ How to submit changes.
+ </Card>
+ <Card title="Community" icon="users" href="community">
+ Community guidelines and channels.
+ </Card>
+</CardGroup>
diff --git a/docs/graph_stores/apache_age.md b/docs/graph_stores/apache_age.md
index 27c16a9d..82341a64 100644
--- a/docs/graph_stores/apache_age.md
+++ b/docs/graph_stores/apache_age.md
@@ -1,6 +1,10 @@
-# Apache AGE Graph Store
+---
+title: "Apache AGE Graph Store"
+description: "PostgreSQL + Apache AGE backend for openCypher queries alongside standard SQL."
+icon: "database"
+---
-**Backend**: PostgreSQL + [Apache AGE](https://age.apache.org/)
+**Backend**: PostgreSQL + [Apache AGE](https://age.apache.org/)
**Driver**: `psycopg2`
Apache AGE is a PostgreSQL extension that adds graph database functionality, enabling you to run openCypher queries alongside traditional SQL. This backend lets Semantica use AGE as a property graph store with the same interface as Neo4j and FalkorDB.
@@ -19,7 +23,7 @@ Apache AGE is a PostgreSQL extension that adds graph database functionality, ena
pip install psycopg2-binary
```
-> **Note**: Apache AGE must be compiled and installed into your PostgreSQL instance. See the [AGE installation guide](https://age.apache.org/age-manual/master/intro/setup.html).
+<Note>Apache AGE must be compiled and installed into your PostgreSQL instance. See the [AGE installation guide](https://age.apache.org/age-manual/master/intro/setup.html).</Note>
---
@@ -121,7 +125,7 @@ node = store.create_node(
# node["properties"]["semantica_id"] β†’ "doc-abc-123"
```
-> **Important**: Never mix AGE internal IDs with semantic IDs. Use `node["id"]` for graph operations (delete, update, traverse) and `node["properties"]["semantica_id"]` for application-level lookups.
+<Warning>Never mix AGE internal IDs with semantic IDs. Use `node["id"]` for graph operations (delete, update, traverse) and `node["properties"]["semantica_id"]` for application-level lookups.</Warning>
---
diff --git a/docs/index.md b/docs/index.md
index 1db88690..bdd3b327 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,79 +1,67 @@
-<div align="center">
- <img src="assets/img/Semantica Logo.png" alt="Semantica Logo" width="420" height="auto">
-
- <h1>🧠 Semantica</h1>
-
- <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.8+-blue.svg" alt="Python 3.8+"></a>
- <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
- <a href="https://pypi.org/project/semantica/"><img src="https://img.shields.io/pypi/v/semantica.svg" alt="PyPI"></a>
- <a href="https://github.com/Hawksight-AI/semantica/releases/tag/v0.4.0"><img src="https://img.shields.io/badge/version-0.4.0-brightgreen.svg" alt="Version"></a>
- <a href="https://pepy.tech/project/semantica"><img src="https://static.pepy.tech/badge/semantica" alt="Total Downloads"></a>
- <a href="https://github.com/Hawksight-AI/semantica/actions"><img src="https://github.com/Hawksight-AI/semantica/workflows/CI/badge.svg" alt="CI"></a>
- <a href="https://discord.gg/sV34vps5hH"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Discord"></a>
- <a href="https://x.com/BuildSemantica"><img src="https://img.shields.io/badge/X-Follow-black?logo=x&logoColor=white" alt="X"></a>
-
- <p><strong>A Framework for Building Context Graphs and Decision Intelligence Layers for AI</strong></p>
-
- <p>⭐ Give us a Star &nbsp;β€’&nbsp; 🍴 Fork us &nbsp;β€’&nbsp; πŸ’¬ Join our Discord &nbsp;β€’&nbsp; 🐦 Follow on X</p>
+---
+title: "Semantica"
+description: "The Accountability and Context Layer for AI β€” Context Graphs Β· Decision Intelligence Β· Full Provenance"
+---
- <p><em>Transform Chaos into Intelligence. Build AI systems with context graphs, decision tracking, and advanced knowledge engineering that are explainable, traceable, and trustworthy β€” not black boxes.</em></p>
+<Info>
+ **v0.5.0 is live** β€” Ontology Hub, Distance Intelligence, SHACL Studio, Parquet & XML ingestion, 12 security fixes. [What's new β†’](#whats-new)
+</Info>
- <p>
- <a href="getting-started/" class="md-button md-button--primary">Get Started</a>
- <a href="https://github.com/Hawksight-AI/semantica" class="md-button">View on GitHub</a>
- </p>
-</div>
+> Most AI agents act without a trail. Semantica adds the layer your stack is missing: structured context graphs, auditable decision records, and full provenance from every output back to its source β€” so your AI isn't just powerful, it's accountable.
---
## The Problem
-AI agents today are capable but not trustworthy:
+AI agents today are powerful but not trustworthy. Five structural gaps make them impossible to deploy in regulated environments:
-- **No memory structure** β€” agents store embeddings, not meaning. Retrieval is fuzzy; there's no way to ask *why* something was recalled.
-- **No decision trail** β€” agents make decisions continuously but record nothing. When something goes wrong, there's no history to debug or audit.
-- **No provenance** β€” outputs cannot be traced back to source facts. In regulated industries, this is a compliance blocker.
-- **No reasoning transparency** β€” black-box answers with no explanation of how a conclusion was reached.
-- **No conflict detection** β€” contradictory facts silently coexist in vector stores, producing unpredictable answers.
+- **No memory structure** β€” agents store embeddings, not meaning. There's no way to ask *why* something was recalled or trace a fact to its source.
+- **No decision trail** β€” agents act continuously but record nothing. When something breaks, there's no history to debug or audit.
+- **No provenance** β€” outputs can't be traced back to source facts. In healthcare, finance, and legal, this is a hard compliance blocker.
+- **No reasoning transparency** β€” black-box answers with zero explanation of how a conclusion was reached.
+- **No conflict detection** β€” contradictory facts silently coexist in vector stores, producing unpredictable and inconsistent outputs.
-These aren't edge cases. They are the reason AI cannot be deployed in healthcare, finance, legal, and government without custom guardrails built from scratch.
+These aren't edge cases. They are why AI cannot be deployed in healthcare, finance, legal, and government without custom guardrails built from scratch.
---
## The Solution
-Semantica is the **context and intelligence layer** you add to your AI stack:
+Semantica is the **accountability and context layer** you add on top of your existing AI stack β€” not a replacement for LangChain or LlamaIndex, but the infrastructure that makes their outputs trustworthy.
-- **Context Graphs** β€” structured graph of entities, relationships, and decisions your agent builds as it works. Queryable, traceable, persistent.
-- **Decision Intelligence** β€” every decision is a first-class object: recorded, linked causally, searchable by precedent, and analyzable for downstream impact.
-- **Provenance** β€” every fact links to its source. W3C PROV-O compliant. Full lineage from ingestion to inference.
-- **Reasoning engines** β€” forward chaining, Rete networks, deductive, abductive, and SPARQL reasoning. Explainable inference paths, not black-box answers.
-- **Deduplication & QA** β€” conflict detection, entity resolution, and validation built into the pipeline.
+- **Context Graphs** β€” a structured, queryable graph of everything your agent knows, decides, and reasons about. Persistent across runs.
+- **Decision Intelligence** β€” every decision is a first-class object: recorded, causally linked, searchable by precedent, and analyzable for downstream impact.
+- **Full Provenance** β€” every fact links back to its source. W3C PROV-O compliant. Full lineage from ingestion to inference.
+- **Reasoning Engines** β€” forward chaining, Rete, deductive, abductive, SPARQL, Datalog. Explainable paths, not black boxes.
+- **Temporal Intelligence** β€” point-in-time queries, Allen interval algebra, temporal provenance, OWL-Time export.
+- **Ontology Hub** β€” visual editor, SHACL Studio, alignment authoring, health dashboard. Full ontology lifecycle in the browser.
-Works alongside LangChain, LlamaIndex, AutoGen, CrewAI, and any LLM provider β€” Semantica is not a replacement, it's the accountability layer on top.
+Works alongside any LLM provider and any agent framework β€” Semantica is not a replacement, it's the accountability layer on top.
---
-### ⚑ Quick Installation
+## Quick Start
```bash
pip install semantica
```
-```python
+<CodeGroup>
+
+```python OpenAI
from semantica.context import AgentContext, ContextGraph
from semantica.vector_store import VectorStore
+from semantica.llms import OpenAIProvider
context = AgentContext(
- vector_store=VectorStore(backend="faiss", dimension=768),
+ vector_store=VectorStore(backend="faiss", dimension=1536),
knowledge_graph=ContextGraph(advanced_analytics=True),
decision_tracking=True,
+ llm=OpenAIProvider(model="gpt-4o"),
)
-# Store a memory
context.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%")
-# Record a decision
decision_id = context.record_decision(
category="model_selection",
scenario="Choose LLM for production reasoning pipeline",
@@ -82,252 +70,241 @@ decision_id = context.record_decision(
confidence=0.91,
)
-# Find similar past decisions and analyze downstream impact
precedents = context.find_precedents("model selection reasoning", limit=5)
influence = context.analyze_decision_influence(decision_id)
```
-**[Full Quick Start](getting-started.md)** &nbsp;β€’&nbsp; **[Cookbook](cookbook.md)** &nbsp;β€’&nbsp; **[Join Discord](https://discord.gg/sV34vps5hH)**
+```python Anthropic
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import AnthropicProvider
----
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=1024),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+ decision_tracking=True,
+ llm=AnthropicProvider(model="claude-opus-4-7"),
+)
-## What's New in v0.3.0
+context.store("Claude excels at long-context reasoning and code generation")
-> First stable release (`Production/Stable` on PyPI).
+decision_id = context.record_decision(
+ category="model_selection",
+ scenario="Choose LLM for document analysis pipeline",
+ reasoning="Claude's 200k context window eliminates chunking overhead",
+ outcome="selected_claude",
+ confidence=0.94,
+)
-| Area | Highlights |
-|------|------------|
-| **Context Graphs** | Temporal validity windows, weighted BFS, cross-graph navigation with save/load persistence |
-| **Decision Intelligence** | Full lifecycle: record β†’ trace β†’ impact β†’ precedent; `PolicyEngine` with versioned rules |
-| **KG Algorithms** | PageRank, betweenness, Louvain community detection, Node2Vec, link prediction |
-| **Semantic Extraction** | LLM extraction fixed (no silent drops), duplicate relation bug removed, `"llm_typed"` metadata corrected |
-| **Deduplication v2** | `blocking_v2`/`hybrid_v2` β€” 63.6% faster; semantic v2 β€” 6.98x faster |
-| **Delta Processing** | SPARQL-based incremental diff, `delta_mode` pipelines, snapshot versioning |
-| **Export** | RDF aliases (`"ttl"`, `"json-ld"`), ArangoDB AQL, Apache Parquet (Spark/BigQuery/Databricks) |
-| **Pipeline** | `FailureHandler` with LINEAR/EXPONENTIAL/FIXED backoff; `PipelineValidator` returning `ValidationResult` |
-| **Graph Backends** | Apache AGE (SQL injection fixed), AWS Neptune, FalkorDB, PgVector (HNSW/IVFFlat) |
-| **Tests** | 886+ passing, 0 failures β€” 335 context, ~430 KG, 70 semantic extraction, 85 real-world E2E |
+precedents = context.find_precedents("document analysis model", limit=5)
+```
----
+```python Ollama (Local)
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+from semantica.llms import OllamaProvider
-## Core Value Proposition
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+ decision_tracking=True,
+ llm=OllamaProvider(model="llama3.2", base_url="http://localhost:11434"),
+)
-| **Trustworthy** | **Explainable** | **Auditable** |
-|:---:|:---:|:---:|
-| Conflict detection & validation | Transparent reasoning paths | Complete provenance tracking |
-| Rule-based governance | Entity relationships & ontologies | W3C PROV-O compliant lineage |
-| Production-grade QA | Multi-hop graph reasoning | Source tracking & integrity verification |
+# Fully local β€” no data leaves your infrastructure
+context.store("Local LLMs enable air-gapped compliance deployments")
----
+decision_id = context.record_decision(
+ category="deployment_model",
+ scenario="Choose inference strategy for on-prem environment",
+ reasoning="Air-gap requirement eliminates cloud API options",
+ outcome="local_inference",
+ confidence=0.99,
+)
+```
-## Features
+</CodeGroup>
-### Context & Decision Intelligence
-- **Context Graphs** β€” structured, persistent graph of entities, relationships, and decisions
-- **Decision tracking** β€” `add_decision()`, `record_decision()` for full lifecycle management
-- **Causal chains** β€” `add_causal_relationship()`, `trace_decision_chain()`
-- **Precedent search** β€” hybrid similarity search over past decisions via `find_similar_decisions()`
-- **Influence analysis** β€” `analyze_decision_impact()`, `analyze_decision_influence()`
-- **Policy engine** β€” `check_decision_rules()` with versioned, automated compliance rules
-- **Agent memory** β€” `AgentMemory` with short/long-term storage and conversation history
-
-### Knowledge Graphs
-- **Graph construction** β€” entities, relationships, properties, typed edges
-- **Algorithms** β€” PageRank, betweenness centrality, clustering coefficient, community detection
-- **Node embeddings** β€” Node2Vec via `NodeEmbedder`; cosine similarity via `SimilarityCalculator`
-- **Link prediction** β€” score potential edges via `LinkPredictor`
-- **Temporal graphs** β€” time-aware nodes and edges with validity windows
-- **Delta processing** β€” incremental updates without full recompute
-
-### Semantic Extraction
-- **NER** β€” named entity recognition, normalization, classification
-- **Relation extraction** β€” triplet generation via LLMs or rule-based methods, with `"llm_typed"` metadata
-- **Deduplication v1/v2** β€” Jaro-Winkler, `blocking_v2`, `hybrid_v2`, `semantic_v2`; `dedup_triplets()` for triples
-
-### Reasoning
-- **Forward chaining** β€” `Reasoner` with IF/THEN string rules and dict facts
-- **Rete network** β€” `ReteEngine` for high-throughput production rule matching
-- **Deductive / Abductive** β€” `DeductiveReasoner`, `AbductiveReasoner`
-- **SPARQL** β€” `SPARQLReasoner` for query-based inference over RDF graphs
-
-### Provenance & Auditability
-- **Entity provenance** β€” `ProvenanceTracker.track_entity()`
-- **Algorithm provenance** β€” `AlgorithmTrackerWithProvenance`
-- **W3C PROV-O compliant** β€” lineage tracking across all modules
-- **Change management** β€” version control with checksums, audit trails, compliance support
-
-### Vector Store
-- **Backends** β€” FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory
-- **Search modes** β€” semantic top-k, hybrid (vector + keyword), metadata-filtered
-
-### Data Ingestion
-- **Files** β€” PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives
-- **Sources** β€” web crawl, SQL databases, Snowflake, feeds, email, repositories
-- **Docling** β€” advanced parsing with table and layout extraction
-- **Media** β€” image OCR, audio/video metadata
-
-### Export
-- **RDF** β€” Turtle, JSON-LD, N-Triples, XML via `RDFExporter`
-- **Parquet** β€” `ParquetExporter` for Spark/BigQuery/Databricks pipelines
-- **ArangoDB AQL** β€” ready-to-run INSERT statements
-- **OWL ontologies** β€” Turtle or RDF/XML
-
-### Pipeline & Ontology
-- **Pipeline DSL** β€” `PipelineBuilder` with stage chaining, parallel workers, retry policies
-- **Ontology** β€” auto-generate OWL from KGs, import OWL/RDF/Turtle/JSON-LD, HermiT/Pellet validation
+<CardGroup cols={3}>
+ <Card title="Full Quickstart" icon="rocket" href="quickstart">
+ Step-by-step pipeline walkthrough.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ 40+ real-world Jupyter notebooks.
+ </Card>
+ <Card title="Join Discord" icon="discord" href="https://discord.gg/sV34vps5hH">
+ Community chat and support.
+ </Card>
+</CardGroup>
---
-## Modules
+## What's New
-| Module | What it provides |
-|--------|-----------------|
-| `semantica.context` | Context graphs, agent memory, decision tracking, causal analysis, precedent search, policy engine |
-| `semantica.kg` | KG construction, graph algorithms, centrality, community detection, embeddings, link prediction |
-| `semantica.semantic_extract` | NER, relation extraction, event extraction, coreference, triplet generation, LLM extraction |
-| `semantica.reasoning` | Forward chaining, Rete network, deductive, abductive, SPARQL reasoning, explanation generation |
-| `semantica.vector_store` | FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector; hybrid & filtered search |
-| `semantica.export` | RDF, Parquet, ArangoDB AQL, CSV, YAML, OWL, graph formats |
-| `semantica.ingest` | Files, web crawl, feeds, databases, Snowflake, MCP, email, repositories |
-| `semantica.ontology` | Auto-generation, OWL/RDF export, import, validation, versioning |
-| `semantica.pipeline` | Pipeline DSL, parallel workers, validation, retry policies, failure handling |
-| `semantica.graph_store` | Neo4j, FalkorDB, Apache AGE, Amazon Neptune; Cypher queries |
-| `semantica.embeddings` | Sentence-Transformers, FastEmbed, OpenAI, BGE; similarity calculation |
-| `semantica.deduplication` | Entity deduplication, similarity scoring, merging, clustering |
-| `semantica.provenance` | W3C PROV-O lineage tracking, source attribution, audit trails |
-| `semantica.parse` | PDF, DOCX, PPTX, HTML, code, email, structured data, OCR |
-| `semantica.split` | Recursive, semantic, entity-aware, relation-aware, graph-based chunking |
-| `semantica.normalize` | Text, entities, dates, numbers, quantities, languages, encodings |
-| `semantica.conflicts` | Multi-source conflict detection (value, type, temporal, logical) with resolution |
-| `semantica.change_management` | Version storage, change tracking, checksums, audit trails |
-| `semantica.triplet_store` | Blazegraph, Jena, RDF4J; SPARQL queries and bulk loading |
-| `semantica.visualization` | Interactive/static KG, ontology, embedding, and temporal graph visualization |
-| `semantica.core` | Framework orchestration, configuration, plugin system |
-| `semantica.llms` | Groq, OpenAI, Novita AI, HuggingFace, LiteLLM integrations |
+<AccordionGroup>
----
+<Accordion title="v0.5.0 β€” Ontology Hub & Distance Intelligence" icon="star" defaultOpen={true}>
-## Built for High-Stakes Domains
+Released **May 11, 2026**
-Where **every decision must be accountable** and **mistakes have real consequences**:
+| Area | Highlights |
+|------|------------|
+| **Ontology Hub** | Visual editor, SHACL Studio, alignment authoring, health dashboard, version control β€” full ontology lifecycle in the browser |
+| **Distance Intelligence** | Semantic neighborhoods, NΓ—N distance matrices, ego-mode visualization, distance band classification, embedding cache optimization |
+| **Parquet Ingestion** | `ParquetIngestor` with PyArrow β€” single file, partitioned directories, Hive-style discovery, selective column reading |
+| **XML Ingestion** | `XMLIngestor` with XXE-safe lxml backend, XSD/DTD validation, namespace handling, directory scanning |
+| **Graph Explorer** | Landing page redesign, bidirectional path finding, indexed search (0.004ms on 118k nodes) |
+| **Security** | 12 vulnerability fixes: eval injection, pickle deserialization, SQL injection, XXE, SSRF, ReDoS, path traversal |
+| **Bug Fixes** | NER LLM silent fallback on enterprise gateways, ConflictDetector duplicate definition, Windows `[all]` install, cp1252 crash |
-- **πŸ₯ Healthcare & Life Sciences** β€” Clinical decision support, drug interactions, patient safety
-- **πŸ’° Finance & Risk** β€” Fraud detection, SOX/GDPR/MiFID II compliance, risk assessment
-- **βš–οΈ Legal & Compliance** β€” Evidence-backed research, contract analysis, regulatory tracking
-- **πŸ”’ Cybersecurity** β€” Threat attribution, incident response, security audit trails
-- **πŸ›οΈ Government & Defense** β€” Policy decisions, classified information handling, defense intelligence
-- **🏭 Critical Infrastructure** β€” Power grids, transportation safety, emergency response
-- **πŸš— Autonomous Systems** β€” Self-driving, robotics safety, industrial automation
+```bash
+pip install semantica==0.5.0
+```
----
+</Accordion>
+
+<Accordion title="v0.4.0 β€” Temporal Intelligence & Knowledge Explorer" icon="clock">
-## Choose Your Path
+| Area | Highlights |
+|------|------------|
+| **Temporal Intelligence** | 6-PR system: temporal data model, point-in-time queries, Allen interval algebra (all 13 relations), OWL-Time export |
+| **Knowledge Explorer API** | Full FastAPI backend β€” 99 tests, 12 export formats, WebSocket progress, thread-safe sessions, audit trail |
+| **Ontology Foundations** | SHACL generation/validation, SKOS vocabulary, ontology alignment API, diff & migration tooling |
+| **Datalog Reasoning** | Pure-Python bottom-up semi-naive fixpoint, recursive Horn clause rules, guaranteed termination |
+| **Agno Integration** | 5 components: graph-backed memory, multi-hop GraphRAG, decision toolkit, KG toolkit, shared team context; 110 tests |
-<div class="grid cards" markdown>
+</Accordion>
-- :material-rocket-launch: **Quick Start**
- ---
- Up and running in minutes.
+</AccordionGroup>
+
+---
- [:arrow_right: Start Here](getting-started.md)
+## Start Here
-- :material-book-open-page-variant: **Core Concepts**
- ---
+<CardGroup cols={2}>
+ <Card title="Quickstart" icon="rocket" href="quickstart">
+ Build a complete knowledge graph pipeline in 5 minutes.
+ </Card>
+ <Card title="Core Concepts" icon="book-open" href="concepts">
Knowledge graphs, ontologies, and semantic reasoning explained.
+ </Card>
+ <Card title="API Reference" icon="rectangle-terminal" href="reference/context">
+ Full documentation for every module, class, and method.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ 40+ domain-specific notebooks β€” healthcare, finance, legal, and more.
+ </Card>
+</CardGroup>
- [:arrow_right: Learn Concepts](concepts.md)
+---
-- :material-code-braces: **API Reference**
- ---
- Full technical documentation for every module and class.
+## Capabilities
- [:arrow_right: View API](reference/core.md)
+<AccordionGroup>
-- :material-chef-hat: **Cookbook**
- ---
- 14 domain-specific cookbooks with real-world examples.
+<Accordion title="Context & Decision Intelligence" icon="brain">
- [:arrow_right: Explore Cookbook](cookbook.md)
+- **Context Graphs** β€” structured, persistent graph of entities, relationships, and decisions
+- **Decision tracking** β€” `record_decision()` for full lifecycle management with causal chains
+- **Precedent search** β€” hybrid similarity search over past decisions for consistency
+- **Influence analysis** β€” `analyze_decision_impact()`, `analyze_decision_influence()`
+- **Temporal graphs** β€” `valid_from`/`valid_until` on nodes and edges, point-in-time queries
+- **Distance Intelligence** β€” semantic neighborhoods, NΓ—N distance matrices, ego-mode exploration
-</div>
+</Accordion>
----
+<Accordion title="Knowledge Engineering" icon="diagram-project">
-## Installation
+- **NER** β€” named entity recognition with pattern, ML, or LLM methods
+- **Relation extraction** β€” typed triplets via LLM or rule-based methods
+- **Deduplication v2** β€” `blocking_v2`, `hybrid_v2`, `semantic_v2` β€” up to 7x faster
+- **Ontology Hub** β€” visual editor, SHACL Studio, alignments, health dashboard
+- **Datalog reasoning** β€” recursive Horn clause rules with fixpoint semantics
+- **SPARQL reasoning** β€” query-based inference over RDF graphs
-!!! success "Now Available on PyPI!"
- Install with a single command.
+</Accordion>
-=== "PyPI (Recommended)"
+<Accordion title="Provenance & Auditability" icon="shield-check">
- ```bash
- pip install semantica
+- **W3C PROV-O** β€” lineage tracking across all 17 modules
+- **Change management** β€” version control with SHA-256 checksums and audit trails
+- **Temporal provenance** β€” `recorded_at` stamping, OWL-Time export
+- **Compliance** β€” HIPAA, SOX, GDPR, FDA 21 CFR Part 11 infrastructure
- # With all optional dependencies
- pip install semantica[all]
- ```
+</Accordion>
-=== "From Source"
+<Accordion title="Data Ingestion & Export" icon="database">
- ```bash
- git clone https://github.com/Hawksight-AI/semantica.git
- cd semantica
- pip install -e . # core
- pip install -e ".[all]" # all extras
- ```
+**Ingestion:** PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, Parquet, XML, archives, web crawl, SQL, Snowflake, feeds, email, repositories, MCP
-=== "Development"
+**Vector Stores:** FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory
- ```bash
- git clone https://github.com/Hawksight-AI/semantica.git
- cd semantica
- pip install -e ".[dev]"
- ```
+**Export:** RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, OWL ontologies
-=== "Docker"
+**Graph Stores:** Neo4j, FalkorDB, Apache AGE, Amazon Neptune
- ```bash
- docker pull semantica/semantica:latest
- docker run -it semantica/semantica
- ```
+</Accordion>
+
+</AccordionGroup>
---
-## Why Semantica?
+## Module Reference
+
+| Module | What it provides |
+|--------|-----------------|
+| `semantica.context` | Context graphs, agent memory, decision tracking, causal analysis, precedent search |
+| `semantica.kg` | KG construction, graph algorithms, temporal model, Allen interval algebra |
+| `semantica.semantic_extract` | NER, relation extraction, event extraction, triplet generation |
+| `semantica.reasoning` | Forward chaining, Rete, deductive, abductive, SPARQL, Datalog |
+| `semantica.ontology` | SHACL, SKOS, alignments, diff/migration, auto-generation, OWL/RDF |
+| `semantica.explorer` | FastAPI Knowledge Explorer, Ontology Hub, Distance Intelligence, SHACL Studio |
+| `semantica.mcp_server` | MCP stdio server β€” 12 tools for Claude Desktop, VS Code, Cursor, Windsurf, Cline |
+| `semantica.vector_store` | FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector |
+| `semantica.graph_store` | Neo4j, FalkorDB, Apache AGE, Amazon Neptune |
+| `semantica.triplet_store` | In-memory and persistent RDF triple store |
+| `semantica.ingest` | Files, web, feeds, databases, Snowflake, Parquet, XML, MCP |
+| `semantica.parse` | Document parsing β€” PDF, DOCX, HTML, PPTX; Docling layout analysis |
+| `semantica.split` | Text chunking β€” sentence, paragraph, token, semantic boundary strategies |
+| `semantica.normalize` | Text normalization, entity canonicalization, whitespace and encoding cleanup |
+| `semantica.embeddings` | Sentence-Transformers, FastEmbed, OpenAI, BGE |
+| `semantica.pipeline` | Pipeline DSL, parallel workers, retry policies, failure handling |
+| `semantica.export` | RDF, Parquet, ArangoDB AQL, CSV, OWL, graph formats |
+| `semantica.visualization` | Programmatic graph rendering β€” force, hierarchical, circular layouts |
+| `semantica.deduplication` | Entity deduplication v1/v2, similarity scoring, blocking, merging |
+| `semantica.conflicts` | Conflict detection and resolution across overlapping knowledge sources |
+| `semantica.provenance` | W3C PROV-O lineage tracking, source attribution, audit trails |
+| `semantica.change_management` | Version control with SHA-256 checksums, diff, rollback |
+| `semantica.llms` | Groq, OpenAI, Anthropic, Gemini, Ollama, DeepSeek, Novita AI, LiteLLM |
+| `semantica.seed` | Deterministic data seeding and synthetic graph generation for tests |
+| `semantica.evals` | Evaluation harness β€” precision, recall, F1 for extraction and reasoning |
+| `semantica.utils` | Shared utilities β€” ID generation, date parsing, schema helpers |
+| `semantica.core` | Core data models, base classes, shared type definitions |
+
+---
-<div class="grid cards" markdown>
+## Built for High-Stakes Domains
-- **πŸ†“ Open Source**
- ---
- MIT licensed. No vendor lock-in.
+Where every decision must be accountable and mistakes have real consequences:
-- **πŸš€ Production Ready**
- ---
- Battle-tested with QA, conflict resolution, and validation built in.
+**Healthcare & Life Sciences** β€” clinical decision support, drug interaction graphs, patient safety audit trails, HIPAA compliance.
-- **🧩 Modular**
- ---
- Use only what you need. Swap components easily.
+**Finance & Risk** β€” fraud detection graphs, SOX/GDPR/MiFID II compliance, risk assessment trails.
-- **🌍 Community Driven**
- ---
- Built by developers, for developers. Active Discord.
+**Legal & Compliance** β€” evidence-backed research, contract analysis, regulatory change tracking.
-- **πŸ“š End-to-End**
- ---
- From ingestion to reasoning β€” no duct-taping required.
+**Cybersecurity** β€” threat attribution graphs, incident response timelines, security audit trails.
-- **πŸ”¬ Research-Backed**
- ---
- Grounded in knowledge graph, ontology, and semantic web research.
+**Government & Defense** β€” policy decision trails, classified information handling, provenance chains.
-</div>
+**Critical Infrastructure** β€” power grids, transportation safety, emergency response coordination.
---
-## Learn More
+## Why Semantica?
+
+**Open source, MIT licensed.** No vendor lock-in, no paywalled features. Every line of code is available and forkable.
+
+**Production ready.** 1,000+ passing tests, `PipelineValidator`, `FailureHandler` with exponential backoff, conflict resolution, and 12 security fixes in v0.5.0.
-- [Getting Started](getting-started.md) β€” your first knowledge graph in 5 minutes
-- [Core Concepts](concepts.md) β€” knowledge graphs, ontologies, and semantic reasoning
-- [Cookbook](cookbook.md) β€” 14 domain-specific cookbooks with Jupyter notebooks
-- [API Reference](reference/core.md) β€” complete technical documentation
+**Modular by design.** Import only what you need. Use `NERExtractor` without a graph store. Use `VectorStore` without decision tracking. Every component is independently swappable.
diff --git a/docs/installation.md b/docs/installation.md
index 844eaeb0..1b798697 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -1,12 +1,16 @@
-# Installation
-
-Get Semantica installed in under a minute.
+---
+title: "Installation"
+description: "Get Semantica installed in under a minute."
+icon: "download"
+---
-!!! success "Available on PyPI"
- `pip install semantica` β€” that's it.
+<Check>
+ **Available on PyPI** β€” `pip install semantica` and you're ready.
+</Check>
-!!! note "Requirements"
- Python 3.8 or higher. Python 3.11+ recommended.
+<Note>
+ Python 3.8 or higher required. Python 3.11+ recommended.
+</Note>
---
@@ -32,22 +36,23 @@ python -c "import semantica; print(semantica.__version__)"
## Virtual Environment (Recommended)
-=== "venv"
-
+<Tabs>
+ <Tab title="venv">
```bash
python -m venv venv
source venv/bin/activate # Linux / Mac
venv\Scripts\activate # Windows
pip install semantica
```
-
-=== "conda"
-
+ </Tab>
+ <Tab title="conda">
```bash
conda create -n semantica python=3.11
conda activate semantica
pip install semantica
```
+ </Tab>
+</Tabs>
---
@@ -55,22 +60,20 @@ python -c "import semantica; print(semantica.__version__)"
Install only what you need:
-=== "GPU"
-
+<Tabs>
+ <Tab title="GPU">
```bash
pip install semantica[gpu]
```
Includes PyTorch with CUDA, FAISS GPU, CuPy.
-
-=== "Visualization"
-
+ </Tab>
+ <Tab title="Visualization">
```bash
pip install semantica[viz]
```
Includes PyVis, Graphviz, UMAP.
-
-=== "LLM Providers"
-
+ </Tab>
+ <Tab title="LLM Providers">
```bash
pip install semantica[llm-all] # all providers
@@ -80,13 +83,14 @@ Install only what you need:
pip install semantica[llm-groq] # Groq
pip install semantica[llm-ollama] # Ollama (local)
```
-
-=== "Cloud"
-
+ </Tab>
+ <Tab title="Cloud">
```bash
pip install semantica[cloud]
```
Includes AWS S3, Azure Blob, Google Cloud Storage.
+ </Tab>
+</Tabs>
---
@@ -145,6 +149,14 @@ pip install semantica[gpu]
pip install --user semantica # or use a virtual environment
```
+### Windows `[all]` install fails
+
+This was fixed in **v0.5.0**. Upgrade to the latest release:
+
+```bash
+pip install --upgrade semantica
+```
+
### Windows PyTorch DLL errors
Install the [Microsoft Visual C++ Redistributable](https://aka.ms/vs/17/release/vc_redist.x64.exe). This is a Windows system dependency, not a Semantica bug.
@@ -164,6 +176,14 @@ Install the [Microsoft Visual C++ Redistributable](https://aka.ms/vs/17/release/
## Next Steps
-- [Getting Started](getting-started.md) β€” build your first knowledge graph
-- [Quickstart Tutorial](quickstart.md) β€” full step-by-step pipeline
-- [Cookbook](cookbook.md) β€” interactive Jupyter notebook tutorials
+<CardGroup cols={3}>
+ <Card title="Getting Started" icon="rocket" href="getting-started">
+ Build your first knowledge graph.
+ </Card>
+ <Card title="Quickstart Tutorial" icon="play" href="quickstart">
+ Full step-by-step pipeline.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ Interactive Jupyter notebooks.
+ </Card>
+</CardGroup>
diff --git a/docs/integrations/agno.md b/docs/integrations/agno.md
index a592249b..370434cc 100644
--- a/docs/integrations/agno.md
+++ b/docs/integrations/agno.md
@@ -1,27 +1,33 @@
-# Agno Integration
+---
+title: "Agno Integration"
+description: "Wire Semantica's semantic intelligence stack into Agno multi-agent teams via five focused components."
+icon: "robot"
+---
-Semantica's Agno integration (`semantica[agno]`) wires the full Semantica
-semantic intelligence stack into the [Agno](https://github.com/agno-agi/agno)
-agentic framework via five focused components.
+> Five drop-in components that bring Semantica's KG, vector memory, and decision intelligence into any Agno agent or team.
+
+---
## Installation
```bash
# Core integration
-pip install semantica[agno]
+pip install "semantica[agno]"
# With a graph store backend
-pip install semantica[agno,graph-neo4j]
-pip install semantica[agno,graph-falkordb]
+pip install "semantica[agno,graph-neo4j]"
+pip install "semantica[agno,graph-falkordb]"
# Full stack
-pip install semantica[agno,graph-neo4j,vectorstore-pgvector]
+pip install "semantica[agno,graph-neo4j,vectorstore-pgvector]"
```
+---
+
## Components at a Glance
| Class | Agno Primitive | Semantica Backing |
-|---|---|---|
+|-------|---------------|-------------------|
| `AgnoContextStore` | `AgentMemory(db=…)` | `AgentContext` + `VectorStore` |
| `AgnoKnowledgeGraph` | `Agent(knowledge=…)` | `ContextGraph` + KG pipeline |
| `AgnoDecisionKit` | `Agent(tools=[…])` | `DecisionQuery`, `CausalChainAnalyzer`, `PolicyEngine` |
@@ -32,8 +38,7 @@ pip install semantica[agno,graph-neo4j,vectorstore-pgvector]
## 1. AgnoContextStore
-Replaces Agno's flat conversation storage with a hybrid **vector + context
-graph** memory store. Implements `agno.memory.db.base.MemoryDb`.
+Replaces Agno's flat conversation storage with a hybrid **vector + context graph** memory store. Implements `agno.memory.db.base.MemoryDb`.
```python
from agno.agent import Agent
@@ -61,19 +66,18 @@ agent = Agent(
agent.print_response("Recommend a portfolio allocation for a risk-averse investor.")
```
-### Key behaviours
-
-- `upsert_memory()` β€” stores text in `AgentContext` (vector index + graph node)
-- `read_memories()` β€” hybrid retrieval: vector similarity + optional graph hop expansion
-- `record_decision()` β€” records a structured decision with reasoning & outcome
-- `find_precedents()` β€” returns semantically similar historical decisions
+| Method | Description |
+|--------|-------------|
+| `upsert_memory()` | Store text in `AgentContext` (vector index + graph node) |
+| `read_memories()` | Hybrid retrieval: vector similarity + graph hop expansion |
+| `record_decision()` | Record a structured decision with reasoning and outcome |
+| `find_precedents()` | Return semantically similar historical decisions |
---
## 2. AgnoKnowledgeGraph
-Gives Agno agents a queryable `ContextGraph` instead of a flat document store.
-Ingested documents pass through the full Semantica extraction pipeline.
+Gives Agno agents a queryable `ContextGraph` instead of a flat document store. Ingested documents pass through the full Semantica extraction pipeline.
```python
from agno.agent import Agent
@@ -89,10 +93,7 @@ kg = AgnoKnowledgeGraph(
relation_extractor=RelationExtractor(),
)
-# Ingest local files
kg.load("regulatory_docs/", recursive=True)
-
-# Ingest raw text
kg.load(texts=["Basel IV capital requirements apply from January 2026."])
agent = Agent(
@@ -102,23 +103,19 @@ agent = Agent(
)
```
-### Ingestion pipeline
-
+**Ingestion pipeline:**
```
parse β†’ NER β†’ relation extract β†’ graph build β†’ vector index
```
-### Search: multi-hop GraphRAG
-
+**Search (multi-hop GraphRAG):**
```
vector retrieval β†’ entity lookup β†’ graph hop expansion β†’ context injection
```
-### Get entity subgraph
-
```python
ctx = kg.get_graph_context("Basel IV")
-# Returns a text summary of the entity's immediate neighbourhood in the graph
+# Returns a text summary of the entity's immediate neighbourhood
```
---
@@ -145,28 +142,14 @@ agent = Agent(
agent.print_response("Should we approve this mortgage application?")
```
-### Tools
-
-| Tool | Description | Key Parameters |
-|---|---|---|
-| `record_decision` | Record decision with reasoning and outcome | `category`, `scenario`, `reasoning`, `outcome`, `confidence`, `entities` |
-| `find_precedents` | Search for similar past decisions | `scenario`, `category`, `limit` |
-| `trace_causal_chain` | Trace causal chain of a decision | `decision_id`, `depth` |
-| `analyze_impact` | Assess downstream influence of a decision | `decision_id` |
-| `check_policy` | Validate decision against policy rules | `decision_data`, `policy_rules` |
-| `get_decision_summary` | Summarise decision history by category | `category`, `since`, `limit` |
-
-### Example agent turn
-
-```
-User: Should we approve this mortgage application?
-
-Agent [tool: find_precedents] β†’ 12 similar mortgage approvals found
-Agent [tool: check_policy] β†’ complies with lending policy v2.3
-Agent [tool: record_decision] β†’ recorded: loan_approval / approved / confidence=0.94
-Agent: Based on 12 historical precedents and full policy compliance, I recommend
- approval. Credit score 740, 22% down payment, DTI 31% β€” all within thresholds.
-```
+| Tool | Description |
+|------|-------------|
+| `record_decision` | Record a decision with reasoning, outcome, and confidence |
+| `find_precedents` | Search for similar past decisions |
+| `trace_causal_chain` | Trace causal chain of a decision |
+| `analyze_impact` | Assess downstream influence of a decision |
+| `check_policy` | Validate decision against policy rules |
+| `get_decision_summary` | Summarise decision history by category |
---
@@ -177,7 +160,6 @@ Lets agents actively build and query the context graph during reasoning.
```python
from agno.agent import Agent
from agno.models.openai import OpenAIChat
-
from integrations.agno import AgnoKGToolkit
agent = Agent(
@@ -185,16 +167,10 @@ agent = Agent(
tools=[AgnoKGToolkit()],
show_tool_calls=True,
)
-
-agent.print_response(
- "Extract entities and relationships from this article and store them in the knowledge graph."
-)
```
-### Tools
-
| Tool | Description |
-|---|---|
+|------|-------------|
| `extract_entities` | Extract named entities from text |
| `extract_relations` | Extract relationships between entities |
| `add_to_graph` | Add entities / relations to the context graph |
@@ -207,8 +183,7 @@ agent.print_response(
## 5. AgnoSharedContext
-A single `ContextGraph` shared across an Agno `Team`. Each agent gets a
-**role-scoped view** via `bind_agent()`.
+A single `ContextGraph` shared across an Agno `Team`. Each agent gets a role-scoped view via `bind_agent()`.
```python
from agno.agent import Agent
@@ -244,20 +219,8 @@ team = Team(
agents=[research_agent, decision_agent],
mode="coordinate",
)
-
-team.print_response(
- "Analyse the competitive landscape and recommend our product strategy."
-)
```
-### Shared memory pool
-
-Memories written by one agent are immediately visible to all other agents in the
-team. Each agent's writes are tagged with their role so they can be filtered
-independently.
-
-### Shared decisions
-
```python
# Record a team-level decision
decision_id = shared.record_decision(
@@ -269,51 +232,11 @@ decision_id = shared.record_decision(
agent_role="cfo",
)
-# Query precedents across all agents' history
precedents = shared.find_precedents("market expansion")
-
-# Get cross-agent analytics
-insights = shared.get_shared_insights()
-```
-
----
-
-## Use Cases
-
-### Regulated Industry Agents (Finance, Healthcare, Legal)
-
-Agents that log every decision with full provenance, reasoning chain, and policy
-compliance check for audit trails.
-
-```python
-kit = AgnoDecisionKit(context=ctx)
-# Every agent turn: find_precedents β†’ check_policy β†’ record_decision
-```
-
-### Long-Running Research Agents
-
-Agents that accumulate a persistent `ContextGraph` over days or weeks, enabling
-multi-hop reasoning over a growing knowledge base.
-
-```python
-kg = AgnoKnowledgeGraph(graph_builder=GraphBuilder(), ...)
-# Agents load new documents continuously; search benefits from the growing graph
+insights = shared.get_shared_insights()
```
-### Enterprise Multi-Agent Coordination
-
-Teams using `AgnoSharedContext` to prevent contradictory decisions and share
-structured knowledge across specialist agents.
-
-### GraphRAG Customer Support
-
-Support agents that retrieve answers via graph traversal, providing more
-contextually grounded responses than flat vector search.
-
-### Explainable AI Pipelines
-
-Every agent step, entity reference, and causal chain is traceable back to a
-source document or prior decision.
+Memories written by one agent are immediately visible to all other agents in the team. Each agent's writes are tagged with their role for independent filtering.
---
@@ -321,14 +244,32 @@ source document or prior decision.
```python
from integrations.agno import (
- AgnoContextStore, # MemoryDb implementation
- AgnoKnowledgeGraph, # AgentKnowledge implementation
- AgnoDecisionKit, # Decision intelligence Toolkit
- AgnoKGToolkit, # Knowledge graph Toolkit
- AgnoSharedContext, # Team-level shared context
- AGNO_AVAILABLE, # bool β€” True if agno is installed
+ AgnoContextStore, # MemoryDb implementation
+ AgnoKnowledgeGraph, # AgentKnowledge implementation
+ AgnoDecisionKit, # Decision intelligence Toolkit
+ AgnoKGToolkit, # Knowledge graph Toolkit
+ AgnoSharedContext, # Team-level shared context
+ AGNO_AVAILABLE, # bool β€” True if agno is installed
)
```
-All five classes are usable **without** `agno` installed β€” they carry the full
-Semantica API and degrade gracefully when passed to Agno constructors.
+All five classes are usable without `agno` installed β€” they carry the full Semantica API and degrade gracefully.
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Context Module" icon="brain" href="../reference/context">
+ AgentContext and ContextGraph backing the integration.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="../reference/kg">
+ KG construction used by AgnoKnowledgeGraph.
+ </Card>
+ <Card title="LLMs" icon="microchip" href="../reference/llms">
+ Configure LLM providers for Agno agents.
+ </Card>
+ <Card title="Vector Store" icon="vector-square" href="../reference/vector_store">
+ Vector backend for AgnoContextStore.
+ </Card>
+</CardGroup>
diff --git a/docs/integrations/docling.md b/docs/integrations/docling.md
index 5a5593cf..16e1ac18 100644
--- a/docs/integrations/docling.md
+++ b/docs/integrations/docling.md
@@ -1,107 +1,123 @@
-# Docling Integration
+---
+title: "Docling Integration"
+description: "Native Docling integration for high-fidelity PDF, DOCX, and PPTX parsing with table extraction and OCR."
+icon: "file-lines"
+---
-Semantica features a native integration with **Docling**, the powerful document parsing library that excels at extracting structured data from complex documents like PDFs, DOCX, and PPTX.
+> Parse complex documents β€” PDFs, DOCX, PPTX, HTML β€” with high-fidelity table extraction and built-in OCR.
-## Overview
+---
-Docling is integrated into Semantica's `parse` module via the `DoclingParser`. This allows you to seamlessly convert unstructured documents into semantic structures that can be indexed, searched, and analyzed within the Semantica framework.
+## Overview
-- πŸ“– **Semantica Docling Integration Docs**: [Reference Guide](../reference/parse.md)
-- πŸ’» **Semantica Docling Integration GitHub**: [Source Code](https://github.com/Hawksight-AI/semantica/blob/main/semantica/parse/docling_parser.py)
-- πŸ§‘πŸ½β€πŸ³ **Semantica Docling Integration Example**: [Docling Clear Code Example](../CodeExamples.md#docling-clear-code-example)
-- πŸ“¦ **Semantica Docling Integration PyPI**: [Installation Guide](../installation.md)
+Docling is integrated into Semantica's `parse` module via the `DoclingParser`. Documents pass through Docling's layout engine, then feed directly into Semantica's extraction and KG pipeline.
+
+<CardGroup cols={2}>
+ <Card title="Multi-format" icon="file">
+ PDF, DOCX, PPTX, HTML, and more.
+ </Card>
+ <Card title="Table Extraction" icon="table">
+ High-fidelity table parsing with header detection.
+ </Card>
+ <Card title="OCR Support" icon="eye">
+ Built-in OCR for scanned documents.
+ </Card>
+ <Card title="Markdown Export" icon="markdown">
+ Clean Markdown output optimized for LLM consumption.
+ </Card>
+</CardGroup>
---
-## Integration Documentation
+## Installation
-The `DoclingParser` provides a high-level interface for document processing. It supports:
+```bash
+pip install semantica
+# Docling is included as an optional dependency
+# or install separately:
+pip install docling
+```
-* **Multi-format support**: PDF, DOCX, PPTX, HTML, and more.
-* **Table Extraction**: High-fidelity table extraction with header detection.
-* **OCR Support**: Built-in Optical Character Recognition for scanned documents.
-* **Markdown Export**: Clean markdown output optimized for LLM consumption.
+---
-### Basic Usage
+## Basic Usage
```python
from semantica.parse import DoclingParser
-# Initialize with OCR enabled
parser = DoclingParser(enable_ocr=True)
-
-# Parse a complex document
result = parser.parse("financial_report.pdf")
-# Access the structured data
-print(f"Content: {result['full_text'][:200]}...")
+print(result["full_text"][:200])
print(f"Found {len(result['tables'])} tables")
```
-For more details, see the [Parse Reference](../reference/parse.md).
-
---
-## Integration Example
-
-We provide a detailed cookbook and clear code examples to help you get started quickly.
-
-### Docling Clear Code Example
+## Full Example
```python
from semantica.parse import DoclingParser
-import json
-# 1. Initialize the Docling Parser with advanced config
parser = DoclingParser(
- enable_ocr=True,
- export_format="markdown"
+ enable_ocr=True,
+ export_format="markdown",
)
-# 2. Parse a complex document (PDF, DOCX, etc.)
result = parser.parse("complex_invoice.pdf")
-# 3. Access the clean Markdown text
-print(f"--- Document Content ---\n{result['full_text']}")
+# Full text content
+print(result["full_text"])
-# 4. Iterate through extracted tables
-for i, table in enumerate(result['tables']):
- print(f"\nTable {i+1} headers: {table.get('headers', [])}")
- # Access table rows as a list of lists
- for row in table.get('rows', [])[:3]: # Print first 3 rows
+# Extracted tables
+for i, table in enumerate(result["tables"]):
+ print(f"Table {i+1} headers: {table.get('headers', [])}")
+ for row in table.get("rows", [])[:3]:
print(f" Row: {row}")
-# 5. Get document metadata
-metadata = result['metadata']
-print(f"\n--- Metadata ---\nTitle: {metadata.get('title')}")
-print(f"Total Pages: {result.get('total_pages')}")
+# Metadata
+metadata = result["metadata"]
+print(f"Title: {metadata.get('title')}")
+print(f"Pages: {result.get('total_pages')}")
```
-See more in our [Code Examples](../CodeExamples.md).
-
---
-## GitHub Source
+## DoclingParser Parameters
-The integration is open-source and available on GitHub. You can explore the implementation, contribute improvements, or report issues.
-
-- [docling_parser.py](https://github.com/Hawksight-AI/semantica/blob/main/semantica/parse/docling_parser.py) - The core implementation of the Docling integration.
+| Parameter | Default | Description |
+|-----------|---------|-------------|
+| `enable_ocr` | `False` | Enable OCR for scanned pages |
+| `export_format` | `"markdown"` | Output format: `"markdown"` or `"text"` |
---
-## PyPI & Installation
-
-Docling is an optional but highly recommended dependency for Semantica. You can install it along with Semantica or as a separate requirement.
+## Parsed Result Structure
-### Install via Semantica
-```bash
-pip install semantica
+```python
+{
+ "full_text": str, # Clean document text
+ "tables": list[dict], # Extracted tables (headers + rows)
+ "metadata": dict, # Title, author, creation date, etc.
+ "total_pages": int,
+}
```
-### Install Docling manually
-If you are working in a custom environment:
-```bash
-pip install docling
-```
+---
-For full installation details, see the [Installation Guide](../installation.md).
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Parse Module" icon="file-lines" href="../reference/parse">
+ Full DocumentParser and DoclingParser reference.
+ </Card>
+ <Card title="Ingest Module" icon="file-import" href="../reference/ingest">
+ Loading documents before parsing.
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="../reference/semantic_extract">
+ NER and relation extraction on parsed text.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="../reference/pipeline">
+ Using DoclingParser in a full pipeline.
+ </Card>
+</CardGroup>
diff --git a/docs/integrations/snowflake.md b/docs/integrations/snowflake.md
index d0b1d092..0a135427 100644
--- a/docs/integrations/snowflake.md
+++ b/docs/integrations/snowflake.md
@@ -1,280 +1,195 @@
-# Snowflake Integration
-
-Semantica features a native integration with **Snowflake**, the powerful cloud data warehouse that enables scalable data storage and analytics for enterprise workloads.
-
-## Overview
-
-Snowflake is integrated into Semantica's `ingest` module via the `SnowflakeIngestor`. This allows you to seamlessly extract structured data from Snowflake tables and queries into semantic structures that can be indexed, searched, and analyzed within the Semantica framework.
-
-- πŸ“– **Semantica Snowflake Integration Docs**: [Reference Guide](../reference/ingest.md)
-- πŸ’» **Semantica Snowflake Integration GitHub**: [Source Code](https://github.com/Hawksight-AI/semantica/blob/main/semantica/ingest/snowflake_ingestor.py)
-- πŸ§‘πŸ½β€πŸ³ **Semantica Snowflake Integration Example**: [Snowflake Clear Code Example](../CodeExamples.md#snowflake-clear-code-example)
-- πŸ“¦ **Semantica Snowflake Integration PyPI**: [Installation Guide](../installation.md)
-
+---
+title: "Snowflake Integration"
+description: "Ingest structured data from Snowflake tables and queries into Semantica's KG pipeline."
+icon: "snowflake"
---
-## Integration Documentation
-
-The `SnowflakeIngestor` provides a high-level interface for Snowflake data ingestion. It supports:
-
-* **Multiple Authentication Methods**: Password, key-pair, OAuth, and SSO authentication.
-* **Advanced Querying**: Custom SQL queries with parameterization and batching.
-* **Schema Introspection**: Automatic table schema discovery and metadata extraction.
-* **Document Export**: Convert Snowflake data to Semantica document format.
-
-### Basic Usage
+> Extract data from Snowflake into Semantica with password, key-pair, OAuth, and SSO authentication.
-```python
-from semantica.ingest import SnowflakeIngestor
+---
-# Initialize with environment variables
-ingestor = SnowflakeIngestor()
+## Installation
-# Ingest a table
-data = ingestor.ingest_table("CUSTOMERS")
+```bash
+# Install with Snowflake support
+pip install "semantica[db-snowflake]"
-# Access the structured data
-print(f"Retrieved {data.row_count} rows")
-print(f"Columns: {data.columns}")
+# Or install the connector separately
+pip install snowflake-connector-python
```
-For more details, see the [Ingest Reference](../reference/ingest.md).
-
---
-## Integration Example
-
-We provide a detailed cookbook and clear code examples to help you get started quickly.
-
-### Snowflake Clear Code Example
+## Basic Usage
```python
from semantica.ingest import SnowflakeIngestor
import os
-from dotenv import load_dotenv
-# 1. Load environment variables
-load_dotenv()
-
-# 2. Initialize the Snowflake Ingestor
ingestor = SnowflakeIngestor(
account=os.getenv("SNOWFLAKE_ACCOUNT"),
user=os.getenv("SNOWFLAKE_USER"),
password=os.getenv("SNOWFLAKE_PASSWORD"),
warehouse=os.getenv("SNOWFLAKE_WAREHOUSE"),
database=os.getenv("SNOWFLAKE_DATABASE"),
- schema=os.getenv("SNOWFLAKE_SCHEMA")
-)
-
-# 3. Ingest a table with filters
-data = ingestor.ingest_table(
- "CUSTOMERS",
- where="COUNTRY = 'USA' AND CREATED_DATE > '2024-01-01'",
- order_by="CREATED_DATE DESC",
- limit=10000
-)
-
-# 4. Access the structured data
-print(f"--- Customer Data ---")
-print(f"Retrieved {data.row_count} customers")
-print(f"Columns: {data.columns}")
-
-# 5. Iterate through rows
-for row in data.data[:5]: # Print first 5 rows
- print(f"Customer: {row['NAME']} ({row['EMAIL']})")
-
-# 6. Export as documents for Semantica processing
-documents = ingestor.export_as_documents(
- data,
- id_field="CUSTOMER_ID",
- text_fields=["NAME", "EMAIL", "NOTES"]
+ schema=os.getenv("SNOWFLAKE_SCHEMA"),
)
-print(f"Created {len(documents)} documents for processing")
-```
-
-See more in our [Code Examples](../CodeExamples.md).
-
----
-
-## GitHub Source
-
-The integration is open-source and available on GitHub. You can explore the implementation, contribute improvements, or report issues.
-
-- [snowflake_ingestor.py](https://github.com/Hawksight-AI/semantica/blob/main/semantica/ingest/snowflake_ingestor.py) - The core implementation of the Snowflake integration.
-
----
-
-## PyPI & Installation
-
-Snowflake connector is an optional dependency for Semantica. You can install it along with Semantica or as a separate requirement.
-
-### Install via Semantica
-```bash
-# Install with Snowflake support
-pip install semantica[db-snowflake]
-
-# Or install with all database connectors
-pip install semantica[db-all]
-```
-
-### Install Snowflake connector manually
-If you are working in a custom environment:
-```bash
-pip install snowflake-connector-python
+data = ingestor.ingest_table("CUSTOMERS")
+print(f"Retrieved {data.row_count} rows β€” columns: {data.columns}")
```
-For full installation details, see the [Installation Guide](../installation.md).
+<Tip>
+Use environment variables (or a `.env` file with `python-dotenv`) to keep credentials out of source code. `SnowflakeIngestor()` with no arguments reads from `SNOWFLAKE_*` environment variables automatically.
+</Tip>
---
## Authentication Methods
-Snowflake integration supports multiple authentication methods for different security requirements:
+<Tabs>
+ <Tab title="Password">
+ ```python
+ ingestor = SnowflakeIngestor(
+ account="myaccount",
+ user="myuser",
+ password="mypassword",
+ warehouse="COMPUTE_WH",
+ )
+ ```
+ </Tab>
+ <Tab title="Key-Pair (Recommended)">
+ ```python
+ ingestor = SnowflakeIngestor(
+ account="myaccount",
+ user="myuser",
+ private_key_path="/path/to/rsa_key.p8",
+ warehouse="COMPUTE_WH",
+ )
+ ```
+ Preferred for production β€” no password stored in config.
+ </Tab>
+ <Tab title="OAuth">
+ ```python
+ ingestor = SnowflakeIngestor(
+ account="myaccount",
+ user="myuser",
+ authenticator="oauth",
+ token="your_oauth_token",
+ warehouse="COMPUTE_WH",
+ )
+ ```
+ </Tab>
+ <Tab title="SSO">
+ ```python
+ ingestor = SnowflakeIngestor(
+ account="myaccount",
+ user="myuser",
+ authenticator="externalbrowser",
+ warehouse="COMPUTE_WH",
+ )
+ ```
+ </Tab>
+</Tabs>
-### Password Authentication
-```python
-ingestor = SnowflakeIngestor(
- account="myaccount",
- user="myuser",
- password="mypassword",
- warehouse="COMPUTE_WH"
-)
-```
+---
-### Key-Pair Authentication (Recommended for Production)
-```python
-ingestor = SnowflakeIngestor(
- account="myaccount",
- user="myuser",
- private_key_path="/path/to/rsa_key.p8",
- warehouse="COMPUTE_WH"
-)
-```
+## Querying
-### OAuth Authentication
-```python
-ingestor = SnowflakeIngestor(
- account="myaccount",
- user="myuser",
- authenticator="oauth",
- token="your_oauth_token",
- warehouse="COMPUTE_WH"
-)
-```
+### Ingest a table with filters
-### SSO Authentication
```python
-ingestor = SnowflakeIngestor(
- account="myaccount",
- user="myuser",
- authenticator="externalbrowser",
- warehouse="COMPUTE_WH"
+data = ingestor.ingest_table(
+ "CUSTOMERS",
+ where="COUNTRY = 'USA' AND CREATED_DATE > '2024-01-01'",
+ order_by="CREATED_DATE DESC",
+ limit=10000,
)
```
----
-
-## Advanced Features
+### Custom SQL
-### Schema Introspection
```python
-# Get table schema
-schema = ingestor.get_table_schema("CUSTOMERS")
-for column in schema["columns"]:
- print(f"{column['name']}: {column['type']}")
-```
-
-### Custom Queries
-```python
-# Execute custom SQL
data = ingestor.ingest_query("""
- SELECT
- CUSTOMER_ID,
- SUM(AMOUNT) AS TOTAL_AMOUNT
+ SELECT CUSTOMER_ID, SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES
WHERE DATE >= '2024-01-01'
GROUP BY CUSTOMER_ID
""")
```
-### Batch Processing
+### Schema introspection
+
```python
-# Handle large result sets
-data = ingestor.ingest_query(
- "SELECT * FROM LARGE_TABLE",
- batch_size=5000
-)
+schema = ingestor.get_table_schema("CUSTOMERS")
+for column in schema["columns"]:
+ print(f"{column['name']}: {column['type']}")
```
---
-## Best Practices
-
-### Use Environment Variables
-```python
-import os
-from dotenv import load_dotenv
-
-load_dotenv()
-ingestor = SnowflakeIngestor() # Reads from environment
-```
+## Export as Semantica Documents
-### Use Key-Pair Authentication for Production
```python
-ingestor = SnowflakeIngestor(
- account=os.getenv("SNOWFLAKE_ACCOUNT"),
- user=os.getenv("SNOWFLAKE_USER"),
- private_key_path=os.getenv("SNOWFLAKE_PRIVATE_KEY_PATH"),
- warehouse="COMPUTE_WH"
+documents = ingestor.export_as_documents(
+ data,
+ id_field="CUSTOMER_ID",
+ text_fields=["NAME", "EMAIL", "NOTES"],
)
+print(f"Created {len(documents)} documents for processing")
```
-### Paginate Large Results
+---
+
+## Batch Processing Large Tables
+
```python
-PAGE_SIZE = 10000
+PAGE_SIZE = 5000
for page in range(total_pages):
data = ingestor.ingest_table(
"LARGE_TABLE",
limit=PAGE_SIZE,
- offset=page * PAGE_SIZE
+ offset=page * PAGE_SIZE,
)
process_batch(data)
```
+Or use the built-in `batch_size` parameter:
+
+```python
+data = ingestor.ingest_query(
+ "SELECT * FROM LARGE_TABLE",
+ batch_size=5000,
+)
+```
+
---
## Troubleshooting
-### Connection Issues
```python
-# Test connection
-connector = SnowflakeConnector(
- account="myaccount",
- user="myuser",
- password="mypassword"
-)
+from semantica.ingest import SnowflakeConnector
+connector = SnowflakeConnector(account="myaccount", user="myuser", password="mypassword")
if not connector.test_connection():
- print("Connection failed - check credentials")
-```
-
-### Performance Optimization
-```python
-# Use appropriate warehouse size
-ingestor = SnowflakeIngestor(
- account="myaccount",
- user="myuser",
- password="mypassword",
- warehouse="LARGE_WH" # For heavy workloads
-)
+ print("Connection failed β€” check credentials and account identifier")
```
---
## See Also
-- **[Ingest Module Reference](../reference/ingest.md)** - Complete ingestion documentation
-- **[Getting Started Guide](../getting-started.md)** - Quick start with Semantica
-- **[Code Examples](../CodeExamples.md)** - More integration examples
-- **[Installation Guide](../installation.md)** - Installation instructions
+<CardGroup cols={2}>
+ <Card title="Ingest Module" icon="database" href="../reference/ingest">
+ Full SnowflakeIngestor and all other ingestors.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="../reference/pipeline">
+ Use Snowflake ingestion as a pipeline step.
+ </Card>
+ <Card title="Installation" icon="download" href="../installation">
+ All optional dependency extras.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="../reference/kg">
+ Build a KG from ingested Snowflake data.
+ </Card>
+</CardGroup>
diff --git a/docs/learning-more.md b/docs/learning-more.md
index 49299455..a05920ec 100644
--- a/docs/learning-more.md
+++ b/docs/learning-more.md
@@ -1,64 +1,61 @@
-# Learning More
+---
+title: "Learning More"
+description: "Structured learning paths, configuration reference, troubleshooting, and performance guidance."
+icon: "graduation-cap"
+---
-Structured learning paths, quick references, and performance guidance for going deeper with Semantica.
+> Structured paths for going from beginner to production with Semantica.
---
## Learning Paths
-<div class="grid cards" markdown>
-
-- :material-school: **Beginner** (1–2 hours)
- ---
+<CardGroup cols={3}>
+ <Card title="Beginner (1–2 hrs)" icon="seedling">
New to Semantica and knowledge graphs.
-
- [Start here](#beginner-path)
-
-- :material-compass: **Intermediate** (4–6 hours)
- ---
- Comfortable with basics, building production applications.
-
- [Start here](#intermediate-path)
-
-- :material-rocket: **Advanced** (8+ hours)
- ---
+ [Start with Installation](installation)
+ </Card>
+ <Card title="Intermediate (4–6 hrs)" icon="compass">
+ Comfortable with basics, building production apps.
+ [Start with Modules](modules)
+ </Card>
+ <Card title="Advanced (8+ hrs)" icon="rocket">
Enterprise applications and customization.
-
- [Start here](#advanced-path)
-
-</div>
+ [Start with Architecture](architecture)
+ </Card>
+</CardGroup>
---
### Beginner Path
-1. **Installation & Setup** β€” [Installation Guide](installation.md)
-2. **Core Concepts** β€” [Core Concepts](concepts.md) + [Getting Started](getting-started.md)
-3. **First Knowledge Graph** β€” [Quickstart Tutorial](quickstart.md)
-4. **Interactive Introduction** β€” [Welcome to Semantica notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)
-5. **Hands-On Practice** β€” [Your First Knowledge Graph notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb)
+1. [Installation Guide](installation) β€” set up your environment
+2. [Core Concepts](concepts) β€” understand KGs, embeddings, and extraction
+3. [Getting Started](getting-started) β€” first working example
+4. [Quickstart Tutorial](quickstart) β€” build your first KG
+5. [Welcome to Semantica notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb) β€” interactive introduction
---
### Intermediate Path
-1. **All Modules** β€” [Modules Guide](modules.md)
-2. **Advanced Graph Construction** β€” [Building Knowledge Graphs notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb)
-3. **Embeddings & Search** β€” [Embeddings notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Embeddings.ipynb)
-4. **GraphRAG** β€” [GraphRAG Complete notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)
-5. **Multi-Source Integration** β€” [Multi-Source Data Integration notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)
-6. **Use Case Examples** β€” [Use Cases](use-cases.md)
+1. [Modules Guide](modules) β€” every module with code examples
+2. [Building Knowledge Graphs notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb)
+3. [Embeddings notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Embeddings.ipynb)
+4. [GraphRAG Complete notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)
+5. [Multi-Source Data Integration notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)
+6. [Use Cases](use-cases) β€” domain-specific examples
---
### Advanced Path
-1. **Architecture Deep Dive** β€” [Architecture Guide](architecture.md)
-2. **Temporal Graphs** β€” [Temporal Graphs notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/04_Temporal_Graphs.ipynb)
-3. **Ontologies** β€” [Ontology notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb)
-4. **Visualization** β€” [Complete Visualization Suite notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)
-5. **Export Pipelines** β€” [Multi-Format Export notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)
-6. **Production GraphRAG** β€” [GraphRAG Complete notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)
+1. [Architecture Guide](architecture) β€” three-layer system overview
+2. [Temporal Graphs notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/04_Temporal_Graphs.ipynb) β€” v0.4.0 temporal intelligence
+3. [Ontology notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb) β€” v0.5.0 Ontology Hub
+4. [Complete Visualization Suite notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)
+5. [Multi-Format Export notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)
+6. [Deep Dive](deep-dive) β€” internals and extension points
---
@@ -67,85 +64,79 @@ Structured learning paths, quick references, and performance guidance for going
| Setting | Environment Variable | Default |
|---------|---------------------|---------|
| OpenAI API Key | `OPENAI_API_KEY` | `None` |
+| Groq API Key | `GROQ_API_KEY` | `None` |
| Embedding Provider | `SEMANTICA_EMBEDDING_PROVIDER` | `"openai"` |
| Graph Backend | `SEMANTICA_GRAPH_BACKEND` | `"networkx"` |
+| Log Level | `SEMANTICA_LOG_LEVEL` | `"INFO"` |
+| Log Format | `SEMANTICA_LOG_FORMAT` | `"text"` |
---
## Troubleshooting
-<div class="grid cards" markdown>
+**`ModuleNotFoundError`**
-- :material-alert: **Import Errors**
- ---
- `ModuleNotFoundError`
+Verify installation: `pip list | grep semantica`. Ensure Python 3.8+. For optional extras, install the relevant extra (e.g. `pip install "semantica[llm-openai]"`).
- Verify installation: `pip list | grep semantica`. Ensure Python 3.8+.
+**`AuthenticationError`**
-- :material-key: **API Key Errors**
- ---
- `AuthenticationError`
+Set the relevant API key as an environment variable (`OPENAI_API_KEY`, `GROQ_API_KEY`, etc.). Never hardcode keys in source files.
- Set `OPENAI_API_KEY` (or the relevant provider key) as an environment variable.
+**`MemoryError` or OOM crashes**
-- :material-memory: **Memory Errors**
- ---
- `MemoryError` or OOM crashes
+Reduce batch sizes or switch to a persistent graph backend (Neo4j, FalkorDB) instead of the default in-memory NetworkX backend.
- Reduce batch sizes or switch to a persistent graph backend (Neo4j, FalkorDB).
+Slow processing on large datasets β€” enable parallel processing via `Pipeline(workers=N)` and use GPU acceleration for embedding models.
-- :material-speedometer: **Slow Processing**
- ---
- Long runtimes on large datasets
+**Windows `[all]` installation fails (v0.5.0 fix)**
- Enable parallel processing (`PipelineBuilder` workers) and GPU acceleration.
+Use `pip install "semantica[core]"` instead of `pip install "semantica[all]"` on Windows. See the [Installation guide](installation) for the full list of extras.
-</div>
+cp1252 encoding crash on Windows (v0.5.0 fix) β€” pass `encoding="utf-8"` explicitly to `FileIngestor` or set `PYTHONIOENCODING=utf-8` in your environment.
---
## Performance Optimization
-### Batch Processing
-
-Process documents in batches rather than one at a time. Configure chunk sizes based on available RAM.
-
-### Parallel Execution
+**Batch processing** β€” process documents in batches rather than one at a time; configure chunk sizes based on available RAM.
-`PipelineBuilder` supports configurable worker counts per stage for independent operations.
+**Parallel execution** β€” `Pipeline(workers=N)` runs extraction steps in parallel across documents.
-### Backend Selection
+**Backend selection:**
| Operation | NetworkX | Neo4j / FalkorDB |
-|-----------|----------|------------------|
+|-----------|----------|-----------------|
| Graph construction | Fast | Moderate |
| Query performance | Moderate | Fast |
| Scalability | Low (in-memory) | High (persistent) |
-Use NetworkX for development and smaller graphs; switch to a persistent backend for production at scale.
+Use NetworkX for development and small graphs; switch to a persistent backend for production.
---
## Security Best Practices
-**API keys**
-- Store in environment variables or a secrets manager
-- Never hardcode keys or commit them to version control
-- Rotate keys regularly
+**API keys** β€” store in environment variables or a secrets manager; never commit them to version control; rotate regularly.
-**Data privacy**
-- Use local embedding models for sensitive data
-- Avoid sending PII to external APIs without appropriate data handling agreements
-- Encrypt sensitive graph exports at rest
+**Data privacy** β€” use local embedding models (Ollama, HuggingFace) for sensitive data; avoid sending PII to external APIs without appropriate data handling agreements.
----
-
-## Next Steps
+**Exports** β€” encrypt sensitive graph exports at rest; use the v0.5.0 SSRF-safe `base_url` validation when configuring custom LLM gateways.
-- [Cookbook](cookbook.md) β€” interactive Jupyter notebook tutorials
-- [API Reference](reference/core.md) β€” complete technical documentation
-- [Use Cases](use-cases.md) β€” real-world domain examples
-- [FAQ](faq.md) β€” common questions
+---
-!!! info "Questions or feedback?"
- [Open an issue](https://github.com/Hawksight-AI/semantica/issues) or [start a discussion](https://github.com/Hawksight-AI/semantica/discussions).
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Cookbook" icon="book-open" href="cookbook">
+ Interactive Jupyter notebook tutorials.
+ </Card>
+ <Card title="FAQ" icon="circle-question" href="faq">
+ Common questions answered.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/core">
+ Complete technical documentation.
+ </Card>
+ <Card title="Use Cases" icon="briefcase" href="use-cases">
+ Real-world domain examples.
+ </Card>
+</CardGroup>
diff --git a/docs/license.md b/docs/license.md
index 429a4a32..6e3871f0 100644
--- a/docs/license.md
+++ b/docs/license.md
@@ -1,6 +1,10 @@
-# License
+---
+title: "License"
+description: "Semantica is open source under the MIT License β€” free for personal and commercial use."
+icon: "file-contract"
+---
-**Semantica is open source under the MIT License.**
+> Semantica is open source and free for everyone under the MIT License.
---
@@ -34,37 +38,39 @@ SOFTWARE.
## What This Means
-### βœ… You Can
-- **Use commercially** - Free for business use
-- **Modify** - Change the source code
-- **Distribute** - Share with others
-- **Sublicense** - Use in your own projects
-- **Private use** - Use in proprietary software
+**You can:**
+
+- Use Semantica commercially β€” free for business use
+- Modify the source code
+- Distribute copies or derivatives
+- Use in proprietary software
+
+**You must:**
-### βœ… You Must
-- **Include copyright** - Keep the copyright notice
-- **Include license** - Share the MIT license text
+- Keep the copyright notice in copies
+- Include the MIT license text in distributions
-### ❌ No Warranty
-- **No liability** - Authors not responsible for damages
-- **No endorsement** - Can't use authors' names for promotion
+**No warranty** β€” the authors are not responsible for damages or liable for how you use the software.
---
## Commercial Use
-**Semantica is completely free for commercial use.** No attribution required (though appreciated!).
+Semantica is completely free for commercial use. No attribution is required (though it's appreciated).
---
## Third-Party Dependencies
Semantica uses open-source libraries with compatible licenses:
-- **Python** (PSF License)
-- **NumPy, Pandas** (BSD License)
-- **spaCy** (MIT License)
-- **Transformers** (Apache 2.0)
-- **RDFLib** (BSD License)
+
+| Library | License |
+|---------|---------|
+| Python | PSF License |
+| NumPy, Pandas | BSD |
+| spaCy | MIT |
+| Transformers | Apache 2.0 |
+| RDFLib | BSD |
---
@@ -74,12 +80,13 @@ By contributing to Semantica, you agree that your contributions will be licensed
---
-## Questions?
-
-- **[GitHub Issues](https://github.com/Hawksight-AI/semantica/issues)** - License questions
-- **[Contributing Guide](contributing.md)** - How to contribute
-- **[Community](community.md)** - Get in touch
-
----
+## See Also
-**Semantica is open source and free for everyone!** πŸŽ‰
+<CardGroup cols={2}>
+ <Card title="Contributing" icon="code-pull-request" href="contributing">
+ How to contribute to the project.
+ </Card>
+ <Card title="Citation" icon="quote-left" href="citation">
+ How to cite Semantica in research.
+ </Card>
+</CardGroup>
diff --git a/docs/modules.md b/docs/modules.md
index d03bc0a3..4190eb1b 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -1,123 +1,87 @@
-ο»Ώ# Modules
-
-Every Semantica module works independently β€” use only what you need.
+---
+title: "Modules"
+description: "Every Semantica module works independently β€” use only what you need."
+icon: "puzzle-piece"
+---
-!!! tip "Just need a quick reference?"
- Jump to the [Module Index](#module-index) at the bottom of this page.
+<Tip>
+ Just need a quick reference? Jump to the [Module Index](#module-index) at the bottom of this page.
+</Tip>
---
## Architecture Overview
-Semantica is organized into **six logical layers** - each with specific responsibilities:
-
-<div class="grid cards" markdown>
-
-- **Input Layer**
-
- ---
-
- Data ingestion and preparation
-
- **Modules**: Ingest, Parse, Split, Normalize
-
-- **Core Processing**
-
- ---
-
- Intelligence and understanding
-
- **Modules**: Semantic Extract, Knowledge Graph, Ontology, Reasoning
-
-- **Storage**
-
- ---
-
- Persistent data storage
-
- **Modules**: Embeddings, Vector Store, Graph Store, Triplet Store
-
-- **Quality Assurance**
-
- ---
-
- Data quality and consistency
-
- **Modules**: Deduplication, Conflicts
-
-- **Context & Memory**
-
- ---
-
- Agent memory and foundation data
-
- **Modules**: Context, Seed, LLM Providers
-
-- **Output & Orchestration**
-
- ---
-
- Export, visualization, and workflows
-
- **Modules**: Export, Visualization, Pipeline
-
-</div>
+Semantica is organized into **six logical layers**, each with specific responsibilities:
+
+<CardGroup cols={3}>
+ <Card title="Input Layer" icon="database">
+ Data ingestion and preparation. **Modules:** Ingest, Parse, Split, Normalize
+ </Card>
+ <Card title="Core Processing" icon="microchip">
+ Intelligence and understanding. **Modules:** Semantic Extract, KG, Ontology, Reasoning
+ </Card>
+ <Card title="Storage" icon="hard-drive">
+ Persistent data storage. **Modules:** Embeddings, Vector Store, Graph Store, Triplet Store
+ </Card>
+ <Card title="Quality Assurance" icon="check-circle">
+ Data quality and consistency. **Modules:** Deduplication, Conflicts
+ </Card>
+ <Card title="Context & Memory" icon="brain">
+ Agent memory and decision tracking. **Modules:** Context, Provenance, Change Management
+ </Card>
+ <Card title="Output & Orchestration" icon="share-nodes">
+ Export, visualization, and workflows. **Modules:** Export, Visualization, Pipeline
+ </Card>
+</CardGroup>
---
## Input Layer
-### Ingest Module
-**Data ingestion from multiple sources**
+### Ingest
+
+Data ingestion from files, web, databases, and streams.
```python
-from semantica.ingest import FileIngestor, WebIngestor
+from semantica.ingest import FileIngestor, WebIngestor, ParquetIngestor, XMLIngestor
-# File ingestion
+# Files (PDF, DOCX, CSV, Excel, PPTX, JSON, HTML, archives)
ingestor = FileIngestor()
documents = ingestor.ingest_directory("data/")
-# Web ingestion
+# Web
web_ingestor = WebIngestor()
pages = web_ingestor.ingest_urls(["https://example.com"])
-```
-- **File formats** - PDF, DOCX, TXT, JSON, CSV
-- **Web scraping** - Extract content from websites
-- **Database** - Connect to SQL and NoSQL databases
-- **Batch processing** - Handle large datasets efficiently
+# Parquet β€” single file, partitioned directory, Hive-style (v0.5.0)
+parquet = ParquetIngestor()
+sources = parquet.ingest("data/events.parquet")
+
+# XML with XSD/DTD validation, namespace handling (v0.5.0)
+xml = XMLIngestor(validate_xsd="schema.xsd")
+sources = xml.ingest("data/records/")
+```
-- Document processing pipelines
-- Web data extraction
-- Database integration
-- Multi-source data collection
+### Parse
-### Parse Module
-**Document parsing and text extraction**
+Document parsing and text extraction.
```python
-from semantica.parse import DocumentParser
+from semantica.parse import DocumentParser, DoclingParser
+# Standard parser
parser = DocumentParser()
parsed = parser.parse_document("document.pdf")
-text = parsed["full_text"]
-metadata = parsed["metadata"]
-```
-
-- **Text extraction** - Extract clean text from documents
-- **Metadata parsing** - Extract titles, authors, dates
-- **Structure analysis** - Identify sections, headings
-- **OCR support** - Handle scanned documents
-- PDF processing
-- Document analysis
-- Content extraction
-- Metadata harvesting
+# Advanced parser: multi-column PDFs, merged-cell tables, OCR
+parser = DoclingParser(extract_tables=True, extract_images=True, output_format="markdown")
+parsed = parser.parse("data/annual_report.pdf")
+```
----
+### Split
-### Split Module
-**Text chunking and segmentation**
+Text chunking and segmentation for embedding and RAG pipelines.
```python
from semantica.split import TextSplitter
@@ -126,20 +90,11 @@ splitter = TextSplitter(method="semantic")
chunks = splitter.split(text, chunk_size=1000, overlap=200)
```
-- **Intelligent chunking** - Split text while preserving context
-- **Semantic splitting** - Break at natural boundaries
-- **Size control** - Manage chunk sizes for processing
-- **Overlap handling** - Maintain context between chunks
-
-- Document preprocessing
-- Embedding preparation
-- RAG systems
-- Large document processing
+Methods: `recursive`, `semantic`, `entity-aware`, `relation-aware`.
----
+### Normalize
-### Normalize Module
-**Data cleaning and standardization**
+Data cleaning and standardization.
```python
from semantica.normalize import DataNormalizer
@@ -149,127 +104,91 @@ clean_text = normalizer.normalize_text(text)
standardized_date = normalizer.normalize_date("Jan 1st, 2020")
```
-- **Text cleaning** - Remove noise and artifacts
-- **Date standardization** - Convert to ISO format
-- **Name normalization** - Standardize person names
-- **Entity normalization** - Clean up company names
-
-- Data preprocessing
-- Quality improvement
-- Standardization
-- Consistency enforcement
-
---
## Core Processing
-### Semantic Extract Module
-**Entity and relationship extraction**
+### Semantic Extract
+
+Named entity recognition, relation extraction, and triplet generation.
```python
-from semantica.semantic_extract import NERExtractor, RelationExtractor
+from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor
-# Entity extraction
-ner = NERExtractor()
+ner = NERExtractor(method="llm", llm_provider=llm)
entities = ner.extract("Apple Inc. was founded by Steve Jobs.")
-# Relationship extraction
-rel_extractor = RelationExtractor()
-relationships = rel_extractor.extract(text, entities)
-```
+rel = RelationExtractor(method="llm", llm_provider=llm)
+relationships = rel.extract(text, entities=entities)
-- **Named Entity Recognition** - Find people, orgs, locations
-- **Relationship extraction** - Find connections between entities
-- **Custom entities** - Define your own entity types
-- **Confidence scoring** - Quality assessment for extractions
+trip = TripletExtractor(method="llm", llm_provider=llm)
+triplets = trip.extract(text)
+```
-- Knowledge graph construction
-- Document analysis
-- Information extraction
-- Content understanding
+Methods: `"pattern"`, `"ml"`, `"llm"`. LLM method supports all 8 providers.
----
+### Knowledge Graph
-### Knowledge Graph Module
-**Graph construction and management**
+Graph construction, algorithms, temporal model, and distance intelligence.
```python
-from semantica.kg import GraphBuilder, GraphAnalyzer
-
-# Build graph
-builder = GraphBuilder()
-kg = builder.build({"entities": entities, "relationships": relationships})
+from semantica.kg import GraphBuilder, GraphAnalyzer, TemporalKnowledgeGraph, DistanceCalculator
-# Analyze graph
-analyzer = GraphAnalyzer()
-stats = analyzer.analyze(kg)
-```
+# Build
+builder = GraphBuilder(merge_entities=True)
+kg = builder.build(entities=entities, relationships=relationships)
-- **Graph construction** - Build knowledge graphs from data
-- **Graph analysis** - Calculate metrics and statistics
-- **Graph querying** - Search and retrieve information
-- **Graph manipulation** - Merge, split, transform graphs
+# Temporal graphs (v0.4.0)
+tkg = TemporalKnowledgeGraph()
+tkg.add_node("ceo_role", valid_from=datetime(2020, 1, 1), valid_until=datetime(2023, 6, 1))
+snapshot = tkg.at(datetime(2021, 6, 15))
-- Knowledge base creation
-- Graph analytics
-- Information retrieval
-- Data integration
+# Distance Intelligence (v0.5.0)
+calc = DistanceCalculator(kg)
+neighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)
+matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])
+```
----
+### Ontology
-### Ontology Module
-**Schema definition and validation**
+SHACL, SKOS, alignments, diff/migration, auto-generation, and OWL/RDF β€” plus the visual Ontology Hub (v0.5.0).
```python
-from semantica.ontology import OntologyManager
+from semantica.ontology import OntologyManager, SHACLGenerator
-# Define ontology
ontology = OntologyManager()
ontology.add_class("Person", ["name", "birth_date"])
ontology.add_relationship("works_for", "Person", "Organization")
-
-# Validate data
is_valid = ontology.validate_graph(kg)
-```
-
-- **Schema definition** - Define data structure
-- **Data validation** - Ensure data conforms to schema
-- **Inheritance** - Create hierarchical relationships
-- **Constraints** - Enforce data quality rules
-- Data modeling
-- Quality assurance
-- Schema management
-- Rule enforcement
+shacl = SHACLGenerator()
+shapes = shacl.generate(ontology)
+```
----
+### Reasoning
-### Reasoning Module
-**Logical inference and deduction**
+Forward chaining, Rete, deductive, abductive, SPARQL, and Datalog reasoning.
```python
-from semantica.reasoning import ReasoningEngine
+from semantica.reasoning import ReasoningEngine, DatalogEngine
+# Rule-based reasoning
engine = ReasoningEngine()
inferences = engine.infer(kg, rules=["transitivity", "symmetry"])
-```
-
-- **Logical inference** - Derive new facts from existing ones
-- **Pattern matching** - Find complex patterns in data
-- **Consistency checking** - Detect contradictions
-- **Decision support** - Automated reasoning
-- Knowledge discovery
-- Decision making
-- Consistency checking
-- Advanced analytics
+# Datalog β€” recursive Horn clause rules (v0.4.0)
+datalog = DatalogEngine()
+datalog.add_rule("ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).")
+results = datalog.query("ancestor(alice, ?)")
+```
---
-## Storage Layer
+## Storage
+
+### Embeddings
-### Embeddings Module
-**Vector embeddings and similarity**
+Vector embeddings and similarity computation.
```python
from semantica.embeddings import EmbeddingGenerator
@@ -279,43 +198,26 @@ embeddings = generator.generate(["text1", "text2"])
similarity = generator.similarity(embeddings[0], embeddings[1])
```
-- **Text embeddings** - Convert text to vectors
-- **Similarity search** - Find similar content
-- **Clustering** - Group related items
-- **AI integration** - Provide context to LLMs
-
-- Semantic search
-- Recommendation systems
-- Clustering
-- AI context
+Supported: Sentence-Transformers, FastEmbed, OpenAI, BGE.
----
+### Vector Store
-### Vector Store Module
-**Vector database management**
+Multi-backend vector database management.
```python
from semantica.vector_store import VectorStore
-store = VectorStore(backend="faiss")
+store = VectorStore(backend="faiss", dimension=768)
store.add_vectors(embeddings, ids)
results = store.search(query_vector, top_k=10)
```
-- **Vector storage** - Efficient vector database
-- **Fast search** - Approximate nearest neighbor search
-- **Indexing** - Optimize for performance
-- **Batch operations** - Handle large datasets
-
-- Semantic search
-- RAG systems
-- Recommendation engines
-- Similarity matching
+Backends: FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory.
+Search modes: semantic top-k, hybrid (vector + keyword), metadata-filtered.
----
+### Graph Store
-### Graph Store Module
-**Graph database integration**
+Graph database integration.
```python
from semantica.graph_store import GraphStore
@@ -326,67 +228,42 @@ store.add_edges(relationships)
results = store.query("MATCH (n)-[r]->(m) RETURN n, r, m")
```
-- **Graph persistence** - Store graphs in databases
-- **Graph queries** - Cypher and Gremlin support
-- **Graph algorithms** - Path finding, centrality
-- **Transactions** - ACID compliance
+Backends: Neo4j, FalkorDB, Apache AGE, Amazon Neptune.
-- Knowledge graph storage
-- Graph analytics
-- Network analysis
-- Relationship queries
+### Triplet Store
----
-
-### Triplet Store Module
-**Triple-based storage**
+RDF triple-based storage with SPARQL.
```python
from semantica.triplet_store import TripletStore
-store = TripletStore()
-store.add_triplets(subject, predicate, object)
-triplets = store.get_triplets(entity="Apple Inc.")
+store = TripletStore(backend="blazegraph")
+store.add_triplets(subject, predicate, obj)
+results = store.sparql("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
```
-- **Triple storage** - Store (subject, predicate, object) triples
-- **Pattern matching** - Find specific patterns
-- **RDF support** - Semantic web standards
-- **Bulk operations** - Efficient batch processing
-
-- Semantic web
-- Knowledge representation
-- Linked data
-- Triple stores
+Backends: Blazegraph, Apache Jena, RDF4J.
---
## Quality Assurance
-### Deduplication Module
-**Entity deduplication and resolution**
+### Deduplication
+
+Entity deduplication v1/v2, similarity scoring, and merging.
```python
from semantica.deduplication import EntityResolver
resolver = EntityResolver()
-merged_entities = resolver.resolve(entities, strategy="semantic")
+merged = resolver.resolve(entities, strategy="semantic_v2")
```
-- **Duplicate detection** - Find similar entities
-- **Entity resolution** - Merge duplicate records
-- **Similarity scoring** - Quality assessment
-- **Record linkage** - Connect related records
-
-- Data cleaning
-- Master data management
-- Record linkage
-- Quality improvement
+v2 strategies (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to 7x faster than v1. `DuplicateDetector` supports `max_results`, `top_k_per_entity`, `min_similarity`, and `sort_by` for fine-grained control.
----
+### Conflicts
-### Conflicts Module
-**Conflict detection and resolution**
+Multi-source conflict detection and resolution.
```python
from semantica.conflicts import ConflictDetector
@@ -396,134 +273,85 @@ conflicts = detector.detect_conflicts(kg)
resolved = detector.resolve(conflicts, strategy="most_recent")
```
-- **Conflict detection** - Find contradictory information
-- **Resolution strategies** - Automated conflict resolution
-- **Source reliability** - Trustworthiness assessment
-- **Temporal analysis** - Time-based conflict handling
-
-- Data quality
-- Consistency checking
-- Trust management
-- Conflict resolution
+Detection types: value, type, temporal, and logical conflicts.
---
## Context & Memory
-### Context Module
-**Context management for AI agents**
+### Context
-```python
-from semantica.context import ContextManager
+Agent context graphs, decision tracking, causal chains, and precedent search.
-manager = ContextManager()
-context = manager.get_context(query, history)
+```python
+from semantica.context import AgentContext, ContextGraph
+
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+ decision_tracking=True,
+)
+
+context.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%")
+decision_id = context.record_decision(
+ category="model_selection", scenario="...", reasoning="...", outcome="...", confidence=0.9
+)
+precedents = context.find_precedents("model selection", limit=5)
```
-- **Context tracking** - Maintain conversation context
-- **Memory management** - Store and retrieve context
-- **Relevance scoring** - Find relevant context
-- **Session management** - Handle multiple conversations
-
-- AI agents
-- Chatbots
-- Conversational AI
-- Context-aware systems
-
----
+### Provenance
-### Seed Module
-**Foundation data and knowledge**
+W3C PROV-O compliant lineage tracking across all 17 modules.
```python
-from semantica.seed import SeedData
+from semantica.provenance import ProvenanceManager
-seed = SeedData()
-knowledge = seed.get_knowledge("technology", "companies")
+manager = ProvenanceManager()
+manager.track_entity("entity_1", "document.pdf", "person")
+lineage = manager.get_lineage("entity_1")
```
-- **Seed knowledge** - Foundation data for domains
-- **Knowledge bases** - Pre-built domain knowledge
-- **Quick start** - Bootstrap applications
-- **Domain models** - Industry-specific data
-
-- Domain bootstrapping
-- Quick start data
-- Industry knowledge
-- Foundation models
-
----
+### Change Management
-### LLM Providers Module
-**Large Language Model integration**
+Version storage, change tracking, SHA-256 checksums, and audit trails.
```python
-from semantica.llms import LLMProvider
+from semantica.change_management import TemporalVersionManager
-provider = LLMProvider(model="gpt-4")
-response = provider.generate(prompt, context=kg)
+manager = TemporalVersionManager(storage_path="versions.db")
+snapshot = manager.create_snapshot(kg, "v1.0", "[email protected]", "Initial version")
+diff = manager.diff("v1.0", "v1.1")
```
-- **LLM integration** - Connect to various LLM providers
-- **Prompt engineering** - Optimize prompts for results
-- **Context injection** - Provide knowledge graph context
-- **Response parsing** - Extract structured outputs
-
-- AI generation
-- Question answering
-- Text completion
-- Knowledge reasoning
-
---
## Output & Orchestration
-### Export Module
-**Data export and serialization**
+### Export
+
+RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, CSV, OWL ontologies.
```python
-from semantica.export import GraphExporter
+from semantica.export import RDFExporter
-exporter = GraphExporter()
-exporter.export(kg, format="json", filename="output.json")
+exporter = RDFExporter()
+rdf = exporter.export_to_rdf(graph, format="turtle")
```
-- **Multiple formats** - JSON, CSV, RDF, GraphML
-- **Database export** - Export to various databases
-- **Streaming** - Handle large datasets
-- **Filtering** - Export specific data subsets
+### Visualization
-- Data sharing
-- System integration
-- Backup and restore
-- Format conversion
-
----
-
-### Visualization Module
-**Graph visualization and analysis**
+Interactive and static KG, ontology, embedding, and temporal visualization.
```python
from semantica.visualization import GraphVisualizer
-visualizer = GraphVisualizer()
-visualizer.plot(kg, layout="force_directed")
+viz = GraphVisualizer()
+viz.visualize(graph, output="graph.html")
```
-- **Graph visualization** - Interactive graph plots
-- **Custom styling** - Tailored visual appearance
-- **Analytics charts** - Statistics and metrics
-- **Exploration tools** - Interactive data exploration
-
-- Data exploration
-- Presentation
-- Analysis
-- Reporting
-
----
+### Pipeline
-### Pipeline Module
-**Workflow orchestration**
+Pipeline DSL with parallel workers, retry policies, and failure handling.
```python
from semantica.pipeline import Pipeline
@@ -535,85 +363,17 @@ pipeline.add_step("build", GraphBuilder())
result = pipeline.run("data/")
```
-- **Workflow orchestration** - Coordinate multiple steps
-- **Parallel processing** - Run steps concurrently
-- **Progress tracking** - Monitor pipeline execution
-- **Error handling** - Robust error management
-
-- Data processing
-- Workflow automation
-- Batch processing
-- System integration
-
----
-
-## Additional Modules
-
-### Change Management Module
-**Version control and audit trails**
-
-```python
-from semantica.change_management import TemporalVersionManager
-
-manager = TemporalVersionManager(storage_path="versions.db")
-snapshot = manager.create_snapshot(kg, "v1.0", "[email protected]", "Initial version")
-```
-
-- **Version control** - Track changes over time
-- **Audit trails** - Complete change history
-- **Data integrity** - SHA-256 checksums
-- **Change comparison** - Detailed diff analysis
-
-- Knowledge graph versioning
-- Compliance tracking
-- Data governance
-- Change management
-
----
-
-### Provenance Module
-**W3C PROV-O compliant tracking**
-
-```python
-from semantica.provenance import ProvenanceManager
-
-manager = ProvenanceManager()
-manager.track_entity("entity_1", "document.pdf", "person")
-```
-
-- **W3C PROV-O compliant** - Industry standard tracking
-- **Complete lineage** - End-to-end traceability
-- **Source attribution** - Track data origins
-- **Integrity verification** - Tamper detection
-
-- Regulatory compliance
-- Data provenance
-- Audit trails
-- Source tracking
-
----
+### Explorer (v0.4.0/v0.5.0)
-### Core Module
-**Framework orchestration and configuration**
+FastAPI Knowledge Explorer + Ontology Hub with WebSocket progress, thread-safe sessions, bidirectional path finding, and indexed search.
```python
-from semantica.core import Semantica, Config
+from semantica.explorer import start_explorer
-# Initialize framework
-semantica = Semantica(config=Config())
-result = semantica.process("data/")
+start_explorer(graph=kg, port=8080)
+# Opens at http://localhost:8080
```
-- **Framework orchestration** - Central coordination
-- **Configuration management** - Settings and preferences
-- **Lifecycle management** - Start/stop/restart
-- **Plugin system** - Extensible architecture
-
-- Framework initialization
-- Configuration management
-- Plugin development
-- System orchestration
-
---
## Common Module Chains
@@ -622,44 +382,56 @@ result = semantica.process("data/")
|------|---------|
| Document processing | Ingest β†’ Parse β†’ Split β†’ Semantic Extract β†’ KG |
| Web scraping | Ingest (Web) β†’ Normalize β†’ Semantic Extract β†’ Graph Store |
+| GraphRAG | KG + Vector Store β†’ Context β†’ Reasoning β†’ Export |
| AI agents | Context β†’ LLM Providers β†’ Reasoning β†’ Export |
-| Analytics | KG β†’ Graph Store β†’ Visualization β†’ Export |
+| Temporal analysis | KG (Temporal) β†’ Context β†’ Change Management β†’ Export |
+| Compliance pipeline | Ingest β†’ Semantic Extract β†’ KG β†’ Provenance β†’ Export |
---
## Module Index
-| Module | Purpose | Key Classes | Use Cases |
-|--------|---------|-------------|-----------|
-| [Ingest](reference/ingest.md) | Data ingestion | FileIngestor, WebIngestor | File processing, web scraping |
-| [Parse](reference/parse.md) | Document parsing | DocumentParser | PDF processing, text extraction |
-| [Split](reference/split.md) | Text chunking | TextSplitter | RAG systems, preprocessing |
-| [Normalize](reference/normalize.md) | Data cleaning | DataNormalizer | Quality improvement |
-| [Semantic Extract](reference/semantic_extract.md) | Information extraction | NERExtractor, RelationExtractor | Knowledge graphs |
-| [Knowledge Graph](reference/kg.md) | Graph management | GraphBuilder, GraphAnalyzer | Graph construction |
-| [Ontology](reference/ontology.md) | Schema management | OntologyManager | Data modeling |
-| [Reasoning](reference/reasoning.md) | Logical inference | ReasoningEngine | Knowledge discovery |
-| [Embeddings](reference/embeddings.md) | Vector embeddings | EmbeddingGenerator | Semantic search |
-| [Vector Store](reference/vector_store.md) | Vector database | VectorStore | Similarity search |
-| [Graph Store](reference/graph_store.md) | Graph database | GraphStore | Graph storage |
-| [Triplet Store](reference/triplet_store.md) | Triple storage | TripletStore | Semantic web |
-| [Deduplication](reference/deduplication.md) | Entity resolution | EntityResolver | Data quality |
-| [Conflicts](reference/conflicts.md) | Conflict resolution | ConflictDetector | Consistency |
-| [Context](reference/context.md) | Context management | ContextManager | AI agents |
-| [Seed](reference/seed.md) | Foundation data | SeedData | Domain knowledge |
-| [LLM Providers](reference/llms.md) | LLM integration | LLMProvider | AI generation |
-| [Export](reference/export.md) | Data export | GraphExporter | Data sharing |
-| [Visualization](reference/visualization.md) | Graph visualization | GraphVisualizer | Data exploration |
-| [Pipeline](reference/pipeline.md) | Workflow orchestration | Pipeline | Process automation |
-| [Change Management](reference/change_management.md) | Version control | TemporalVersionManager | Audit trails |
-| [Provenance](reference/provenance.md) | Data lineage | ProvenanceManager | Source tracking |
-| [Core](reference/core.md) | Framework orchestration | Semantica, Config | System management |
+| Module | Purpose | Key Classes |
+|--------|---------|-------------|
+| [ingest](reference/ingest) | Data ingestion | `FileIngestor`, `WebIngestor`, `ParquetIngestor`, `XMLIngestor` |
+| [parse](reference/parse) | Document parsing | `DocumentParser`, `DoclingParser` |
+| [split](reference/split) | Text chunking | `TextSplitter` |
+| [normalize](reference/normalize) | Data cleaning | `DataNormalizer` |
+| [semantic_extract](reference/semantic_extract) | NER & relation extraction | `NERExtractor`, `RelationExtractor`, `TripletExtractor` |
+| [kg](reference/kg) | Graph construction | `GraphBuilder`, `TemporalKnowledgeGraph`, `DistanceCalculator` |
+| [ontology](reference/ontology) | Schema management | `OntologyManager`, `SHACLGenerator` |
+| [reasoning](reference/reasoning) | Logical inference | `ReasoningEngine`, `DatalogEngine` |
+| [embeddings](reference/embeddings) | Vector embeddings | `EmbeddingGenerator` |
+| [vector_store](reference/vector_store) | Vector database | `VectorStore` |
+| [graph_store](reference/graph_store) | Graph database | `GraphStore` |
+| [triplet_store](reference/triplet_store) | RDF triple store | `TripletStore` |
+| [deduplication](reference/deduplication) | Entity resolution | `EntityResolver`, `DuplicateDetector` |
+| [conflicts](reference/conflicts) | Conflict resolution | `ConflictDetector` |
+| [context](reference/context) | Agent context & decisions | `AgentContext`, `ContextGraph` |
+| [provenance](reference/provenance) | W3C PROV-O lineage | `ProvenanceManager` |
+| [change_management](reference/change_management) | Version control | `TemporalVersionManager` |
+| [export](reference/export) | Data export | `RDFExporter` |
+| [visualization](reference/visualization) | Graph visualization | `GraphVisualizer` |
+| [pipeline](reference/pipeline) | Workflow orchestration | `Pipeline` |
+| [explorer](reference/evals) | Knowledge Explorer UI | `start_explorer` |
+| [llms](reference/llms) | LLM providers | `Groq`, `OpenAI`, `Anthropic`, `create_provider` |
+| [seed](reference/seed) | Foundation data | `SeedData` |
---
## More
-- [Getting Started](getting-started.md)
-- [Examples](examples.md)
-- [Cookbook](cookbook.md)
-- [API Reference](reference/core.md)
+<CardGroup cols={2}>
+ <Card title="Getting Started" icon="rocket" href="getting-started">
+ Your first knowledge graph in 5 minutes.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ 40+ domain notebooks with real-world examples.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/context">
+ Full technical documentation.
+ </Card>
+ <Card title="Use Cases" icon="briefcase" href="use-cases">
+ Domain-specific examples.
+ </Card>
+</CardGroup>
diff --git a/docs/quickstart.md b/docs/quickstart.md
index 9c6d5392..be9591d3 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -1,71 +1,151 @@
-# Quickstart
+---
+title: "Quickstart"
+description: "Build your first knowledge graph in 5 minutes. No configuration required."
+icon: "rocket"
+---
-Build your first knowledge graph in 5 minutes.
+<Info>
+ **v0.5.0** β€” Ontology Hub, Distance Intelligence, Parquet & XML ingestion, 12 security fixes. [What's new β†’](index#whats-new)
+</Info>
-!!! tip "Prerequisites"
- Semantica installed (`pip install semantica`). If not, see the [Installation Guide](installation.md).
+This guide walks you through a complete Semantica pipeline β€” from raw document to queryable knowledge graph with full provenance. You need Python 3.8+ and nothing else to start. An LLM API key is optional; pattern-based extraction works out of the box.
---
-## Pipeline Overview
+## Install
+
+<CodeGroup>
+
+```bash pip (recommended)
+pip install semantica
+```
+
+```bash With all extras
+pip install semantica[all]
+```
+
+```bash From source
+git clone https://github.com/Hawksight-AI/semantica.git
+cd semantica
+pip install -e ".[dev]"
+```
+
+</CodeGroup>
+
+Verify:
-```mermaid
-flowchart LR
- A[Ingest] --> B[Parse]
- B --> C[Extract]
- C --> D[Build Graph]
- D --> E[Visualize / Export]
+```bash
+python -c "import semantica; print(semantica.__version__)"
+# 0.5.0
```
---
-## Step 1 β€” Ingest
+## Full Pipeline
-Load documents from files, directories, or the web.
+<Steps>
-```python
+<Step title="Ingest">
+
+Load a document from a file, directory, URL, or database.
+
+<CodeGroup>
+
+```python File
from semantica.ingest import FileIngestor
ingestor = FileIngestor()
-sources = ingestor.ingest("data/sample.pdf")
+sources = ingestor.ingest("data/report.pdf")
+# Also accepts: .docx, .html, .json, .csv, .xlsx, .pptx, .parquet, .xml
```
-Supported formats: PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives. For web content, use `WebIngestor`.
+```python Web
+from semantica.ingest import WebIngestor
----
+ingestor = WebIngestor(max_depth=2)
+sources = ingestor.ingest("https://example.com/article")
+```
+
+```python Parquet / XML (v0.5.0)
+from semantica.ingest import ParquetIngestor, XMLIngestor
-## Step 2 β€” Parse
+# Parquet β€” single file or Hive-partitioned directory
+sources = ParquetIngestor().ingest("data/events.parquet")
-Extract structured text from raw documents.
+# XML with XSD schema validation
+sources = XMLIngestor(validate_xsd="schema.xsd").ingest("data/records/")
+```
+
+</CodeGroup>
+
+</Step>
+
+<Step title="Parse">
+
+Extract structured text and layout from raw documents.
```python
from semantica.parse import DocumentParser
parser = DocumentParser()
parsed = parser.parse(sources[0])
+
+print(parsed.text[:200]) # extracted text
+print(parsed.metadata) # title, author, date, source
```
-For complex layouts (tables, columns): use `DoclingParser` instead β€” it handles PDF tables and structured DOCX/PPTX better.
+<Tip>
+ For PDFs with tables, charts, or multi-column layouts, use `DoclingParser` β€” it uses advanced layout analysis and returns structured table data alongside text.
+</Tip>
----
+```python
+from semantica.parse import DoclingParser
+
+parser = DoclingParser()
+parsed = parser.parse(sources[0])
+print(parsed.tables) # structured table objects
+```
-## Step 3 β€” Extract Entities and Relationships
+</Step>
-```python
+<Step title="Extract Entities & Relationships">
+
+Identify named entities and extract typed relationships between them.
+
+<CodeGroup>
+
+```python Pattern-based (fast, no API key)
from semantica.semantic_extract import NERExtractor, RelationExtractor
-ner = NERExtractor()
+ner = NERExtractor(method="pattern")
entities = ner.extract(parsed)
+# Returns: [{"text": "Apple Inc.", "type": "ORGANIZATION", "confidence": 0.98}, ...]
-rel = RelationExtractor()
+rel = RelationExtractor(method="rule")
relationships = rel.extract(parsed, entities=entities)
+# Returns: [{"subject": "Steve Jobs", "predicate": "founded", "object": "Apple Inc."}, ...]
```
-Each entity gets a type, confidence score, and source reference. Relationships are extracted as typed triplets: `(subject, predicate, object)`.
+```python LLM-powered (higher accuracy)
+from semantica.semantic_extract import NERExtractor, RelationExtractor
+from semantica.llms import Groq
----
+llm = Groq(model="llama-3.3-70b-versatile")
+
+ner = NERExtractor(method="llm", llm_provider=llm)
+entities = ner.extract(parsed)
+
+rel = RelationExtractor(method="llm", llm_provider=llm)
+relationships = rel.extract(parsed, entities=entities)
+```
+
+</CodeGroup>
+
+</Step>
+
+<Step title="Build the Knowledge Graph">
-## Step 4 β€” Build the Knowledge Graph
+Assemble extracted entities and relationships into a queryable knowledge graph.
```python
from semantica.kg import GraphBuilder
@@ -73,78 +153,288 @@ from semantica.kg import GraphBuilder
builder = GraphBuilder(merge_entities=True)
graph = builder.build(entities=entities, relationships=relationships)
-print(f"{len(graph.nodes)} nodes, {len(graph.edges)} edges")
+print(f"Graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges")
+
+# Query the graph
+apple = graph.get_node("Apple Inc.")
+founders = graph.get_neighbors("Apple Inc.", predicate="founded_by")
```
-`merge_entities=True` resolves duplicates across sources automatically.
+<Note>
+ `merge_entities=True` automatically resolves duplicate entity references (e.g., "Apple", "Apple Inc.", "AAPL") using semantic similarity β€” no manual deduplication needed.
+</Note>
----
+</Step>
+
+<Step title="Visualize">
-## Step 5 β€” Visualize
+Render an interactive, zoomable knowledge graph in the browser.
```python
from semantica.visualization import GraphVisualizer
-viz = GraphVisualizer()
-viz.visualize(graph, output="graph.html") # interactive HTML
+viz = GraphVisualizer(
+ layout="force", # "force" | "hierarchical" | "circular"
+ node_color_by="type", # color nodes by entity type
+ show_confidence=True,
+)
+viz.visualize(graph, output="graph.html")
```
----
+Open `graph.html` in any browser β€” pan, zoom, click nodes for details, filter by entity type.
-## Step 6 β€” Export
+</Step>
-```python
+<Step title="Export">
+
+Export to any downstream format.
+
+<CodeGroup>
+
+```python RDF / Semantic Web
from semantica.export import RDFExporter
exporter = RDFExporter()
-rdf = exporter.export_to_rdf(graph, format="turtle")
+exporter.export_to_rdf(graph, format="turtle", output="graph.ttl")
+exporter.export_to_rdf(graph, format="json-ld", output="graph.jsonld")
+exporter.export_to_rdf(graph, format="nt", output="graph.nt")
```
-Other formats: `"json-ld"`, `"nt"`, `"xml"`, Parquet, ArangoDB AQL. See [Export Reference](reference/export.md).
+```python Parquet / Analytics
+from semantica.export import ParquetExporter
+
+exporter = ParquetExporter()
+exporter.export(graph, output_dir="output/")
+# Writes: nodes.parquet, edges.parquet β€” ready for Spark / BigQuery / Databricks
+```
+
+```python ArangoDB
+from semantica.export import ArangoDBExporter
+
+exporter = ArangoDBExporter()
+aql = exporter.export(graph)
+# Returns ready-to-run AQL INSERT statements
+```
+
+</CodeGroup>
+
+</Step>
+
+</Steps>
+
+---
+
+## Add Decision Intelligence
+
+Track every agent decision with full causal chains and provenance β€” one extra import:
+
+```python
+from semantica.context import AgentContext, ContextGraph
+from semantica.vector_store import VectorStore
+
+context = AgentContext(
+ vector_store=VectorStore(backend="faiss", dimension=768),
+ knowledge_graph=ContextGraph(advanced_analytics=True),
+ decision_tracking=True,
+)
+
+# Store a fact with provenance
+context.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%")
+
+# Record a decision
+decision_id = context.record_decision(
+ category="model_selection",
+ scenario="Choose LLM for production reasoning pipeline",
+ reasoning="GPT-4 benchmark advantage justifies 3x cost increase",
+ outcome="selected_gpt4",
+ confidence=0.91,
+)
+
+# Retrieve similar past decisions β€” prevents inconsistent choices
+precedents = context.find_precedents("model selection reasoning", limit=5)
+influence = context.analyze_decision_influence(decision_id)
+```
---
## Common Patterns
-### Process text directly (no file)
+<AccordionGroup>
+
+<Accordion title="Process raw text directly β€” no file needed" icon="text">
```python
-from semantica.semantic_extract import NERExtractor
+from semantica.semantic_extract import NERExtractor, RelationExtractor
+
+text = "Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976 in Cupertino, California."
ner = NERExtractor()
-entities = ner.extract("Apple Inc. was founded by Steve Jobs in 1976.")
+entities = ner.extract(text)
+
+rel = RelationExtractor()
+relationships = rel.extract(text, entities=entities)
```
-### Incremental build from multiple sources
+</Accordion>
+
+<Accordion title="Multi-source incremental graph build" icon="layer-group">
```python
from semantica.kg import GraphBuilder
+builder = GraphBuilder(merge_entities=True)
all_entities, all_rels = [], []
+
for doc in parsed_docs:
- all_entities.extend(ner.extract(doc))
- all_rels.extend(rel.extract(doc, entities=all_entities))
+ entities = ner.extract(doc)
+ rels = rel.extract(doc, entities=entities)
+ all_entities.extend(entities)
+ all_rels.extend(rels)
+
+graph = builder.build(entities=all_entities, relationships=all_rels)
+```
+
+</Accordion>
+
+<Accordion title="Temporal knowledge graph with point-in-time queries (v0.4.0+)" icon="clock">
+
+```python
+from semantica.kg import TemporalKnowledgeGraph
+from datetime import datetime
-graph = GraphBuilder(merge_entities=True).build(
- entities=all_entities, relationships=all_rels
+tkg = TemporalKnowledgeGraph()
+
+tkg.add_node("Tim Cook", role="CEO", valid_from=datetime(2011, 8, 24))
+tkg.add_node("Steve Jobs", role="CEO", valid_from=datetime(1997, 9, 16),
+ valid_until=datetime(2011, 8, 24))
+
+# What did the graph look like on Jan 1, 2005?
+snapshot = tkg.at(datetime(2005, 1, 1))
+print(snapshot.get_node("Steve Jobs")) # role: CEO βœ“
+```
+
+</Accordion>
+
+<Accordion title="Persistent graph store β€” Neo4j, FalkorDB, Apache AGE" icon="database">
+
+```python
+from semantica.graph_store import Neo4jStore
+from semantica.kg import GraphBuilder
+
+store = Neo4jStore(
+ uri="bolt://localhost:7687",
+ user="neo4j",
+ password="password",
)
+
+builder = GraphBuilder(merge_entities=True, graph_store=store)
+graph = builder.build(entities=entities, relationships=relationships)
+# Graph persisted to Neo4j β€” survives process restarts
```
+</Accordion>
+
+<Accordion title="Full provenance pipeline β€” W3C PROV-O" icon="link">
+
+```python
+from semantica.provenance import ProvenanceTracker
+from semantica.kg import GraphBuilder
+
+tracker = ProvenanceTracker()
+builder = GraphBuilder(merge_entities=True, provenance=tracker)
+graph = builder.build(entities=entities, relationships=relationships)
+
+# Every node and edge has full lineage
+node = graph.get_node("Apple Inc.")
+print(node.provenance)
+# {
+# "source_document": "data/report.pdf",
+# "extraction_method": "NERExtractor:llm",
+# "extracted_at": "2026-05-22T10:30:00Z",
+# "confidence": 0.98
+# }
+```
+
+</Accordion>
+
+</AccordionGroup>
+
---
## Troubleshooting
-| Problem | Fix |
-|---------|-----|
-| No entities extracted | Check the document has machine-readable text (not just scanned images) |
-| Slow processing | Process in chunks; use GPU acceleration (`pip install semantica[gpu]`) |
-| Memory errors | Reduce batch size or switch to a persistent graph backend |
+<AccordionGroup>
+
+<Accordion title="No entities extracted" icon="magnifying-glass">
+
+The document likely contains scanned images rather than machine-readable text. Use OCR:
+
+```python
+from semantica.parse import DocumentParser
+
+parser = DocumentParser(ocr=True) # enables Tesseract OCR
+parsed = parser.parse(sources[0])
+```
+
+</Accordion>
+
+<Accordion title="Slow processing on large corpora" icon="gauge">
+
+Enable parallel processing and GPU acceleration:
+
+```bash
+pip install semantica[gpu]
+```
+
+```python
+from semantica.pipeline import Pipeline
+
+pipeline = Pipeline(workers=8, batch_size=32)
+pipeline.run(sources)
+```
+
+</Accordion>
+
+<Accordion title="Memory errors" icon="memory">
+
+Switch from in-memory NetworkX to a persistent backend:
+
+```python
+from semantica.graph_store import FalkorDBStore
+
+store = FalkorDBStore(host="localhost", port=6379)
+builder = GraphBuilder(merge_entities=True, graph_store=store)
+```
+
+</Accordion>
+
+<Accordion title="NER falls back to pattern mode on enterprise gateway" icon="triangle-exclamation">
+
+Fixed in **v0.5.0**. Upgrade:
+
+```bash
+pip install --upgrade semantica
+```
+
+</Accordion>
+
+</AccordionGroup>
---
## Next Steps
-- [Core Concepts](concepts.md) β€” understand how knowledge graphs and reasoning work
-- [Modules Guide](modules.md) β€” every module explained
-- [Use Cases](use-cases.md) β€” domain-specific examples
-- [Cookbook](cookbook.md) β€” interactive Jupyter notebooks for each step
+<CardGroup cols={2}>
+ <Card title="Core Concepts" icon="book-open" href="concepts">
+ Knowledge graphs, ontologies, reasoning engines β€” the mental model behind Semantica.
+ </Card>
+ <Card title="Examples" icon="code" href="examples">
+ 15+ copy-paste examples for healthcare, finance, legal, and cybersecurity.
+ </Card>
+ <Card title="API Reference" icon="rectangle-terminal" href="reference/context">
+ Complete documentation for every module, class, and parameter.
+ </Card>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ 40+ interactive Jupyter notebooks with real-world datasets.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/change_management.md b/docs/reference/change_management.md
index 47d40499..7f74124f 100644
--- a/docs/reference/change_management.md
+++ b/docs/reference/change_management.md
@@ -1,463 +1,113 @@
-# Change Management
-
-**Enterprise-grade version control and audit trails for knowledge graphs and ontologies with data integrity verification**
-
-## Overview
-
-The Semantica change management module provides enterprise-grade version control, audit trails, and compliance tracking for knowledge graphs and ontologies. Designed for high-stakes domains where every change must be tracked, verified, and auditable with complete data integrity guarantees.
-
-<div class="grid cards" markdown>
-
-- :material-history:{ .lg .middle } **Version Control**
-
- ---
-
- Complete snapshot management with SHA-256 integrity verification
-
-- :material-database:{ .lg .middle } **Dual Storage**
-
- ---
-
- InMemory (development) and SQLite (production) with ACID guarantees
-
-- :material-graph:{ .lg .middle } **Knowledge Graph Versioning**
-
- ---
-
- Entity and relationship-level change tracking with detailed diffs
-
-- :material-shape:{ .lg .middle } **Ontology Versioning**
-
- ---
-
- Structural change tracking for classes, properties, and axioms
-
-- :material-clipboard-check:{ .lg .middle } **Audit Trail Compliance**
-
- ---
-
- Complete change logs with author attribution and timestamps
-
-- :material-shield-check:{ .lg .middle } **Data Integrity**
-
- ---
-
- SHA-256 checksums for tamper detection and verification
-
-- :material-compare:{ .lg .middle } **Change Comparison**
-
- ---
-
- Detailed diff algorithms for entities, relationships, and ontology structures
-
-- :material-backup-restore:{ .lg .middle } **Backward Compatibility**
+---
+title: "Change Management Module"
+description: "Enterprise-grade version control, SHA-256 checksums, and audit trails for knowledge graphs."
+icon: "clock-rotate-left"
+---
- ---
+> Version control and audit trails for knowledge graphs with data integrity verification.
- Legacy support for existing ontology version management
+---
-</div>
+## Overview
-- **Enterprise Version Control** β€” Complete snapshot management with SHA-256 integrity verification
-- **Dual Storage Backends** β€” InMemory (development) and SQLite (production) with ACID guarantees
-- **Knowledge Graph Versioning** β€” Entity and relationship-level change tracking with detailed diffs
-- **Ontology Versioning** β€” Structural change tracking for classes, properties, and axioms
-- **Audit Trail Compliance** β€” Complete change logs with author attribution and timestamps
-- **Data Integrity** β€” SHA-256 checksums for tamper detection and verification
-- **Change Comparison** β€” Detailed diff algorithms for entities, relationships, and ontology structures
-- **Backward Compatibility** β€” Legacy support for existing ontology version management
+The **Change Management Module** provides version control for knowledge graphs β€” SHA-256 checksums, full snapshot history, diff analysis, and rollback protection.
---
-## Quick Start
+## TemporalVersionManager
```python
from semantica.change_management import TemporalVersionManager
-# Initialize version manager
manager = TemporalVersionManager(storage_path="versions.db")
-# Create versioned snapshot
-snapshot = manager.create_snapshot(
- graph={"entities": [...], "relationships": [...]},
- version_label="v1.0",
+# Create a snapshot
+snapshot_id = manager.create_snapshot(
+ graph=kg,
+ version="v1.0",
- description="Initial knowledge graph"
+ message="Initial knowledge graph"
)
-# Compare versions
-diff = manager.compare_versions("v1.0", "v2.0")
+print(f"Snapshot {snapshot_id} β€” checksum: {manager.get_checksum(snapshot_id)}")
```
-**What this does:**
-- Initializes version manager with persistent SQLite storage
-- Creates a versioned snapshot of knowledge graph data
-- Compares two versions to detect changes
-- Provides complete audit trail with author attribution
-
---
-## Core Components
-
-### ChangeLogEntry
+## Versioning
-Standardized metadata for tracking version changes with validation.
-
-```python
-from semantica.change_management import ChangeLogEntry
-
-@dataclass
-class ChangeLogEntry:
- timestamp: str # ISO 8601 format
- author: str # Email address
- description: str # Max 500 characters
- change_id: Optional[str] = None
-```
-
-**Key Method:**
-- `create_now(author, description, change_id=None)` - Create entry with current timestamp
-
-### Storage Backends
-
-**InMemoryVersionStorage** β€” Fast, volatile storage for development and testing.
```python
-from semantica.change_management import InMemoryVersionStorage
-
-storage = InMemoryVersionStorage()
-```
+# List all versions
+versions = manager.list_versions()
+for v in versions:
+ print(f"{v.version} β€” {v.author} β€” {v.created_at} β€” {v.checksum[:8]}...")
-**SQLiteVersionStorage** β€” Persistent storage with ACID guarantees for production.
-```python
-from semantica.change_management import SQLiteVersionStorage
+# Get a specific version
+kg_v1 = manager.get_version("v1.0")
-storage = SQLiteVersionStorage("versions.db")
+# Rollback to a previous version
+manager.rollback(target_version="v1.0", allow_data_loss=False)
```
-**VersionStorage (Abstract)** β€” Base interface for custom storage implementations.
-
-**Core Methods:**
-- `save(snapshot)` - Store version snapshot
-- `get(label)` - Retrieve by version label
-- `list_all()` - List all versions
-- `exists(label)` - Check if version exists
-- `delete(label)` - Remove version
-
---
-## Version Managers
-
-### BaseVersionManager
-
-Abstract base class providing common version management functionality.
-
-```python
-from semantica.change_management import BaseVersionManager
-
-manager = BaseVersionManager(storage_path="versions.db")
-```
-
-**Common Methods:**
-- `list_versions()` - Get all version metadata
-- `get_version(label)` - Retrieve specific version
-- `verify_checksum(snapshot)` - Validate data integrity
-
-### TemporalVersionManager
-
-**Knowledge Graph Version Management**
-
-Perfect for tracking changes in knowledge graphs with entity and relationship diffs.
+## Diff Analysis
```python
-from semantica.change_management import TemporalVersionManager
+diff = manager.diff("v1.0", "v2.0")
-manager = TemporalVersionManager(storage_path="kg_versions.db")
-
-# Create snapshot
-snapshot = manager.create_snapshot(
- graph={
- "entities": [
- {"id": "e1", "name": "Entity 1", "type": "Person"},
- {"id": "e2", "name": "Entity 2", "type": "Organization"}
- ],
- "relationships": [
- {"source": "e1", "target": "e2", "type": "works_for"}
- ]
- },
- version_label="v1.0",
- author="[email protected]",
- description="Initial knowledge graph"
-)
+print(f"Added nodes: {len(diff.added_nodes)}")
+print(f"Removed nodes: {len(diff.removed_nodes)}")
+print(f"Modified edges: {len(diff.modified_edges)}")
-# Compare versions with detailed diffs
-diff = manager.compare_versions("v1.0", "v2.0")
-print(f"Entities added: {diff['summary']['entities_added']}")
-print(f"Relationships modified: {diff['summary']['relationships_modified']}")
-```
-
-**Key Features:**
-- Entity-level change tracking
-- Relationship diff analysis
-- SHA-256 checksums for integrity
-- Detailed change summaries
-
-### OntologyVersionManager
-
-**Ontology Version Management**
-
-Designed for structural changes in ontologies with class, property, and axiom tracking.
-
-```python
-from semantica.change_management import OntologyVersionManager
-
-manager = OntologyVersionManager(storage_path="ontology_versions.db")
-
-# Create ontology snapshot
-snapshot = manager.create_snapshot(
- ontology={
- "uri": "https://example.com/ontology",
- "structure": {
- "classes": ["Person", "Organization"],
- "properties": ["name", "email"],
- "axioms": ["Person hasEmail exactly 1 Email"]
- }
- },
- version_label="ont_v1.0",
- author="[email protected]",
- description="Initial ontology design"
-)
-
-# Compare structural changes
-diff = manager.compare_versions("ont_v1.0", "ont_v2.0")
-print(f"Classes added: {diff['classes_added']}")
-print(f"Axioms modified: {diff['axioms_modified']}")
-```
-
-**Key Features:**
-- Class and property tracking
-- Axiom change detection
-- Structural comparison
-- Import/export support
-
----
-
-## Incremental / Delta processing
-
-For large-scale knowledge graphs, reprocessing the entire dataset on every update is computationally expensive.
-Semantica supports **Delta-Aware Pipelines**, allowing you to compute the exact differences (added and removed triples)
-between the two graph snapshots and run validation, enrichment, or export jobs *only* on the changes.
-
-**Delta Pipeline Example**
-
-```python
-from semantica.change_management import TemporalVersionManager
-from semantica.pipeline import PipelineBuilder, ExecutionEngine
-
-# a. Initialize your managers
-version_manager = TemporalVersionManager(store_graph="kg_version.db")
-triplet_store = get_my_triplet_store()
-
-# b. Build a delta-aware pipeline
-builder = PipelineBuilder()
-builder.add_step(
- step_name="validate_changes",
- step_type="validation",
- handler=my_validation_handler,
- delta_mode=True, # Enables incremental processing
- base_version_id="v1.0",
- target_version_id="v1.1",
-)
-
-pipeline = builder.build("incremental_nightly_job")
-
-# c. Execute the pipeline
-engine = ExecutionEngine()
-
-# The engine dynamically intercepts the flow, computes the delta on the
-# database backend, and passes ONLY the changed triples to the handler.
-result = engine.execute_pipeline(
- pipeline,
- data={}, # Is ignored in delta mode
- version_manager=version_manager,
- triplet_store=triplet_store
-)
+for change in diff.changes:
+ print(f" [{change.type}] {change.element}: {change.description}")
```
---
-## Data Integrity
-
-### compute_checksum
-
-Generate SHA-256 checksum for data integrity verification.
-
-```python
-from semantica.change_management import compute_checksum
-
-data = {"entities": [...], "relationships": [...]}
-checksum = compute_checksum(data)
-print(f"SHA-256: {checksum}")
-```
-
-**Use cases:**
-- Verify data integrity before storing snapshots
-- Detect unauthorized modifications to version data
-- Ensure consistency across distributed systems
-- Generate unique identifiers for data versions
-
-### verify_checksum
-
-Validate data integrity using stored checksums.
+## Integrity Verification
```python
-from semantica.change_management import verify_checksum
-
-snapshot = manager.get_version("v1.0")
-is_valid = verify_checksum(snapshot)
+# Verify current graph against stored checksum
+is_valid = manager.verify_integrity(kg, version="v2.0")
if not is_valid:
- print("WARNING: Data integrity compromised!")
-```
-
-**Use cases:**
-- Validate snapshot integrity after retrieval
-- Detect data corruption or tampering
-- Ensure compliance with data integrity requirements
-- Verify backup and restore operations
-
----
-
-## Legacy Support
-
-### VersionManager
-
-Original ontology version manager for backward compatibility.
-
-```python
-from semantica.change_management import VersionManager, OntologyVersion
-```
-
-**Note:** Use `OntologyVersionManager` for new projects.
-
----
-
-## Error Handling
-
-```python
-from semantica.utils.exceptions import ValidationError, ProcessingError
-
-try:
- snapshot = manager.create_snapshot(...)
-except ValidationError as e:
- print(f"Invalid input: {e}")
-except ProcessingError as e:
- print(f"Operation failed: {e}")
+ print("Warning: Graph has been modified since v2.0 was created")
```
-**Common Errors:**
-- `ValidationError` - Invalid email, missing fields, bad timestamps
-- `ProcessingError` - Database issues, file system errors
-
----
-
-## Best Practices
-
-### Performance Tips
-- Use `InMemoryVersionStorage` for development/testing
-- Use `SQLiteVersionStorage` for production
-- Implement retention policies for old versions
-
-### Security Considerations
-- Validate author emails for audit trails
-- Use checksums for data integrity
-- Store sensitive data with appropriate permissions
-
-### Usage Patterns
-```python
-from semantica.change_management import TemporalVersionManager
-
-# Development workflow
-dev_manager = TemporalVersionManager() # In-memory
-
-# Production workflow
-prod_manager = TemporalVersionManager(
- storage_path="secure/production_versions.db"
-)
-
-# Audit trail generation
-for version in prod_manager.list_versions():
- print(f"{version['timestamp']}: {version['description']} by {version['author']}")
-```
+SHA-256 checksums are computed over the serialized graph to detect unauthorized modifications.
---
-## Ontology Diff & Migration
-
-Semantica allows you to treat ontology schema changes with the same rigor as database migrations. By comparing two versions, you can generate a machine-readable diff and a structured impact report to catch breaking changes before they reach production.
-
-
-**Comparing Versions**
-
-The `OntologyEngine` provides a high-level API to orchestrate the comparison of two schema versions.
+## Audit Trail
```python
-from semantica.ontology.engine import OntologyEngine
-
-engine = OntologyEngine()
-
-# Generate a migration impact report between v1.0 and v2.0
-report = engine.compare_versions(
- base_id="v1.0",
- target_id="v2.0"
-)
-
-print(f"Total changes detected: {report['summary']['total_changes']}")
+# Full audit trail for an entity
+trail = manager.get_audit_trail(entity_id="apple_inc")
+for entry in trail:
+ print(f"{entry.timestamp} β€” {entry.author}: {entry.action} β€” {entry.description}")
+
+# Export audit trail
+manager.export_audit_trail("audit.csv", format="csv")
+manager.export_audit_trail("audit.json", format="json")
```
---
-**Report Format**
-
-The `compare_versions` method returns a dictionary with a machine-readable diff and a human-readable impact analysis:
-
-```json
-{
- "summary": {
- "total_changes": 12
- },
- "impact_classification": {
- "breaking": [
- {
- "entity_uri": "http://example.org/Person",
- "severity": "critical",
- "description": "Class Person removed.",
- "mitigation": "Migrate orphaned instances."
- }
- ],
- "potentially_breaking": [],
- "safe": []
- },
- "recommendations": [
- "[BREAKING] Schedule downtime or validate existing data."
- ],
- "diff": {
- "added_classes": [],
- "removed_classes": [],
- "changed_classes": [],
- "added_properties": [],
- "removed_properties": [],
- "changed_properties": []
- },
- "validation_results": {
- "valid": true,
- "consistent": true,
- "satisfiable": true,
- "errors": [],
- "warnings": []
- },
- "graph_validation": {
- "valid": false,
- "errors": ["Instance data violates new domain constraint"],
- "warnings": []
- }
-}
-```
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Provenance" icon="link" href="provenance">
+ W3C PROV-O lineage tracking.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The graph being versioned.
+ </Card>
+ <Card title="Export" icon="file-export" href="export">
+ Export versioned snapshots.
+ </Card>
+ <Card title="Conflicts" icon="triangle-exclamation" href="conflicts">
+ Detect conflicts introduced between versions.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/conflicts.md b/docs/reference/conflicts.md
index 8a9d051d..da38f6b6 100644
--- a/docs/reference/conflicts.md
+++ b/docs/reference/conflicts.md
@@ -1,348 +1,121 @@
-# Conflicts
-
-> **Comprehensive conflict detection and resolution system for managing data discrepancies across multiple sources.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-alert-decagram:{ .lg .middle } **Multi-Source Detection**
-
- ---
-
- Detect conflicts across values, types, relationships, and temporal data
-
-- :material-scale-balance:{ .lg .middle } **Resolution Strategies**
-
- ---
-
- Resolve using voting, credibility, recency, or confidence scores
-
-- :material-chart-line:{ .lg .middle } **Conflict Analysis**
-
- ---
-
- Analyze patterns, trends, and severity of data discrepancies
-
-- :material-source-branch:{ .lg .middle } **Source Tracking**
-
- ---
-
- Track data provenance and source credibility
-
-- :material-clipboard-check:{ .lg .middle } **Investigation Guides**
-
- ---
-
- Generate automated guides for manual conflict resolution
-
-- :material-history:{ .lg .middle } **Traceability**
-
- ---
-
- Maintain full traceability of resolution decisions
-
-</div>
-
-!!! tip "When to Use"
- - **Data Integration**: When merging data from multiple sources with overlapping entities
- - **Quality Assurance**: To identify inconsistent data in your knowledge graph
- - **Truth Maintenance**: To establish a "single source of truth" from noisy data
-
+title: "Conflicts Module"
+description: "Multi-source conflict detection and resolution β€” value, type, temporal, and logical conflicts."
+icon: "triangle-exclamation"
---
-## βš™οΈ Algorithms Used
-
-### Conflict Detection
-
-The conflict detection system identifies discrepancies using:
-
-- **Value Comparison**: Equality checking with type normalization
-- **Type Mismatch**: Entity type hierarchy validation
-- **Temporal Analysis**: Timestamp comparison for time-based conflicts
-- **Logical Consistency**: Rule-based validation (e.g., "Person cannot be Organization")
-- **Severity Calculation**: Multi-factor scoring based on:
- - Property importance weights
- - Value difference magnitude
- - Number of conflicting sources
-
-### Conflict Resolution
-
-The module provides multiple resolution strategies:
-
-- **Voting (Majority Rule)**: `` `max(frequency(values))` `` using Counter
-- **Credibility Weighted**: `` `Ξ£(value_i * source_credibility_i) / Ξ£(source_credibility)` ``
-- **Temporal Selection**: Select value with latest timestamp (`` `max(timestamp)` ``)
-- **Confidence Selection**: Select value with highest extraction confidence
-- **Hybrid Resolution**: Waterfall approach (e.g., Voting β†’ Credibility β†’ Recency)
-
-### Analysis & Tracking
-- **Pattern Identification**: Frequency analysis of conflict types
-- **Credibility Scoring**: Historical accuracy tracking per source
-- **Traceability**: Graph-based lineage of values and decisions
+> Comprehensive conflict detection and resolution for data discrepancies across multiple sources.
---
-## Main Classes
-
-### ConflictDetector
+## Overview
-Detects conflicts across entities and properties.
+When multiple sources disagree on the same fact, the **Conflicts Module** detects and resolves the conflict rather than silently picking one value.
-**Methods:**
+Detection types: **value**, **type**, **temporal**, and **logical** conflicts.
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `detect_conflicts(entities, entity_type)` | Detect all conflicts | Multi-pass detection |
-| `detect_value_conflicts(entities, property_name, entity_type)` | Check specific property | Value comparison |
-| `detect_type_conflicts(entities)` | Check entity types | Hierarchy validation |
-| `detect_temporal_conflicts(entities)` | Check timestamps | Time-series analysis |
-| `detect_logical_conflicts(entities)` | Check logical inconsistencies | Rule validation |
-| `detect_relationship_conflicts(relationships)` | Check relationship conflicts | Relationship comparison |
-| `detect_entity_conflicts(entities, entity_type)` | Detect all conflicts for entity | Multi-property detection |
-| `get_conflict_report()` | Generate conflict report | Report generation |
+---
-**Example:**
+## ConflictDetector
```python
from semantica.conflicts import ConflictDetector
detector = ConflictDetector()
-conflicts = detector.detect_conflicts([
- {"id": "1", "name": "Apple", "source": "doc1"},
- {"id": "1", "name": "Apple Inc.", "source": "doc2"}
-])
+conflicts = detector.detect_conflicts(kg)
for conflict in conflicts:
- print(f"Conflict on {conflict.property_name}: {conflict.conflicting_values}")
-```
-
-### ConflictResolver
-
-Resolves detected conflicts using configured strategies.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `resolve_conflicts(conflicts, strategy)` | Resolve list of conflicts | Strategy pattern |
-| Strategies: `voting`, `credibility_weighted`, `most_recent`, `first_seen`, `highest_confidence`, `manual_review` | Various resolution strategies | See algorithm descriptions |
-
-**Example:**
-
-```python
-from semantica.conflicts import ConflictResolver
-
-resolver = ConflictResolver(default_strategy="credibility_weighted")
-results = resolver.resolve_conflicts(conflicts)
-
-for result in results:
- if result.resolved:
- print(f"Resolved conflict {result.conflict_id}: {result.resolved_value}")
- print(f"Strategy used: {result.resolution_strategy}")
-```
-
-### SourceTracker
-
-Tracks source information and credibility scores.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `track_property_source(entity_id, property_name, value, source)` | Track source for property value |
-| `track_entity_source(entity_id, source)` | Track source for entity |
-| `track_relationship_source(relationship_id, source)` | Track source for relationship |
-| `get_source_credibility(document)` | Get current credibility score |
-| `set_source_credibility(document, score)` | Set source credibility score |
-| `get_property_sources(entity_id, property_name)` | Get sources for a property |
-| `get_entity_sources(entity_id)` | Get all sources for an entity |
-| `generate_traceability_chain(entity_id, property_name)` | Generate traceability chain |
-| `generate_source_report(entity_id)` | Generate source analysis report |
-
-**Example:**
-
-```python
-from semantica.conflicts import SourceTracker, SourceReference
-
-tracker = SourceTracker()
-tracker.set_source_credibility("reliable_source", 0.9)
-tracker.set_source_credibility("noisy_source", 0.4)
-
-# Track property sources
-source = SourceReference(document="doc1", confidence=0.9)
-tracker.track_property_source("entity_1", "name", "Apple Inc.", source)
-```
-
-### InvestigationGuideGenerator
-
-Generates human-readable guides for manual resolution.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `generate_guide(conflict, additional_context)` | Create investigation guide for a conflict |
-| `generate_guides(conflicts, additional_context)` | Create investigation guides for multiple conflicts |
-| `export_investigation_checklist(guide, format)` | Export guide as checklist (text/markdown) |
-| `generate_conflict_report(conflicts, format)` | Generate comprehensive conflict report |
-
-**Example:**
-
-```python
-from semantica.conflicts import InvestigationGuideGenerator
-
-generator = InvestigationGuideGenerator()
-guide = generator.generate_guide(conflict)
-checklist = generator.export_investigation_checklist(guide, format="markdown")
-```
-
-### ConflictAnalyzer
-
-Analyzes conflict patterns, trends, and provides recommendations.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `analyze_conflicts(conflicts)` | Comprehensive conflict analysis |
-| `analyze_trends(conflicts)` | Temporal trend analysis |
-| `generate_insights_report(conflicts)` | Generate insights report |
-
-**Example:**
-
-```python
-from semantica.conflicts import ConflictAnalyzer
-
-analyzer = ConflictAnalyzer()
-analysis = analyzer.analyze_conflicts(conflicts)
-trends = analyzer.analyze_trends(conflicts)
-insights = analyzer.generate_insights_report(conflicts)
+ print(f"Conflict on '{conflict.entity}' β€” {conflict.attribute}")
+ print(f" Source A: {conflict.value_a} (from {conflict.source_a})")
+ print(f" Source B: {conflict.value_b} (from {conflict.source_b})")
+ print(f" Type: {conflict.conflict_type}")
```
---
-## Configuration
-
-### Environment Variables
+## Detection Types
-```bash
-export CONFLICT_DEFAULT_STRATEGY=voting
-export CONFLICT_SIMILARITY_THRESHOLD=0.85
-export CONFLICT_AUTO_RESOLVE=true
+```python
+# Detect specific types only
+conflicts = detector.detect_conflicts(
+ kg,
+ types=["value", "temporal"] # value | type | temporal | logical
+)
```
-### YAML Configuration
-
-```yaml
-conflicts:
- default_strategy: voting
- auto_resolve: true
-
- strategies:
- voting:
- min_votes: 2
- credibility:
- default_score: 0.5
-
- weights:
- name: 1.0
- description: 0.5
- date: 0.8
-```
+**Value conflicts** β€” same entity, same attribute, different values across sources.
+**Type conflicts** β€” same entity classified as different types in different sources.
+**Temporal conflicts** β€” overlapping validity windows with contradictory facts.
+**Logical conflicts** β€” facts that violate ontology axioms or constraints.
---
-## Integration Examples
-
-### Pipeline Integration
+## Conflict Resolution
```python
-from semantica.conflicts import ConflictDetector, ConflictResolver
-from semantica.ingest import FileIngestor
-from semantica.parse import DocumentParser
-from semantica.semantic_extract import NERExtractor
-from semantica.kg import GraphBuilder
-
-# 1. Build knowledge base from multiple sources using individual modules
-ingestor = FileIngestor()
-parser = DocumentParser()
-ner = NERExtractor()
-builder = GraphBuilder()
-
-all_entities = []
-for source in ["source1.pdf", "source2.html"]:
- doc = ingestor.ingest_file(source)
- parsed = parser.parse_document(source)
- text = parsed.get("full_text", "")
- entities = ner.extract_entities(text)
- all_entities.extend(entities)
-
-kg = builder.build_graph(entities=all_entities, relationships=[])
-entities = all_entities
-
-# 3. Detect conflicts
-detector = ConflictDetector()
-conflicts = detector.detect_value_conflicts(entities, "revenue")
+from semantica.conflicts import ConflictResolver
-# 4. Resolve conflicts
-resolver = ConflictResolver(default_strategy="credibility_weighted")
-resolutions = resolver.resolve_conflicts(
+resolver = ConflictResolver()
+resolved_kg = resolver.resolve(
+ kg,
conflicts,
- strategy="credibility_weighted"
+ strategy="most_recent" # see strategies below
)
-
-# 5. Apply resolutions
-for resolution in resolutions:
- if resolution.resolved:
- print(f"Final value for {resolution.conflict_id}: {resolution.resolved_value}")
```
----
-
-## Best Practices
+Resolution strategies:
-1. **Define Source Credibility**: Always assign credibility scores to your sources if possible.
-2. **Use Hybrid Strategies**: Voting is good for categorical data, Recency for temporal data.
-3. **Keep Humans in the Loop**: Use `InvestigationGuideGenerator` for high-severity conflicts.
-4. **Normalize First**: Ensure data is normalized (dates, numbers) before conflict detection to avoid false positives.
+| Strategy | Description |
+|----------|-------------|
+| `most_recent` | Prefer the most recently updated fact |
+| `most_reliable` | Prefer the source with the highest reliability score |
+| `majority_vote` | Use the value agreed upon by most sources |
+| `highest_confidence` | Prefer the fact with the highest confidence score |
+| `flag_for_review` | Mark conflicting facts for manual resolution |
---
-## Troubleshooting
-
-**Issue**: Too many false positives on string fields.
-**Solution**: Enable fuzzy matching or increase similarity threshold.
+## Source Reliability Scoring
```python
-detector = ConflictDetector(
- string_similarity_threshold=0.9, # Stricter matching
- ignore_case=True
+resolver = ConflictResolver(
+ source_reliability={
+ "pubmed": 0.95,
+ "wikipedia": 0.80,
+ "user_input": 0.60
+ }
)
+resolved_kg = resolver.resolve(kg, conflicts, strategy="most_reliable")
```
-**Issue**: Resolution favoring wrong source.
-**Solution**: Check and adjust source credibility scores.
+---
+
+## Conflict Report
```python
-tracker.set_source_credibility("bad_source", 0.1)
+report = detector.generate_report(conflicts)
+print(f"Total conflicts: {report.total}")
+print(f"By type: {report.by_type}")
+print(f"Most conflicted entities: {report.top_entities[:5]}")
+
+report.export("conflicts.json")
```
---
## See Also
-- [Deduplication Module](deduplication.md) - For merging duplicate entities
-- [Normalize Module](normalize.md) - For pre-processing data
-- [Modules Guide](../modules.md#quality-assurance) - Quality assurance overview
-
-## Cookbook
-
-Interactive tutorials to learn conflict detection and resolution:
-
-- **[Conflict Detection & Resolution](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb)**: Strategies for handling contradictory information from multiple sources
- - **Topics**: Truth discovery, voting, confidence scoring, conflict resolution strategies
- - **Difficulty**: Advanced
- - **Use Cases**: Multi-source data integration, quality assurance
+<CardGroup cols={2}>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Resolve duplicate entities before conflict detection.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Logical conflicts use ontology axioms.
+ </Card>
+ <Card title="Provenance" icon="link" href="provenance">
+ Track which source each conflicting fact came from.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The graph being checked for conflicts.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/context.md b/docs/reference/context.md
index f0d0fb74..70accb62 100644
--- a/docs/reference/context.md
+++ b/docs/reference/context.md
@@ -1,94 +1,63 @@
-# Context Module Reference
-
-> **The intelligent brain for AI agents, providing memory, decision tracking, and knowledge organization with easy-to-use interfaces that make building smart agents simple and effective.**
-
+---
+title: "Context Module"
+description: "Agent context graphs, decision tracking, causal chains, and precedent search."
+icon: "brain"
---
-## 🎯 Overview
-
-The **Context Module** gives your AI agents the ability to **remember**, **learn**, and **make smarter decisions** through intelligent memory management and knowledge organization. It's designed to be both powerful for production use and simple enough for rapid development.
-
-### Key Capabilities
+> The intelligent brain for AI agents, providing memory, decision tracking, and knowledge organization.
-<div class="grid cards" markdown>
+---
-- :material-brain:{ .lg .middle } **Smart Memory**
+## Overview
- ---
+The **Context Module** gives your AI agents the ability to remember, learn, and make smarter decisions through intelligent memory management and knowledge organization.
+<CardGroup cols={2}>
+ <Card title="Smart Memory" icon="memory">
Human-like memory that stores conversations, learns from experience, and retrieves relevant information when needed.
-
-- :material-graph-outline:{ .lg .middle } **Decision Intelligence**
-
- ---
-
+ </Card>
+ <Card title="Decision Intelligence" icon="diagram-project">
Track decisions, learn from past choices, and make consistent, improving decisions over time.
-
-- :material-lightbulb:{ .lg .middle } **Easy-to-Use API**
-
- ---
-
+ </Card>
+ <Card title="Easy-to-Use API" icon="code">
Simple methods that make complex features accessible without overwhelming complexity.
-
-- :material-search:{ .lg .middle } **Smart Retrieval**
-
- ---
-
- Find relevant information quickly using hybrid search that understands context and relationships.
-
-- :material-account-tree:{ .lg .middle } **Knowledge Organization**
-
- ---
-
+ </Card>
+ <Card title="Smart Retrieval" icon="magnifying-glass">
+ Find relevant information using hybrid search that understands context and relationships.
+ </Card>
+ <Card title="Knowledge Organization" icon="sitemap">
Build intelligent knowledge graphs that understand relationships and context.
-
-- :material-trending-up:{ .lg .middle } **Learning & Analytics**
-
- ---
-
- Get insights about agent performance, decision patterns, and knowledge growth.
-
-- :material-security:{ .lg .middle } **Production Ready**
-
- ---
-
+ </Card>
+ <Card title="Production Ready" icon="check-circle">
Scalable, reliable, and tested for real-world applications.
+ </Card>
+</CardGroup>
-</div>
-
-!!! tip "Perfect For"
- - **AI Agents** that need to remember conversations and learn from decisions
- - **Chatbots** that become smarter with every interaction
- - **Decision Systems** that need to track choices and learn from patterns
- - **Knowledge Management** that organizes information intelligently
- - **Production Applications** that require reliable, scalable solutions
+<Tip>
+ **Perfect for:** AI agents that need to remember conversations and learn from decisions, chatbots that become smarter with every interaction, and decision systems that need compliance-ready audit trails.
+</Tip>
---
-## πŸ€– AgentContext - Your Agent's Brain
+## AgentContext
-The main interface that makes your agent intelligent. It handles memory, decisions, and knowledge organization automatically.
+The main interface that makes your agent intelligent. Handles memory, decisions, and knowledge organization automatically.
### Quick Start
+
```python
from semantica.context import AgentContext
from semantica.vector_store import VectorStore
-# Create your intelligent agent
agent = AgentContext(vector_store=VectorStore(backend="inmemory", dimension=384))
-# Your agent can now remember things
memory_id = agent.store("User asked about Python programming")
-print(f"Agent remembered: {memory_id}")
-
-# And find information when needed
results = agent.retrieve("Python tutorials")
-print(f"Agent found {len(results)} relevant memories")
```
-### Easy Decision Learning
+### Decision Learning
+
```python
-# Your agent learns from its decisions
decision_id = agent.record_decision(
category="content_recommendation",
scenario="User wants Python tutorial",
@@ -97,42 +66,12 @@ decision_id = agent.record_decision(
confidence=0.85
)
-# Your agent can now find similar past decisions
similar_decisions = agent.find_precedents("Python tutorial", limit=3)
-print(f"Agent found {len(similar_decisions)} similar past decisions")
```
-### Getting Smarter Over Time
-```python
-# Enable all learning features
-smart_agent = AgentContext(
- vector_store=vector_store,
- decision_tracking=True, # Learn from decisions
- graph_expansion=True, # Find related information
- advanced_analytics=True, # Understand patterns
- kg_algorithms=True, # Advanced analysis
- vector_store_features=True
-)
+### Full Setup
-# Get insights about your agent's learning
-insights = smart_agent.get_context_insights()
-print(f"Total decisions learned: {insights.get('total_decisions', 0)}")
-print(f"Decision categories: {list(insights.get('categories', {}).keys())}")
-```
-
-### Core Methods
-
-| Method | What It Does | When to Use |
-|--------|-------------|------------|
-| `store(content, ...)` | Remember information | Store conversations, facts, user preferences |
-| `retrieve(query, ...)` | Find relevant memories | Search for information when needed |
-| `record_decision(category, scenario, reasoning, outcome, confidence, ...)` | Learn from decisions | Track choices and improve over time |
-| `find_precedents(scenario, category, ...)` | Find similar decisions | Make consistent choices based on experience |
-| `get_context_insights()` | Understand performance | Get analytics about your agent |
-
-### Advanced Features
```python
-# Enable all features for maximum intelligence
agent = AgentContext(
vector_store=vector_store,
knowledge_graph=ContextGraph(advanced_analytics=True),
@@ -143,7 +82,23 @@ agent = AgentContext(
vector_store_features=True
)
-# Query with multi-hop reasoning (GraphRAG)
+insights = agent.get_context_insights()
+```
+
+### Core Methods
+
+| Method | Description |
+|--------|-------------|
+| `store(content, ...)` | Remember information |
+| `retrieve(query, ...)` | Find relevant memories |
+| `record_decision(category, scenario, reasoning, outcome, confidence, ...)` | Learn from decisions |
+| `find_precedents(scenario, category, ...)` | Find similar past decisions |
+| `analyze_decision_influence(decision_id)` | Analyze downstream impact |
+| `get_context_insights()` | Get analytics about your agent |
+
+### GraphRAG with Multi-Hop Reasoning
+
+```python
from semantica.llms import Groq
import os
@@ -161,48 +116,25 @@ print(f"Reasoning: {result['reasoning_path']}")
---
-## πŸ—οΈ ContextGraph - Knowledge Organization
+## ContextGraph
+
+Organizes complex information and relationships into intelligent knowledge networks.
-When you need to organize complex information and understand relationships, ContextGraph helps you build intelligent knowledge networks.
+### Building a Knowledge Graph
-### Easy Knowledge Graph Building
```python
from semantica.context import ContextGraph
-# Create a knowledge graph
knowledge = ContextGraph(advanced_analytics=True)
-# Add things you want to remember (nodes)
knowledge.add_node("Python", "language", properties={"popularity": "high"})
-knowledge.add_node("Programming", "concept", properties={"type": "skill"})
knowledge.add_node("FastAPI", "framework", properties={"language": "Python"})
-
-# Connect related things (edges)
-knowledge.add_edge("Python", "Programming", "related_to")
knowledge.add_edge("Python", "FastAPI", "supports")
-knowledge.add_edge("FastAPI", "Programming", "used_for")
```
-### Easy Decision Management
-```python
-# Record decisions in your knowledge graph
-from semantica.context.decision_models import Decision
-from datetime import datetime
+### Decision Management
-decision = Decision(
- decision_id="tech_choice_001",
- category="technology_choice",
- scenario="Framework selection for web API",
- reasoning="FastAPI provides better performance for Python APIs",
- outcome="selected_fastapi",
- confidence=0.92,
- timestamp=datetime.now(),
- decision_maker="system",
- metadata={"entities": ["Python", "FastAPI", "web_project"]}
-)
-knowledge.add_decision(decision)
-
-# Or use the convenience method for quick decisions
+```python
decision_id = knowledge.add_decision_simple(
category="technology_choice",
scenario="Framework selection for web API",
@@ -212,145 +144,101 @@ decision_id = knowledge.add_decision_simple(
entities=["Python", "FastAPI", "web_project"]
)
-# Find similar decisions easily
similar = knowledge.find_precedents_by_scenario(
scenario="web framework",
category="technology_choice",
limit=3
)
-print(f"Found {len(similar)} similar decisions")
-```
-
-### Smart Analytics
-```python
-# Understand decision impact
impact = knowledge.analyze_decision_impact(decision_id)
-print(f"This decision influenced {impact.get('total_influenced', 0)} other decisions")
-
-# Get decision summary
-summary = knowledge.get_decision_summary()
-print(f"Total decisions: {summary.get('total_decisions', 0)}")
-print(f"Categories: {list(summary.get('categories', {}).keys())}")
-
-# Trace decision chains
-chains = knowledge.trace_decision_chain(decision_id)
-print(f"Decision chain has {len(chains)} connections")
-
-# Check if decisions follow rules
-compliance = knowledge.check_decision_rules({
- "category": "loan_approval",
- "scenario": "Mortgage application",
- "reasoning": "Good credit score, stable income",
- "outcome": "approved",
- "confidence": 0.95
-})
-
-if compliance.get("compliant", False):
- print("βœ… Decision follows all rules")
-else:
- print(f"❌ Rule violations: {compliance.get('violations', [])}")
```
-### Graph Analytics Made Simple
-```python
-# Get overview of your knowledge graph
-summary = knowledge.get_graph_summary()
-print(f"Knowledge graph has {summary.get('nodes', 0)} concepts")
-print(f"And {summary.get('edges', 0)} relationships")
-
-# Find related concepts
-related = knowledge.find_related_nodes("Python", how_many=5)
-for concept_id, similarity in related:
- print(f"Related to {concept_id}: {similarity:.2f}")
-
-# Understand which concepts are most important
-importance = knowledge.get_node_importance("Python")
-print(f"Python importance score: {importance.get('degree', 0)}")
-```
+### Core ContextGraph Methods
-### Core Methods
+| Method | Description |
+|--------|-------------|
+| `add_node(node_id, node_type, properties)` | Add concepts to remember |
+| `add_edge(source, target, relation)` | Connect related concepts |
+| `add_decision_simple(category, scenario, reasoning, outcome, confidence, ...)` | Record decisions |
+| `find_precedents_by_scenario(scenario, category, ...)` | Find similar past decisions |
+| `analyze_decision_impact(decision_id)` | See how decisions affect others |
+| `trace_decision_chain(decision_id)` | Trace decision connections |
+| `check_decision_rules(decision_data)` | Validate decisions against policy |
+| `find_related_nodes(node_id, how_many)` | Discover connections |
-| Method | What It Does | When to Use |
-|--------|-------------|------------|
-| `add_node(node_id, node_type, properties)` | Add concepts to remember | Build knowledge base |
-| `add_edge(source, target, relation)` | Connect related concepts | Show relationships |
-| `add_decision(decision)` or `add_decision(category, scenario, reasoning, outcome, ...)` | Record decisions | Track choices and learn |
-| `add_decision_simple(category, scenario, reasoning, outcome, confidence, ...)` | Easy decision recording | Quick decision tracking |
-| `find_precedents(decision_id, limit)` | Find precedents by ID | Get connected decisions |
-| `find_precedents_by_scenario(scenario, category, ...)` | Find similar decisions | Make consistent choices |
-| `analyze_decision_impact(decision_id)` | Understand decision influence | See how decisions affect others |
-| `get_decision_summary()` | Get decision statistics | Understand decision patterns |
-| `trace_decision_chain(decision_id)` | Trace decision connections | Understand decision relationships |
-| `check_decision_rules(decision_data)` | Validate decisions | Ensure compliance |
-| `get_graph_summary()` | Get graph overview | Understand knowledge structure |
-| `find_related_nodes(node_id, how_many)` | Find related concepts | Discover connections |
-| `get_node_importance(node_id)` | Measure concept importance | Identify key concepts |
+---
+
+## Data Structures
+
+```python
+@dataclass
+class MemoryItem:
+ content: str
+ timestamp: datetime
+ metadata: Dict
+ embedding: List[float]
+ entities: List[Dict]
+
+@dataclass
+class Decision:
+ decision_id: str
+ category: str
+ scenario: str
+ reasoning: str
+ outcome: str
+ confidence: float # 0–1
+ decision_maker: str
+ timestamp: datetime
+ entities: List[str]
+ metadata: Dict
+```
---
-## πŸ”„ Using Both Together - Complete Intelligence
+## Configuration Options
-### Your Smart Agent System
```python
-from semantica.context import AgentContext, ContextGraph
-from semantica.vector_store import VectorStore
+# Minimal: memory only
+agent = AgentContext(vector_store=vector_store)
-# Create the components
-vector_store = VectorStore(backend="inmemory", dimension=384)
-knowledge = ContextGraph(advanced_analytics=True)
+# Recommended: memory + decision learning
+agent = AgentContext(
+ vector_store=vector_store,
+ decision_tracking=True,
+ graph_expansion=True
+)
-# Create your intelligent agent
+# Full: all features
agent = AgentContext(
vector_store=vector_store,
- knowledge_graph=knowledge, # Add knowledge graph
+ knowledge_graph=ContextGraph(advanced_analytics=True),
decision_tracking=True,
graph_expansion=True,
- advanced_analytics=True
+ advanced_analytics=True,
+ kg_algorithms=True,
+ vector_store_features=True
)
-# Your agent works like this:
-# 1. Store information in memory
-agent.store("User wants to learn web development with Python")
-agent.store("User is a beginner programmer")
-agent.store("User prefers hands-on tutorials")
-
-# 2. Find relevant information
-results = agent.retrieve("Python web development tutorials")
-print(f"Found {len(results)} relevant memories")
-
-# 3. Make smart decisions
-decision_id = agent.record_decision(
- category="content_recommendation",
- scenario="Python web development learning path",
- reasoning="Beginner needs hands-on Python web tutorial",
- outcome="recommended_flask_tutorial",
- confidence=0.89
+# ContextGraph options
+graph = ContextGraph(
+ advanced_analytics=True,
+ centrality_analysis=True,
+ community_detection=True,
+ node_embeddings=True
)
-
-# 4. Learn and improve over time
-insights = agent.get_context_insights()
-print(f"Agent insights: {insights}")
-
-# 5. Access advanced features when needed
-graph_summary = agent.graph_builder.get_graph_summary()
-node_importance = agent.graph_builder.get_node_importance("Python")
```
---
-## 🎯 Real-World Applications
+## Real-World Examples
+
+### Banking β€” Loan Decisions
-### 🏦 Banking - Smart Loan Decisions
```python
-# Track loan decisions and learn from patterns
bank_agent = AgentContext(vector_store=bank_vector_store, decision_tracking=True)
-# Store customer information
bank_agent.store("Customer has credit score 750, stable employment")
-bank_agent.store("Customer is first-time homebuyer")
-# Make loan decision
loan_decision = bank_agent.record_decision(
category="loan_approval",
scenario="First-time homebuyer mortgage",
@@ -359,21 +247,17 @@ loan_decision = bank_agent.record_decision(
confidence=0.94
)
-# Find similar loan decisions for consistency
similar_loans = bank_agent.find_precedents("homebuyer", category="loan_approval")
-print(f"Found {len(similar_loans)} similar loan decisions")
```
-### πŸ₯ Healthcare - Patient Care Decisions
+### Healthcare β€” Treatment Decisions
+
```python
-# Track patient care decisions
health_agent = AgentContext(vector_store=medical_vector_store, decision_tracking=True)
-# Store patient information
health_agent.store("Patient has hypertension, type 2 diabetes")
health_agent.store("Patient allergic to penicillin")
-# Make treatment decision
treatment_decision = health_agent.record_decision(
category="treatment_plan",
scenario="Hypertension with diabetes",
@@ -381,270 +265,29 @@ treatment_decision = health_agent.record_decision(
outcome="prescribed_ace_inhibitor",
confidence=0.91
)
-
-# Find similar treatment cases
-similar_cases = health_agent.find_precedents("hypertension", category="treatment_plan")
-```
-
-### πŸ›’ E-commerce - Smart Recommendations
-```python
-# Track recommendation decisions
-ecommerce_graph = ContextGraph()
-
-# Build user-product knowledge
-ecommerce_graph.add_node("user_123", "user", {"segment": "premium"})
-ecommerce_graph.add_node("laptop_xyz", "product", {"category": "electronics"})
-ecommerce_graph.add_edge("user_123", "laptop_xyz", "viewed")
-
-# Make recommendation decision
-from semantica.context.decision_models import Decision
-from datetime import datetime
-
-rec_decision = Decision(
- decision_id="rec_001",
- category="product_recommendation",
- scenario="Laptop recommendation for premium user",
- reasoning="User prefers high-performance electronics",
- outcome="recommended_gaming_laptop",
- confidence=0.87,
- timestamp=datetime.now(),
- decision_maker="recommendation_system",
- metadata={"entities": ["user_123", "laptop_xyz"]}
-)
-ecommerce_graph.add_decision(rec_decision)
-
-# Or use the convenience method
-rec_decision_id = ecommerce_graph.add_decision_simple(
- category="product_recommendation",
- scenario="Laptop recommendation for premium user",
- reasoning="User prefers high-performance electronics",
- outcome="recommended_gaming_laptop",
- confidence=0.87,
- entities=["user_123", "laptop_xyz"]
-)
-
-# Find similar recommendations
-similar_recs = ecommerce_graph.find_precedents_by_scenario(
- scenario="laptop recommendation",
- limit=5
-)
-```
-
----
-
-## βš™οΈ Configuration Options
-
-### Simple Setup (Most Common)
-```python
-# Just memory and basic learning
-agent = AgentContext(vector_store=vector_store)
-```
-
-### Smart Setup (Recommended)
-```python
-# Memory + decision learning
-agent = AgentContext(
- vector_store=vector_store,
- decision_tracking=True,
- graph_expansion=True
-)
-```
-
-### Complete Setup (Maximum Power)
-```python
-# Everything enabled
-agent = AgentContext(
- vector_store=vector_store,
- knowledge_graph=ContextGraph(advanced_analytics=True),
- decision_tracking=True,
- graph_expansion=True,
- advanced_analytics=True,
- kg_algorithms=True,
- vector_store_features=True
-)
-```
-
-### ContextGraph Options
-```python
-# Basic knowledge graph
-graph = ContextGraph()
-
-# Advanced knowledge graph
-graph = ContextGraph(
- advanced_analytics=True, # Enable smart algorithms
- centrality_analysis=True, # Find important concepts
- community_detection=True, # Find groups of related concepts
- node_embeddings=True # Understand concept similarity
-)
-```
-
----
-
-## πŸ“Š Data Structures
-
-### MemoryItem - The Basic Memory Unit
-```python
-@dataclass
-class MemoryItem:
- content: str # The actual text content
- timestamp: datetime # When it was created
- metadata: Dict # Tags like user_id, conversation_id
- embedding: List[float] # Vector representation
- entities: List[Dict] # Entities found in content
-```
-
-### Decision - The Decision Unit
-```python
-@dataclass
-class Decision:
- decision_id: str # Unique decision identifier
- category: str # Decision category (approval, rejection, etc.)
- scenario: str # Decision scenario description
- reasoning: str # Decision reasoning and explanation
- outcome: str # Decision outcome
- confidence: float # Confidence score (0-1)
- decision_maker: str # Decision maker identifier
- timestamp: datetime # When decision was made
- entities: List[str] # Related entities
- metadata: Dict # Additional decision metadata
-```
-
-### Graph Node - Knowledge Concept
-```python
-{
- "id": "node_unique_id",
- "type": "concept",
- "properties": {
- "content": "Description of the node",
- "weight": 1.0,
- "importance": 0.85
- }
-}
-```
-
-### Graph Edge - Knowledge Relationship
-```python
-{
- "source_id": "origin_node",
- "target_id": "destination_node",
- "type": "related_to",
- "weight": 0.8,
- "properties": {
- "similarity": 0.75,
- "confidence": 0.9
- }
-}
```
---
-## πŸš€ Advanced Features
-
-### GraphRAG with Multi-Hop Reasoning
-```python
-# Query with reasoning and LLM integration
-result = agent.query_with_reasoning(
- query="What technologies work well together?",
- llm_provider=llm_provider,
- max_hops=2,
- max_results=10
-)
-
-print(f"Response: {result['response']}")
-print(f"Reasoning Path: {result['reasoning_path']}")
-print(f"Confidence: {result['confidence']:.3f}")
-```
-
-### Production Integration
-```python
-# Use with persistent graph stores
-from semantica.graph_store import GraphStore
-
-# Neo4j integration
-neo4j_store = GraphStore(
- backend="neo4j",
- uri="bolt://localhost:7687",
- user="neo4j",
- password="password"
-)
-
-# Production agent with persistent storage
-production_agent = AgentContext(
- vector_store=vector_store,
- knowledge_graph=neo4j_store,
- decision_tracking=True,
- advanced_analytics=True
-)
-```
-
-### Analytics and Insights
-```python
-# Get comprehensive insights
-insights = agent.get_context_insights()
-print(f"Total decisions: {insights.get('total_decisions', 0)}")
-print(f"Decision categories: {list(insights.get('categories', {}).keys())}")
-print(f"Most common outcome: {insights.get('most_common_outcome', 'N/A')}")
-
-# Graph analytics
-graph_insights = agent.graph_builder.get_graph_summary()
-node_importance = agent.graph_builder.get_node_importance("key_concept")
-```
-
----
-
-## πŸ“š Need More Help?
-
-### For Beginners
-- Start with **AgentContext** for most applications
-- Use basic **store/retrieve** for memory management
-- Add **decision tracking** to enable learning
-- Enable features gradually as needed
-
-### For Advanced Users
-- Add **ContextGraph** for knowledge organization
-- Use **analytics** to understand patterns
-- Implement **policies** for consistent decisions
-- Use **persistence** for state management
-
-### For Production
-- Enable **all features** for maximum intelligence
-- Use **save/load** for state persistence
-- **Monitor performance** with insights and health checks
-- **Test thoroughly** before deployment
-
-### Examples and Tutorials
-- Look at the **real-world examples** above for your specific use case
-- Check **configuration options** to customize your agent
-- Start simple and add power as needed
-
----
-
-**Happy building intelligent agents!** 🎯
-
----
-
-## πŸ“š See Also
-
-- [Vector Store](vector_store.md) - The long-term storage backend
-- [Graph Store](graph_store.md) - The knowledge graph backend
-- [KG Algorithms](kg.md) - Knowledge graph algorithms and analytics
-- [Reasoning](reasoning.md) - Uses context for logic
-
-## Cookbook
-
-Interactive tutorials to learn context management, GraphRAG, and decision tracking:
-
-- **[Context Module](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb)**: Practical guide to the context module for AI agents
- - **Topics**: Agent memory, context graph, hybrid retrieval, entity linking, decision tracking
- - **Difficulty**: Intermediate
- - **Use Cases**: Building stateful AI agents, persistent memory systems, decision management
-
-- **[Advanced Context Engineering](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb)**: Build a production-grade memory system for AI agents
- - **Topics**: Agent memory, GraphRAG, entity injection, lifecycle management, persistent stores, decision analytics
- - **Difficulty**: Advanced
- - **Use Cases**: Production agent systems, advanced memory management, decision analysis
-
-- **[Decision Tracking with KG Algorithms](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/12_Decision_Tracking_KG.ipynb)**: Advanced decision tracking and analytics
- - **Topics**: Decision lifecycle, precedent search, causal analysis, KG algorithms, policy compliance
- - **Difficulty**: Advanced
- - **Use Cases**: Banking decisions, healthcare decisions, legal precedent analysis
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Vector Store" icon="database" href="vector_store">
+ Long-term vector storage backend.
+ </Card>
+ <Card title="KG Module" icon="diagram-project" href="kg">
+ Knowledge graph algorithms and analytics.
+ </Card>
+ <Card title="Reasoning" icon="microchip" href="reasoning">
+ Logical inference over context.
+ </Card>
+ <Card title="Provenance" icon="link" href="provenance">
+ W3C PROV-O lineage tracking.
+ </Card>
+</CardGroup>
+
+### Cookbook
+
+- [Context Module](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb) β€” practical guide to agent memory and decision tracking Β· Intermediate
+- [Advanced Context Engineering](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb) β€” production-grade memory system with FAISS and Neo4j Β· Advanced
+- [Decision Tracking with KG Algorithms](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/12_Decision_Tracking_KG.ipynb) β€” decision lifecycle, precedent search, policy compliance Β· Advanced
diff --git a/docs/reference/core.md b/docs/reference/core.md
index 067e8699..1de640cd 100644
--- a/docs/reference/core.md
+++ b/docs/reference/core.md
@@ -1,226 +1,72 @@
-# Core
-
-> **Framework infrastructure, lifecycle management, and plugin system.**
-
---
-
-## 🎯 Overview
-
-The **Core Module** provides framework infrastructure, lifecycle management, configuration, and orchestration capabilities. It's the foundation that enables coordination between all Semantica modules.
-
-### What is the Core Module?
-
-The Core module provides:
-
-- **Orchestration**: The `` `Semantica` `` class coordinates multiple modules for complex workflows
-- **Lifecycle Management**: Handles initialization, startup, shutdown, and state transitions
-- **Configuration**: Unified configuration management via YAML and environment variables
-- **Plugin System**: Extensible plugin registry for custom modules and capabilities
-- **Method Registry**: Registry for custom orchestration methods
-
-### When to Use the Core Module
-
-!!! tip "Primary Approach: Individual Modules"
- For most use cases, **use individual modules directly** (e.g., `semantica.ingest`, `semantica.kg`). This gives you full control and transparency.
-
-!!! note "When to Use Orchestration"
- Use the `Semantica` orchestration class when you need:
- - **Complex Workflows**: Multi-step pipelines that span multiple modules
- - **Lifecycle Management**: Application-level initialization and shutdown
- - **Centralized Configuration**: Global settings that affect multiple modules
- - **Plugin Integration**: Custom plugins that need framework coordination
-
-<div class="grid cards" markdown>
-
-- :material-cogs:{ .lg .middle } **Semantica**
-
- ---
-
- Orchestration class for coordinating complex workflows across modules
-
-- :material-lifecycle:{ .lg .middle } **Lifecycle Management**
-
- ---
-
- Manage initialization, startup, shutdown, and state transitions
-
-- :material-tune:{ .lg .middle } **Configuration**
-
- ---
-
- Unified configuration management via YAML and Environment variables
-
-- :material-puzzle:{ .lg .middle } **Plugin System**
-
- ---
-
- Extensible plugin registry for adding custom modules and capabilities
-
-- :material-console:{ .lg .middle } **Method Registry**
-
- ---
-
- Registry for custom orchestration methods and extensibility
-
-</div>
-
+title: "Core Module"
+description: "Framework orchestration, lifecycle management, configuration, and plugin system."
+icon: "gear"
---
-## βš™οΈ Algorithms Used
-
-### Lifecycle Management
-
-**What is Lifecycle Management?**
-
-Lifecycle management handles the initialization, startup, running, and shutdown phases of the Semantica framework. It ensures that all components are properly initialized, resources are managed correctly, and cleanup happens gracefully.
-
-**How it works:**
-- **State Machine**: `UNINITIALIZED` -> `INITIALIZING` -> `READY` -> `RUNNING` -> `STOPPING` -> `STOPPED`
-- **Priority-based Hooks**: Startup and shutdown hooks executed in priority order (lower = earlier)
-- **Graceful Shutdown**: Ensuring all resources (DB connections, thread pools) are closed properly
-
-**Why it matters:**
-- Prevents resource leaks (database connections, file handles)
-- Ensures proper initialization order (dependencies are ready before use)
-- Enables clean application shutdown
-- Supports health monitoring and status tracking
-
-### Configuration
-
-**What is Configuration Management?**
-
-Configuration management provides a unified way to configure all Semantica modules. It supports multiple configuration sources with a clear priority order, ensuring consistent settings across your application.
-
-**How it works:**
-- **Layered Loading**: Defaults -> Config File -> Environment Variables (Priority order)
-- **Schema Validation**: Validating config structure against defined schemas
-- **Nested Access**: Dot notation for accessing nested configuration values
-
-**Why it matters:**
-- Centralized configuration for all modules
-- Environment-specific settings (dev, staging, production)
-- Secure credential management (via environment variables)
-- Validation prevents configuration errors
-
-### Plugin System
-
-**What is the Plugin System?**
-
-The plugin system allows you to extend Semantica with custom modules and capabilities. Plugins can add new functionality, modify existing behavior, or integrate with external systems.
-
-**How it works:**
-- **Discovery**: Auto-discovery of plugins via directory scanning
-- **Registration**: Dynamic registration of classes and functions
-- **Dependency Resolution**: Automatic loading of plugin dependencies
-
-**Why it matters:**
-- Extend Semantica with custom functionality
-- Integrate with external systems and APIs
-- Modify or enhance existing modules
-- Share custom functionality across projects
+> Framework infrastructure for complex workflows β€” lifecycle hooks, centralized config, and a plugin registry.
---
-## Main Classes
-
-### Semantica
+## Overview
+
+The **Core Module** is the coordination layer for Semantica. For most tasks you should use individual modules directly; reach for Core when you need lifecycle management, centralized configuration, or multi-step orchestration.
+
+<Tip>
+**Use individual modules directly** (`semantica.ingest`, `semantica.kg`, etc.) for the vast majority of use cases. Use the `Semantica` orchestration class only when you need application-level lifecycle management or a plugin system.
+</Tip>
+
+<CardGroup cols={2}>
+ <Card title="Semantica" icon="network-wired">
+ Orchestration class for coordinating complex multi-module workflows.
+ </Card>
+ <Card title="ConfigManager" icon="sliders">
+ Unified configuration loading, validation, and merging.
+ </Card>
+ <Card title="LifecycleManager" icon="rotate">
+ Startup/shutdown hooks and system health monitoring.
+ </Card>
+ <Card title="PluginRegistry" icon="puzzle-piece">
+ Dynamic plugin discovery, registration, and loading.
+ </Card>
+</CardGroup>
-The **Semantica** class is an orchestration class that coordinates multiple modules for complex workflows. It's designed for applications that need lifecycle management, centralized configuration, and multi-step pipeline coordination.
-
-!!! important "Not a Convenience Wrapper"
- The `Semantica` class is **not** a convenience wrapper. It's an orchestration tool for complex workflows. For most use cases, use individual modules directly for better control and transparency.
-
-**What it does:**
-- Coordinates multiple modules (ingest, parse, extract, kg, etc.)
-- Manages application lifecycle (initialization, shutdown)
-- Provides centralized configuration
-- Enables plugin integration
-- Handles complex multi-step workflows
-
-**When to use it:**
-- Building applications with multiple components
-- Need lifecycle management (startup/shutdown hooks)
-- Complex workflows spanning multiple modules
-- Want centralized configuration
-- Integrating custom plugins
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `__init__(config=None, **kwargs)` `` | Initialize framework with optional configuration |
-| `` `initialize()` `` | Initialize all framework components and modules |
-| `` `build_knowledge_base(sources, **kwargs)` `` | Orchestrate building a knowledge base from data sources |
-| `` `run_pipeline(pipeline, data)` `` | Execute a processing pipeline |
-| `` `get_status()` `` | Get system health and status |
-| `` `shutdown(graceful=True)` `` | Shutdown the framework gracefully |
+---
-**Example - Orchestration for Complex Workflow:**
+## Semantica (Orchestration)
```python
-from semantica.core import Semantica
-
-# Initialize framework for orchestration
-framework = Semantica()
-framework.initialize()
-
-# Build knowledge base (orchestrates multiple modules)
-result = framework.build_knowledge_base(
- sources=["doc1.pdf", "doc2.docx"],
- embeddings=True,
- graph=True
-)
-
-# Check status
-status = framework.get_status()
-print(f"System state: {status['state']}")
+from semantica.core import Semantica, ConfigManager
-# Shutdown gracefully
-framework.shutdown()
-```
+config_manager = ConfigManager()
+config = config_manager.load_from_file("config.yaml")
-**Alternative - Using Individual Modules (Recommended):**
+framework = Semantica(config=config)
+framework.initialize()
-```python
-from semantica.ingest import FileIngestor
-from semantica.parse import DocumentParser
-from semantica.semantic_extract import NERExtractor, RelationExtractor
-from semantica.kg import GraphBuilder
-from semantica.embeddings import TextEmbedder
-
-# Use modules directly for full control
-ingestor = FileIngestor()
-parser = DocumentParser()
-ner = NERExtractor()
-rel_extractor = RelationExtractor()
-builder = GraphBuilder()
-embedder = TextEmbedder()
-
-# Build your pipeline step by step
-docs = ingestor.ingest_file("doc1.pdf")
-parsed = parser.parse_document("doc1.pdf")
-entities = ner.extract_entities(parsed.get("full_text", ""))
-relationships = rel_extractor.extract_relations(parsed.get("full_text", ""), entities=entities)
-kg = builder.build_graph(entities=entities, relationships=relationships)
-embeddings = embedder.embed_batch([e.text for e in entities])
+try:
+ result = framework.build_knowledge_base(
+ sources=["doc1.pdf", "doc2.docx"],
+ embeddings=True,
+ graph=True,
+ )
+ status = framework.get_status()
+ print(f"State: {status['state']}")
+finally:
+ framework.shutdown(graceful=True)
```
-### ConfigManager
-
-Manages global configuration loading, validation, and merging.
-
-**Methods:**
-
| Method | Description |
|--------|-------------|
-| `` `load_from_file(file_path, validate=True)` `` | Load config from YAML or JSON file |
-| `` `load_from_dict(config_dict, validate=True)` `` | Load config from dictionary |
-| `` `merge_configs(*configs, validate=True)` `` | Merge multiple configurations |
-| `get_config()` | Get current configuration |
-| `set_config(config, validate=True)` | Set current configuration |
-| `reload(file_path=None)` | Reload configuration from file |
+| `initialize()` | Initialize all framework components |
+| `build_knowledge_base(sources, **kwargs)` | Orchestrate KG construction |
+| `run_pipeline(pipeline, data)` | Execute a processing pipeline |
+| `get_status()` | System health and state |
+| `shutdown(graceful=True)` | Graceful shutdown |
+
+---
-**Example:**
+## ConfigManager
```python
from semantica.core import ConfigManager
@@ -228,265 +74,26 @@ from semantica.core import ConfigManager
manager = ConfigManager()
config = manager.load_from_file("config.yaml")
-# Merge configurations
-config1 = manager.load_from_file("base_config.yaml")
-config2 = manager.load_from_file("override_config.yaml")
-merged = manager.merge_configs(config1, config2)
-```
-
-### Config
-
-Configuration data class with validation and nested access.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `get(key_path, default=None)` | Get nested configuration value by key path |
-| `set(key_path, value)` | Set nested configuration value |
-| `update(updates, merge=True)` | Update configuration with new values |
-| `validate()` | Validate configuration settings |
-| `to_dict()` | Convert configuration to dictionary |
-
-**Example:**
-
-```python
-from semantica.core import Config, ConfigManager
-
-manager = ConfigManager()
-config = manager.load_from_dict({"processing": {"batch_size": 32}})
+# Merge base + override configs
+merged = manager.merge_configs(
+ manager.load_from_file("base.yaml"),
+ manager.load_from_file("prod.yaml"),
+)
-# Access nested values
+# Nested access
batch_size = config.get("processing.batch_size", default=16)
-
-# Update values
config.set("processing.batch_size", 64)
-config.update({"quality": {"min_confidence": 0.9}})
-
-# Validate
config.validate()
```
-### LifecycleManager
-
-System lifecycle management with hooks and health monitoring.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `startup()` | Execute startup sequence with registered hooks |
-| `shutdown(graceful=True)` | Execute shutdown sequence |
-| `register_startup_hook(hook_fn, priority=50)` | Register a startup hook |
-| `register_shutdown_hook(hook_fn, priority=50)` | Register a shutdown hook |
-| `register_component(name, component)` | Register component for health monitoring |
-| `health_check()` | Perform comprehensive system health check |
-| `get_health_summary()` | Get summary of system health |
-| `get_state()` | Get current system state |
-| `is_ready()` | Check if system is ready |
-| `is_running()` | Check if system is running |
-
-**Example:**
-
-```python
-from semantica.core import LifecycleManager
-
-manager = LifecycleManager()
-
-# Register hooks
-def init_db():
- print("Initializing database...")
-
-manager.register_startup_hook(init_db, priority=10)
-manager.startup()
-
-# Register component for health monitoring
-class DatabaseComponent:
- def health_check(self):
- return {"healthy": True, "message": "Connected"}
-
-db = DatabaseComponent()
-manager.register_component("database", db)
-
-# Check health
-health = manager.health_check()
-summary = manager.get_health_summary()
-
-manager.shutdown(graceful=True)
-```
-
-### PluginRegistry
-
-Plugin registry and management system for dynamic plugin discovery and loading.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `__init__(plugin_paths=None)` | Initialize with optional plugin paths for auto-discovery |
-| `register_plugin(plugin_name, plugin_class, version="1.0.0", **metadata)` | Manually register a plugin |
-| `load_plugin(plugin_name, **config)` | Load and initialize a plugin |
-| `unload_plugin(plugin_name)` | Unload a plugin |
-| `list_plugins()` | List all available plugins |
-| `get_plugin_info(plugin_name)` | Get information about a plugin |
-| `is_plugin_loaded(plugin_name)` | Check if a plugin is loaded |
-| `get_loaded_plugin(plugin_name)` | Get loaded plugin instance |
-
-**Example:**
-
-```python
-from semantica.core import PluginRegistry
-
-# Auto-discover plugins
-registry = PluginRegistry(plugin_paths=["./plugins"])
-
-# Load plugin with configuration
-plugin = registry.load_plugin("my_plugin", api_key="xxx")
-
-# List all plugins
-plugins = registry.list_plugins()
-for plugin_info in plugins:
- print(f"{plugin_info['name']}: {plugin_info['version']}")
-
-# Get plugin info
-info = registry.get_plugin_info("my_plugin")
-```
-
-### MethodRegistry
-
-Registry for custom orchestration methods.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `register(task, name, method_func)` | Register a custom orchestration method |
-| `get(task, name)` | Get method by task and name |
-| `list_all(task=None)` | List all registered methods |
-| `unregister(task, name)` | Unregister a method |
-| `clear(task=None)` | Clear all registered methods |
-
-**Example:**
-
-```python
-from semantica.core import method_registry
-
-def custom_kb_builder(sources, **kwargs):
- # Custom logic
- return {"knowledge_graph": {}}
-
-method_registry.register("knowledge_base", "custom", custom_kb_builder)
-
-# Use custom method
-method = method_registry.get("knowledge_base", "custom")
-result = method(sources=["doc.pdf"])
-```
-
----
-
-## Orchestration Methods
-
-Convenience functions for common orchestration tasks.
-
-### build_knowledge_base()
-
-Build knowledge base from data sources.
-
-```python
-from semantica.core.methods import build_knowledge_base
-
-result = build_knowledge_base(
- sources=["doc1.pdf", "doc2.docx"],
- method="default",
- embeddings=True,
- graph=True
-)
-```
-
-### run_pipeline()
-
-Execute a processing pipeline.
-
-```python
-from semantica.core.methods import run_pipeline
-
-result = run_pipeline(
- pipeline={"steps": ["parse", "extract"]},
- data="sample text",
- method="default"
-)
-```
-
-### initialize_framework()
-
-Initialize Semantica framework.
-
-```python
-from semantica.core.methods import initialize_framework
-
-framework = initialize_framework(
- config={"llm_provider": {"name": "openai"}},
- method="default"
-)
-```
-
-### get_status()
-
-Get system status.
-
-```python
-from semantica.core.methods import get_status
-
-status = get_status(framework=my_framework, method="detailed")
-```
-
-### get_orchestration_method()
-
-Get orchestration method by task and name.
-
-```python
-from semantica.core.methods import get_orchestration_method
-
-method = get_orchestration_method("knowledge_base", "custom")
-```
-
-### list_available_methods()
-
-List all available orchestration methods.
-
-```python
-from semantica.core.methods import list_available_methods
-
-all_methods = list_available_methods()
-kb_methods = list_available_methods("knowledge_base")
-```
-
----
-
-## Configuration
-
-### Environment Variables
-
-Configuration can be loaded from environment variables with `SEMANTICA_` prefix:
-
-```bash
-export SEMANTICA_PROCESSING_BATCH_SIZE=64
-export SEMANTICA_LLM_PROVIDER_MODEL=gpt-4
-export SEMANTICA_QUALITY_MIN_CONFIDENCE=0.8
-```
-
### YAML Configuration
```yaml
llm_provider:
name: openai
- model: gpt-4
+ model: gpt-4o
api_key: ${OPENAI_API_KEY}
-embedding_model:
- name: openai
- model: text-embedding-ada-002
-
processing:
batch_size: 32
max_workers: 4
@@ -496,62 +103,52 @@ quality:
logging:
level: INFO
-
-plugins:
- my_plugin:
- enabled: true
- config_key: config_value
```
-### JSON Configuration
-
-```json
-{
- "llm_provider": {
- "name": "openai",
- "model": "gpt-4"
- },
- "processing": {
- "batch_size": 32
- }
-}
+```bash
+# Environment variable overrides (SEMANTICA_ prefix)
+export SEMANTICA_PROCESSING_BATCH_SIZE=64
+export SEMANTICA_LOG_LEVEL=DEBUG
```
---
-## Integration Examples
+## LifecycleManager
-### Basic Usage
+State machine: `UNINITIALIZED` β†’ `INITIALIZING` β†’ `READY` β†’ `RUNNING` β†’ `STOPPING` β†’ `STOPPED`
```python
-from semantica.core import Semantica, ConfigManager
+from semantica.core import LifecycleManager
-# 1. Load configuration
-config_manager = ConfigManager()
-config = config_manager.load_from_file("config.yaml")
+manager = LifecycleManager()
-# 2. Initialize framework
-framework = Semantica(config=config)
-framework.initialize()
+def init_db():
+ print("Initializing database...")
-try:
- # 3. Build knowledge base
- result = framework.build_knowledge_base(
- sources=["doc1.pdf", "doc2.docx"],
- embeddings=True,
- graph=True
- )
-
- # 4. Check status
- status = framework.get_status()
- print(f"System state: {status['state']}")
-
-finally:
- # 5. Shutdown gracefully
- framework.shutdown(graceful=True)
+def cleanup_db():
+ print("Closing database connections...")
+
+manager.register_startup_hook(init_db, priority=10)
+manager.register_shutdown_hook(cleanup_db, priority=10)
+
+manager.startup()
+
+# Health monitoring
+class DatabaseComponent:
+ def health_check(self):
+ return {"healthy": True, "message": "Connected"}
+
+manager.register_component("database", DatabaseComponent())
+summary = manager.get_health_summary()
+
+manager.shutdown(graceful=True)
```
-### Custom Plugin
+Lower `priority` values execute first during startup; higher values execute first during shutdown.
+
+---
+
+## PluginRegistry
```python
from semantica.core import PluginRegistry
@@ -559,108 +156,54 @@ from semantica.core import PluginRegistry
class MyPlugin:
def initialize(self):
print("Plugin initialized")
-
+
def execute(self, data):
return {"processed": True}
-registry = PluginRegistry()
-registry.register_plugin(
- plugin_name="my_plugin",
- plugin_class=MyPlugin,
- version="1.0.0"
-)
+registry = PluginRegistry(plugin_paths=["./plugins"])
+registry.register_plugin("my_plugin", MyPlugin, version="1.0.0")
-plugin = registry.load_plugin("my_plugin")
+plugin = registry.load_plugin("my_plugin", api_key="xxx")
result = plugin.execute("sample data")
-```
-
-### Lifecycle Hooks
-```python
-from semantica.core import LifecycleManager
-
-manager = LifecycleManager()
-
-def init_database():
- print("Initializing database...")
-
-def cleanup_database():
- print("Cleaning up database...")
+for info in registry.list_plugins():
+ print(f"{info['name']}: {info['version']}")
+```
-manager.register_startup_hook(init_database, priority=10)
-manager.register_shutdown_hook(cleanup_database, priority=10)
+---
-manager.startup()
-# ... do work ...
-manager.shutdown(graceful=True)
-```
+## MethodRegistry
-### Custom Orchestration Method
+Register custom orchestration methods for extensibility.
```python
-from semantica.core import method_registry, Semantica
+from semantica.core import method_registry
def fast_kb_builder(sources, **kwargs):
- framework = Semantica()
- framework.initialize()
- try:
- return framework.build_knowledge_base(
- sources=sources,
- embeddings=False, # Skip for speed
- graph=True,
- **kwargs
- )
- finally:
- framework.shutdown()
+ # custom logic β€” skip embeddings for speed
+ ...
method_registry.register("knowledge_base", "fast", fast_kb_builder)
-# Use custom method
from semantica.core.methods import build_knowledge_base
result = build_knowledge_base(sources=["doc.pdf"], method="fast")
```
---
-## Best Practices
-
-1. **Always Initialize**: Always call `initialize()` after creating a `Semantica` instance before using it.
-
-2. **Graceful Shutdown**: Always call `shutdown(graceful=True)` in a `finally` block to ensure proper cleanup.
-
-3. **Configuration Management**: Use `ConfigManager` for loading and managing configurations. Prefer YAML files for complex configurations.
-
-4. **Error Handling**: Wrap framework operations in try-except blocks to handle `ConfigurationError` and `ProcessingError` appropriately.
-
-5. **Health Monitoring**: Register components with `LifecycleManager` for health monitoring and use `health_check()` regularly.
-
-6. **Plugin Development**: Follow the plugin interface (must have `initialize()` and `execute()` methods) when creating custom plugins.
-
-7. **Method Registration**: Use `MethodRegistry` for extensibility. Register custom methods for knowledge base building, pipeline execution, etc.
-
-8. **Hook Priorities**: Use appropriate priorities for lifecycle hooks. Lower numbers execute first.
-
-9. **Configuration Validation**: Always validate configurations using `config.validate()` before using them.
-
-10. **Resource Cleanup**: Ensure all resources are properly cleaned up in shutdown hooks.
-
----
-
## See Also
-- [Pipeline Module](pipeline.md) - Pipeline execution and orchestration
-- [Utils Module](utils.md) - Shared utilities used by Core
-- [Getting Started Guide](../getting-started.md) - Learn the basics
-
-## Cookbook
-
-Interactive tutorials to learn orchestration and lifecycle management:
-
-- **[Welcome to Semantica](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)**: Comprehensive introduction to all Semantica modules and architecture
- - **Topics**: Framework overview, all modules, architecture, configuration, lifecycle
- - **Difficulty**: Beginner
- - **Use Cases**: Understanding the framework structure, first-time users
-- **[Pipeline Orchestration](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/07_Pipeline_Orchestration.ipynb)**: Build robust, automated data processing pipelines
- - **Topics**: Workflows, automation, error handling, pipeline orchestration
- - **Difficulty**: Advanced
- - **Use Cases**: Complex multi-step workflows, production pipelines
+<CardGroup cols={2}>
+ <Card title="Pipeline" icon="arrows-turn-to-dots" href="pipeline">
+ Pipeline execution and orchestration.
+ </Card>
+ <Card title="Utils" icon="wrench" href="utils">
+ Shared utilities used by Core internally.
+ </Card>
+ <Card title="Getting Started" icon="play" href="../getting-started">
+ Learn the basics before using Core.
+ </Card>
+ <Card title="LLMs" icon="microchip" href="llms">
+ Configure LLM providers via ConfigManager.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/deduplication.md b/docs/reference/deduplication.md
index dd01e1e0..05923a41 100644
--- a/docs/reference/deduplication.md
+++ b/docs/reference/deduplication.md
@@ -1,774 +1,123 @@
-# Deduplication
-
-> **Advanced entity deduplication and resolution system for maintaining a clean, single-source-of-truth Knowledge Graph.**
-
----
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-content-duplicate:{ .lg .middle } **Duplicate Detection**
-
- ---
-
- Identify duplicates using multi-factor similarity metrics
-
-- :material-set-merge:{ .lg .middle } **Entity Merging**
-
- ---
-
- Merge entities with configurable strategies (Keep First, Most Complete, etc.)
-
-- :material-group:{ .lg .middle } **Clustering**
-
- ---
-
- Cluster similar entities for efficient batch processing
-
-- :material-calculator:{ .lg .middle } **Similarity Metrics**
-
- ---
-
- Levenshtein, Jaro-Winkler, Cosine, and Jaccard similarity support
-
-- :material-history:{ .lg .middle } **Provenance**
-
- ---
-
- Preserve data lineage and history during merges
-
-- :material-scale:{ .lg .middle } **Scalable**
-
- ---
-
- Batch processing and blocking for large datasets
-
-</div>
-
-!!! tip "When to Use"
- - **Data Ingestion**: Clean incoming data before adding to the graph
- - **Graph Maintenance**: Periodically clean up existing knowledge graphs
- - **Entity Resolution**: Resolve entities from different sources (e.g., "Apple" vs "Apple Inc.")
-
---
-
-## βš™οΈ Algorithms Used
-
-### Similarity Calculation
-
-The deduplication system uses multiple similarity metrics:
-
-- **Levenshtein Distance**: Edit distance for string difference
-- **Jaro-Winkler**: String similarity with prefix weighting (Default for strings, optimized for entity names)
-- **Cosine Similarity**: Vector similarity for embeddings
-- **Jaccard Similarity**: Set overlap for properties/relationships
-- **Property Matching**: Handles disjoint properties with neutral scoring (`` `0.5` ``) to prevent false negatives
-- **Multi-factor Aggregation**: Weighted sum of multiple metrics
-
-### Default Configuration
-
-The deduplication module uses the following default weights to prioritize name matching while considering other factors:
-
-- **String Similarity**: `` `0.6` `` (Primary factor, using Jaro-Winkler)
-- **Property Similarity**: `` `0.2` `` (Handles missing values neutrally)
-- **Relationship Similarity**: `` `0.2` ``
-- **Embedding Similarity**: `` `0.0` `` (Optional, enabled if embeddings are present)
-
-### Duplicate Detection
-
-The system uses efficient detection algorithms:
-
-- **Pairwise Comparison**: `` `O(nΒ²)` `` comparison (for small sets)
-- **Blocking/Indexing**: Reduce search space for large sets
-- **Union-Find**: Disjoint set data structure for grouping duplicates
-- **Confidence Scoring**: `` `0.0 - 1.0` `` probability score for duplicates
-
-### Clustering
-
-The module provides clustering algorithms for grouping similar entities:
-- **Hierarchical Clustering**: Agglomerative bottom-up clustering
-- **Connected Components**: Graph-based cluster detection
-- **Cluster Quality**: Cohesion and separation metrics
-
-### Entity Merging
-- **Strategy Pattern**: Pluggable merge logic
-- **Property Union**: Combining unique properties
-- **Relationship Merging**: Re-linking relationships to the merged entity
-
+title: "Deduplication Module"
+description: "Entity deduplication v1/v2, similarity scoring, and merging β€” up to 7x faster with v2 strategies."
+icon: "copy"
---
-## Main Classes
-
-### DuplicateDetector
-
-Identifies potential duplicates in a dataset using similarity metrics and confidence scoring.
-
-**Initialization:**
-
-```python
-DuplicateDetector(
- similarity_threshold: float = 0.7,
- confidence_threshold: float = 0.6,
- use_clustering: bool = True,
- config: Optional[Dict[str, Any]] = None,
- **kwargs
-)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `detect_duplicates(entities, threshold=None, **options)` | Find duplicate pairs | `List[DuplicateCandidate]` |
-| `detect_duplicate_groups(entities, threshold=None, **options)` | Find clusters of duplicates | `List[DuplicateGroup]` |
-| `incremental_detect(new_entities, existing_entities, threshold=None, **options)` | Detect duplicates between new and existing entities | `List[DuplicateCandidate]` |
-| `detect_relationship_duplicates(relationships, **options)` | Detect duplicate relationships | `List[Tuple[Dict, Dict]]` |
-
-**Example:**
-
-```python
-from semantica.deduplication import DuplicateDetector
-
-detector = DuplicateDetector(similarity_threshold=0.85, confidence_threshold=0.7)
-candidates = detector.detect_duplicates(entities)
-groups = detector.detect_duplicate_groups(entities)
-
-for candidate in candidates:
- print(f"Duplicate: {candidate.entity1['name']} <-> {candidate.entity2['name']}")
- print(f" Similarity: {candidate.similarity_score:.2f}, Confidence: {candidate.confidence:.2f}")
-```
-
-### EntityMerger
-
-Merges duplicate entities into a single canonical entity using configurable strategies.
-
-**Initialization:**
-
-```python
-EntityMerger(
- preserve_provenance: bool = True,
- config: Optional[Dict[str, Any]] = None,
- **kwargs
-)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `merge_duplicates(entities, strategy=None, **options)` | Execute merge on duplicate entities | `List[MergeOperation]` |
-| `merge_entity_group(entities, strategy=None, **options)` | Merge a specific group of entities | `MergeOperation` |
-| `incremental_merge(new_entities, existing_entities, **options)` | Incrementally merge new entities with existing ones | `List[MergeOperation]` |
-| `get_merge_history()` | Get merge operation history | `List[MergeOperation]` |
-| `validate_merge_quality(merge_operation)` | Validate quality of a merge operation | `Dict[str, Any]` |
-
-**Strategies:**
-- `"keep_first"`: Keep the first entity encountered
-- `"keep_last"`: Keep the last entity encountered
-- `"keep_most_complete"`: Keep entity with most properties/relationships
-- `"keep_highest_confidence"`: Keep entity with highest confidence score
-- `"merge_all"`: Create new entity combining all info
-
-**Example:**
-
-```python
-from semantica.deduplication import EntityMerger
-
-merger = EntityMerger(preserve_provenance=True)
-
-# Merge with specific strategy
-operations = merger.merge_duplicates(
- entities,
- strategy="keep_most_complete"
-)
-
-# Get merge history
-history = merger.get_merge_history()
-```
-
-### SimilarityCalculator
-
-Calculates multi-factor similarity between entities using string, property, relationship, and embedding similarity.
-
-**Initialization:**
-
-```python
-SimilarityCalculator(
- embedding_weight: float = 0.4,
- string_weight: float = 0.3,
- property_weight: float = 0.2,
- relationship_weight: float = 0.1,
- similarity_threshold: float = 0.7,
- config: Optional[Dict[str, Any]] = None,
- **kwargs
-)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `calculate_similarity(entity1, entity2, **options)` | Calculate overall similarity | `SimilarityResult` |
-| `calculate_string_similarity(str1, str2, method="levenshtein")` | Calculate string similarity | `float` |
-| `calculate_property_similarity(entity1, entity2)` | Calculate property similarity | `float` |
-| `calculate_relationship_similarity(entity1, entity2)` | Calculate relationship similarity | `float` |
-| `calculate_embedding_similarity(embedding1, embedding2)` | Calculate embedding similarity | `float` |
-| `batch_calculate_similarity(entities, threshold=None)` | Calculate similarity for all pairs | `List[Tuple[Dict, Dict, float]]` |
-
-**Example:**
-
-```python
-from semantica.deduplication import SimilarityCalculator
-
-calculator = SimilarityCalculator(
- string_weight=0.4,
- property_weight=0.3,
- embedding_weight=0.3
-)
-
-result = calculator.calculate_similarity(entity1, entity2)
-print(f"Similarity: {result.score:.2f}")
-print(f"Components: {result.components}")
-```
-
-### ClusterBuilder
-
-Builds clusters of similar entities for efficient batch deduplication.
-
-**Initialization:**
-
-```python
-ClusterBuilder(
- similarity_threshold: float = 0.7,
- min_cluster_size: int = 2,
- max_cluster_size: int = 100,
- use_hierarchical: bool = False,
- config: Optional[Dict[str, Any]] = None,
- **kwargs
-)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `build_clusters(entities, **options)` | Build clusters of similar entities | `ClusterResult` |
-| `update_clusters(existing_clusters, new_entities, **options)` | Incrementally update clusters with new entities | `ClusterResult` |
-
-**Example:**
-
-```python
-from semantica.deduplication import ClusterBuilder
-
-builder = ClusterBuilder(
- similarity_threshold=0.8,
- min_cluster_size=2,
- max_cluster_size=50
-)
-
-result = builder.build_clusters(entities)
-print(f"Found {len(result.clusters)} clusters")
-print(f"Unclustered: {len(result.unclustered)} entities")
-print(f"Quality metrics: {result.quality_metrics}")
-```
-
-### MergeStrategyManager
-
-Manages merge strategies and property-specific merge rules with conflict resolution.
-
-**Initialization:**
-
-```python
-MergeStrategyManager(
- default_strategy: str = "keep_most_complete",
- config: Optional[Dict[str, Any]] = None,
- **kwargs
-)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `merge_entities(entities, strategy=None, **options)` | Merge entities using specified strategy | `MergeResult` |
-| `add_property_rule(property_name, strategy, conflict_resolution=None, priority=0)` | Add property-specific merge rule | `None` |
-| `validate_merge(merge_result)` | Validate merge result quality | `Dict[str, Any]` |
-
-**Example:**
-
-```python
-from semantica.deduplication import MergeStrategyManager, MergeStrategy
-
-manager = MergeStrategyManager(default_strategy="keep_most_complete")
-manager.add_property_rule("name", MergeStrategy.KEEP_FIRST)
-manager.add_property_rule("description", MergeStrategy.MERGE_ALL)
-
-result = manager.merge_entities(entities)
-print(f"Merged entity: {result.merged_entity}")
-print(f"Conflicts: {len(result.conflicts)}")
-```
-
-### MethodRegistry
-
-Registry for custom deduplication methods, enabling extensibility.
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `register(task, name, method_func)` | Register a custom deduplication method | `None` |
-| `get(task, name)` | Get method by task and name | `Optional[Callable]` |
-| `list_all(task=None)` | List all registered methods | `Dict[str, List[str]]` |
-| `unregister(task, name)` | Unregister a method | `None` |
-| `clear(task=None)` | Clear all registered methods | `None` |
-
-**Example:**
-
-```python
-from semantica.deduplication.registry import method_registry
-
-# Register custom similarity method
-def custom_similarity(entity1, entity2, **kwargs):
- # Custom logic
- return SimilarityResult(score=0.85, method="custom")
-
-method_registry.register("similarity", "custom_method", custom_similarity)
-
-# Use custom method
-method = method_registry.get("similarity", "custom_method")
-result = method(entity1, entity2)
-```
-
-### DeduplicationConfig
-
-Configuration manager for deduplication operations, supporting environment variables, config files, and programmatic configuration.
-
-**Initialization:**
-
-```python
-DeduplicationConfig(config_file: Optional[str] = None)
-```
-
-**Methods:**
-
-| Method | Description | Returns |
-|--------|-------------|---------|
-| `set(key, value)` | Set configuration value programmatically | `None` |
-| `get(key, default=None)` | Get configuration value | `Any` |
-| `set_method_config(method, **config)` | Set method-specific configuration | `None` |
-| `get_method_config(method)` | Get method-specific configuration | `Dict` |
-| `get_all()` | Get all configuration | `Dict[str, Any]` |
-
-**Example:**
-
-```python
-from semantica.deduplication.config import dedup_config
-
-# Get configuration
-threshold = dedup_config.get("similarity_threshold", default=0.7)
-
-# Set configuration
-dedup_config.set("similarity_threshold", 0.8)
-
-# Method-specific configuration
-dedup_config.set_method_config("levenshtein", case_sensitive=False)
-levenshtein_config = dedup_config.get_method_config("levenshtein")
-```
+> Advanced entity deduplication and resolution for a clean, single-source-of-truth knowledge graph.
---
-## Data Classes
-
-### DuplicateCandidate
+## Overview
-Represents a duplicate candidate pair with confidence scores.
+The **Deduplication Module** identifies and merges duplicate entities across sources using similarity scoring and blocking strategies.
-**Fields:**
-- `entity1`: First entity dictionary
-- `entity2`: Second entity dictionary
-- `similarity_score`: Similarity score (0.0 to 1.0)
-- `confidence`: Confidence score (0.0 to 1.0)
-- `reasons`: List of reasons why they're considered duplicates
-- `metadata`: Additional metadata dictionary
-
-### DuplicateGroup
-
-Represents a group of duplicate entities.
-
-**Fields:**
-- `entities`: List of duplicate entity dictionaries
-- `similarity_scores`: Dict mapping entity pairs to similarity scores
-- `representative`: Representative entity (most complete)
-- `confidence`: Group confidence score (0.0 to 1.0)
-- `metadata`: Additional group metadata
-
-### MergeOperation
-
-Represents an entity merge operation.
-
-**Fields:**
-- `source_entities`: List of original entities that were merged
-- `merged_entity`: Resulting merged entity dictionary
-- `merge_result`: Detailed merge result with conflicts
-- `timestamp`: Optional timestamp of merge operation
-- `metadata`: Additional operation metadata
-
-### SimilarityResult
-
-Represents a similarity calculation result.
-
-**Fields:**
-- `score`: Overall similarity score (0.0 to 1.0)
-- `method`: Calculation method used
-- `components`: Dict of individual component scores
-- `metadata`: Additional metadata dictionary
-
-### Cluster
-
-Represents an entity cluster.
-
-**Fields:**
-- `cluster_id`: Unique cluster identifier
-- `entities`: List of entities in the cluster
-- `centroid`: Optional representative entity (centroid)
-- `quality_score`: Cluster quality score (0.0 to 1.0)
-- `metadata`: Additional cluster metadata
-
-### ClusterResult
-
-Represents the result of cluster building.
-
-**Fields:**
-- `clusters`: List of Cluster objects
-- `unclustered`: List of entities not in any cluster
-- `quality_metrics`: Cluster quality metrics dictionary
-- `metadata`: Additional result metadata
-
-### MergeResult
-
-Represents the result of a merge operation.
-
-**Fields:**
-- `merged_entity`: Resulting merged entity dictionary
-- `merged_entities`: List of original entities that were merged
-- `conflicts`: List of unresolved conflicts
-- `metadata`: Additional merge metadata
-
-### PropertyMergeRule
-
-Represents a rule for merging specific properties.
-
-**Fields:**
-- `property_name`: Property name
-- `strategy`: Merge strategy to use
-- `conflict_resolution`: Optional custom conflict resolution function
-- `priority`: Rule priority (higher priority rules take precedence)
-
-### MergeStrategy
-
-Enumeration of available merge strategies.
-
-**Values:**
-- `KEEP_FIRST`: Keep the first entity encountered
-- `KEEP_LAST`: Keep the last entity encountered
-- `KEEP_MOST_COMPLETE`: Keep entity with most properties/relationships
-- `KEEP_HIGHEST_CONFIDENCE`: Keep entity with highest confidence score
-- `MERGE_ALL`: Create new entity combining all info
-- `CUSTOM`: Use custom merge logic
+**v2 strategies** (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to **7x faster** than v1 and support fine-grained result control via `max_results`, `top_k_per_entity`, `min_similarity`, and `sort_by`.
---
-## Convenience Functions
-
-### detect_duplicates
-
-Convenience function for duplicate detection with multiple methods.
-
-```python
-from semantica.deduplication.methods import detect_duplicates
-
-# Pairwise detection
-candidates = detect_duplicates(
- entities,
- method="pairwise",
- similarity_threshold=0.8,
- confidence_threshold=0.7
-)
-
-# Group detection
-groups = detect_duplicates(
- entities,
- method="group",
- similarity_threshold=0.8
-)
-
-# Incremental detection
-new_candidates = detect_duplicates(
- new_entities,
- method="incremental",
- existing_entities=existing_entities,
- similarity_threshold=0.8
-)
-```
-
-**Methods:**
-- `"pairwise"`: O(nΒ²) comparison of all entity pairs
-- `"batch"`: Efficient batch similarity calculation
-- `"incremental"`: O(nΓ—m) comparison for new vs existing entities
-- `"group"`: Union-find algorithm for duplicate group formation
-
-### merge_entities
-
-Convenience function for entity merging with multiple strategies.
+## EntityResolver
```python
-from semantica.deduplication.methods import merge_entities
+from semantica.deduplication import EntityResolver
-operations = merge_entities(
- duplicate_entities,
- method="keep_most_complete",
- preserve_provenance=True
-)
+resolver = EntityResolver()
+merged_entities = resolver.resolve(entities, strategy="semantic_v2")
```
-**Methods:**
-- `"keep_first"`: Preserve first entity, merge others
-- `"keep_last"`: Preserve last entity, merge others
-- `"keep_most_complete"`: Preserve entity with most properties/relationships
-- `"keep_highest_confidence"`: Preserve entity with highest confidence
-- `"merge_all"`: Combine all properties and relationships
-
-### calculate_similarity
-
-Convenience function for similarity calculation with multiple methods.
-
-```python
-from semantica.deduplication.methods import calculate_similarity
+Strategies:
-# Different similarity methods
-exact_result = calculate_similarity(entity1, entity2, method="exact")
-lev_result = calculate_similarity(entity1, entity2, method="levenshtein")
-jaro_result = calculate_similarity(entity1, entity2, method="jaro_winkler")
-multi_result = calculate_similarity(entity1, entity2, method="multi_factor")
-```
+| Strategy | Method | Speed | Accuracy |
+|----------|--------|-------|----------|
+| `jaro_winkler` | String similarity (v1) | Fast | Medium |
+| `blocking_v2` | Blocking + Jaro-Winkler (v2) | Very fast | Medium |
+| `hybrid_v2` | Blocking + semantic + string (v2) | Fast | High |
+| `semantic_v2` | Embedding similarity (v2) | Medium | Highest |
-**Methods:**
-- `"exact"`: Exact string matching
-- `"levenshtein"`: Levenshtein distance-based similarity
-- `"jaro_winkler"`: Jaro-Winkler similarity with prefix bonus
-- `"cosine"`: Cosine similarity for embeddings
-- `"property"`: Property value comparison
-- `"relationship"`: Jaccard similarity of relationships
-- `"embedding"`: Cosine similarity of vector embeddings
-- `"multi_factor"`: Weighted aggregation of all components
+---
-### build_clusters
+## DuplicateDetector
-Convenience function for cluster building with multiple methods.
+Fine-grained control over duplicate detection results.
```python
-from semantica.deduplication.methods import build_clusters
+from semantica.deduplication import DuplicateDetector
-# Graph-based clustering
-result = build_clusters(
+detector = DuplicateDetector()
+duplicates = detector.find_duplicates(
entities,
- method="graph_based",
- similarity_threshold=0.8
+ strategy="semantic_v2",
+ min_similarity=0.85, # minimum score to consider a duplicate
+ top_k_per_entity=3, # max candidates per entity
+ max_results=100, # total result cap
+ sort_by="similarity" # "similarity" | "entity_id" | "cluster_size"
)
-# Hierarchical clustering
-result = build_clusters(
- entities,
- method="hierarchical",
- similarity_threshold=0.8
-)
+for dup in duplicates:
+ print(f"{dup['entity_a']} β‰ˆ {dup['entity_b']} ({dup['similarity']:.2f})")
```
-**Methods:**
-- `"graph_based"`: Union-find algorithm for connected components
-- `"hierarchical"`: Agglomerative clustering for large datasets
-
-### get_deduplication_method
-
-Get deduplication method by task and name.
-
-```python
-from semantica.deduplication.methods import get_deduplication_method
-
-method = get_deduplication_method("similarity", "levenshtein")
-if method:
- result = method(entity1, entity2)
-```
-
-### list_available_methods
-
-List all available deduplication methods.
-
-```python
-from semantica.deduplication.methods import list_available_methods
-
-# List all methods
-all_methods = list_available_methods()
-
-# List methods for specific task
-similarity_methods = list_available_methods("similarity")
-```
+<Note>
+ **v0.5.0 fix:** `ConflictDetector` no longer produces duplicate definition errors when the same entity appears in multiple sources with identical definitions.
+</Note>
---
-## Configuration
-
-The deduplication module supports multiple configuration sources: environment variables, config files (YAML, JSON, TOML), and programmatic configuration.
-
-### Environment Variables
-
-```bash
-export DEDUP_SIMILARITY_THRESHOLD=0.8
-export DEDUP_CONFIDENCE_THRESHOLD=0.7
-export DEDUP_USE_CLUSTERING=true
-export DEDUP_PRESERVE_PROVENANCE=true
-export DEDUP_DEFAULT_STRATEGY=keep_most_complete
-export DEDUP_MIN_CLUSTER_SIZE=2
-export DEDUP_MAX_CLUSTER_SIZE=100
-```
-
-### YAML Configuration
-
-```yaml
-deduplication:
- similarity_threshold: 0.8
- confidence_threshold: 0.7
- use_clustering: true
- preserve_provenance: true
- default_strategy: keep_most_complete
- min_cluster_size: 2
- max_cluster_size: 100
-
-deduplication_methods:
- levenshtein:
- case_sensitive: false
- multi_factor:
- string_weight: 0.4
- property_weight: 0.3
- embedding_weight: 0.3
-```
-
-### Programmatic Configuration
+## Merging Entities
```python
-from semantica.deduplication.config import dedup_config
-
-# Set configuration values
-dedup_config.set("similarity_threshold", 0.8)
-dedup_config.set("confidence_threshold", 0.7)
-
-# Get configuration values
-threshold = dedup_config.get("similarity_threshold", default=0.7)
-
-# Method-specific configuration
-dedup_config.set_method_config("levenshtein", case_sensitive=False)
-levenshtein_config = dedup_config.get_method_config("levenshtein")
+from semantica.deduplication import EntityMerger
-# Load from config file
-from semantica.deduplication.config import DeduplicationConfig
-config = DeduplicationConfig(config_file="config.yaml")
+merger = EntityMerger()
+merged_kg = merger.merge(
+ kg,
+ duplicates,
+ strategy="union", # "union" | "intersection" | "most_recent" | "most_confident"
+ preserve_provenance=True # keep source references after merge
+)
```
-### Configuration File Support
-
-The `DeduplicationConfig` class supports loading configuration from:
-- **YAML files** (`.yaml`, `.yml`)
-- **JSON files** (`.json`)
-- **TOML files** (`.toml`)
-
-Configuration is loaded in the following priority order:
-1. Programmatic configuration (via `set()`)
-2. Environment variables
-3. Config file values
-4. Default values
-
---
-## Integration Examples
+## Blocking Strategies
-### Ingestion Pipeline
+Blocking reduces the comparison search space for large entity sets.
```python
-from semantica.core import Semantica
-from semantica.ingest import FileIngestor
-from semantica.parse import DocumentParser
-from semantica.semantic_extract import NERExtractor
-from semantica.deduplication import DuplicateDetector, EntityMerger, MergeStrategy
-
-# 1. Build knowledge base using individual modules
-ingestor = FileIngestor()
-parser = DocumentParser()
-ner = NERExtractor()
-
-all_entities = []
-for file_path in files:
- doc = ingestor.ingest_file(file_path)
- parsed = parser.parse_document(file_path)
- text = parsed.get("full_text", "")
- entities = ner.extract_entities(text)
- all_entities.extend(entities)
-
-raw_entities = all_entities
-
-# 2. Deduplicate
-detector = DuplicateDetector(similarity_threshold=0.85)
-duplicate_groups = detector.detect_duplicate_groups(raw_entities)
-
-merger = EntityMerger(preserve_provenance=True)
-merge_operations = merger.merge_duplicates(
- raw_entities,
- strategy=MergeStrategy.MERGE_ALL
+resolver = EntityResolver(
+ blocking_strategy="token", # "token" | "phonetic" | "ngram"
+ blocking_threshold=0.6,
+ comparison_strategy="semantic_v2"
)
-
-# Extract merged entities
-merged_entities = [op.merged_entity for op in merge_operations]
```
---
-## Best Practices
-
-1. **Block First**: For >1000 entities, enable blocking to avoid O(nΒ²) performance.
-2. **Tune Thresholds**: Start with 0.85 and adjust based on false positive/negative rates.
-3. **Preserve Provenance**: Keep `preserve_provenance=True` to track where merged data came from.
-4. **Normalize**: Run `normalize` module before deduplication for best results.
-
----
-
-## Troubleshooting
-
-**Issue**: Merging "Apple" and "Apple Pie" (False Positive).
-**Solution**: Increase threshold or use Jaro-Winkler which penalizes prefix mismatches.
+## Custom Similarity Functions
```python
-detector = DuplicateDetector(
- similarity_method="jaro_winkler",
- similarity_threshold=0.9
-)
-```
+def custom_similarity(entity_a, entity_b):
+ # Domain-specific matching logic
+ return score # 0.0 to 1.0
-**Issue**: Slow performance on large datasets.
-**Solution**: Use `ClusterBuilder` with blocking.
+resolver = EntityResolver(similarity_fn=custom_similarity)
+```
---
## See Also
-- [Conflicts Module](conflicts.md) - Handling conflicting values during merge
-- [Normalize Module](normalize.md) - Pre-processing for better matching
-- [Knowledge Graph Module](kg.md) - Target for deduplicated data
-
-## Cookbook
-
-Interactive tutorials to learn deduplication:
-
-- **[Deduplication](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/18_Deduplication.ipynb)**: Advanced deduplication techniques for entity resolution
- - **Topics**: Entity deduplication, fuzzy matching, similarity thresholds, merge strategies
- - **Difficulty**: Intermediate
- - **Use Cases**: Entity resolution, data cleaning, multi-source integration
+<CardGroup cols={2}>
+ <Card title="Conflicts" icon="triangle-exclamation" href="conflicts">
+ Detect value conflicts between non-duplicate entities.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ GraphBuilder uses deduplication during construction.
+ </Card>
+ <Card title="Normalize" icon="broom" href="normalize">
+ Normalize entity names before deduplication.
+ </Card>
+ <Card title="Provenance" icon="link" href="provenance">
+ Track merged entity lineage.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.md
index 675ce733..b5098af5 100644
--- a/docs/reference/embeddings.md
+++ b/docs/reference/embeddings.md
@@ -1,256 +1,117 @@
-# Embeddings Module Reference
-
-> **Text embedding generation with multiple model support.**
-
+---
+title: "Embeddings Module"
+description: "Text embedding generation with Sentence-Transformers, FastEmbed, OpenAI, and BGE model support."
+icon: "vector-square"
---
-## 🎯 System Overview
-
-The **Embeddings Module** provides a unified interface for generating vector representations of text. It abstracts away the complexity of different providers (OpenAI, HuggingFace, FastEmbed) and ensures consistent formatting for vector databases.
-
-### What are Embeddings?
-
-**Embeddings** are numerical representations of text that capture semantic meaning. They convert words, sentences, or documents into dense vectors (arrays of numbers) in a high-dimensional space. Similar texts have similar vectors, enabling semantic search, similarity matching, and machine learning applications.
-
-### Why Use the Embeddings Module?
-
-- **Unified Interface**: Switch between different embedding providers without changing your code
-- **Consistent Formatting**: All embeddings are normalized and formatted consistently for vector databases
-- **Performance**: Optimized batch processing for high-throughput embedding generation
-- **Flexibility**: Support for local models (FastEmbed, Sentence Transformers) and API-based models (OpenAI, Anthropic)
-- **Vector DB Ready**: Automatic formatting for FAISS, Qdrant, Weaviate, and Milvus
-
-### How It Works
-
-The embeddings module uses a provider-based architecture:
-
-1. **EmbeddingGenerator**: Main orchestrator that manages the active model
-2. **Provider Stores**: Backend implementations for each provider (FastEmbed, OpenAI, etc.)
-3. **TextEmbedder**: Simplified interface focused on text-to-vector operations
-4. **VectorEmbeddingManager**: Prepares embeddings for specific vector database formats
-
-### Key Capabilities
-
-<div class="grid cards" markdown>
-
-- :material-power-plug:{ .lg .middle } **Multi-Provider Support**
-
- ---
-
- Seamlessly switch between Sentence Transformers, FastEmbed, OpenAI, and BGE models.
-
-- :material-api:{ .lg .middle } **Unified Interface**
-
- ---
-
- Single API for all embedding backends with consistent normalization and output formatting.
-
-- :material-rocket-launch:{ .lg .middle } **Efficient Batching**
-
- ---
-
- Optimized batch processing and pooling strategies for high-throughput embedding generation.
-
-- :material-database-check:{ .lg .middle } **Vector DB Ready**
-
- ---
-
- Automatic formatting and validation for FAISS, Qdrant, and Weaviate.
-
-</div>
-
-!!! tip "When to Use"
- - **Vectorization**: Converting text to embeddings for storage.
- - **Semantic Comparison**: Calculating similarity between two text snippets.
- - **Model Abstraction**: Switching between local and API-based models without code changes.
+> Unified interface for generating vector representations of text.
---
-## πŸ—οΈ Architecture Components
-
-### EmbeddingGenerator (The Orchestrator)
-The main entry point for generating embeddings. It manages the active model and routes requests to the appropriate provider store.
+## Overview
-#### **Constructor Parameters**
-* `method` (Default: `"fastembed"`): The embedding provider to use (e.g., `"sentence_transformers"`, `"openai"`, `"fastembed"`).
-* `model_name` (Optional): Specific model name (e.g., `"all-MiniLM-L6-v2"`, `"text-embedding-3-small"`).
-* `device` (Default: `"cpu"`): Computing device (`"cpu"`, `"cuda"`, `"mps"`).
-* `normalize` (Default: `True`): Whether to L2-normalize embeddings (crucial for cosine similarity).
+The **Embeddings Module** converts text into dense vectors for semantic search, entity resolution, and GraphRAG retrieval. It abstracts multiple providers behind a single API.
-#### **Core Methods**
+---
-| Method | Description |
-|--------|-------------|
-| `` `generate_embeddings(data, data_type="text")` `` | Generates an embedding for a single item |
-| `` `process_batch(items)` `` | Generates embeddings for a list of items (optimized) |
-| `` `compare_embeddings(emb1, emb2)` `` | Calculates cosine similarity between two vectors |
-| `` `get_text_method()` `` | Returns the active embedding strategy |
-| `set_text_model(method, model_name, **config)` | Dynamically switches the text embedding model. |
+## EmbeddingGenerator
-#### **Code Example**
```python
from semantica.embeddings import EmbeddingGenerator
-# 1. Initialize
-gen = EmbeddingGenerator(
- method="sentence_transformers",
- model_name="all-MiniLM-L6-v2"
-)
+# Sentence-Transformers (default, free, local)
+generator = EmbeddingGenerator(model="sentence-transformers")
+embeddings = generator.generate(["Text 1", "Text 2"])
-# 2. Generate
-vector = gen.generate_embeddings("Hello world")
+# Specific model
+generator = EmbeddingGenerator(model="BAAI/bge-large-en-v1.5")
+embeddings = generator.generate(texts)
-# 3. Compare
-vec1 = gen.generate_embeddings("AI is great")
-vec2 = gen.generate_embeddings("Machine learning is awesome")
-similarity = gen.compare_embeddings(vec1, vec2)
-print(f"Similarity: {similarity}")
+# OpenAI
+generator = EmbeddingGenerator(
+ model="openai",
+ model_name="text-embedding-3-small",
+ api_key=os.getenv("OPENAI_API_KEY")
+)
```
---
-### TextEmbedder (The Worker)
-A specialized class focused purely on text-to-vector operations. It wraps the `EmbeddingGenerator` with text-specific logic and simplified methods.
+## Supported Models
-#### **Core Methods**
+| Provider | Model | Dimension | Notes |
+|----------|-------|-----------|-------|
+| `sentence-transformers` | `all-MiniLM-L6-v2` | 384 | Default, fast, free |
+| `sentence-transformers` | `all-mpnet-base-v2` | 768 | Higher quality |
+| `bge` | `BAAI/bge-large-en-v1.5` | 1024 | State-of-the-art retrieval |
+| `fastembed` | `BAAI/bge-small-en-v1.5` | 384 | Fast, CPU-optimized |
+| `openai` | `text-embedding-3-small` | 1536 | OpenAI API |
+| `openai` | `text-embedding-3-large` | 3072 | OpenAI API, highest quality |
-| Method | Description |
-|--------|-------------|
-| `` `embed_text(text)` `` | Returns a list of floats for the input string |
-| `` `embed_batch(texts)` `` | Returns a list of lists (vectors) for the input strings |
-| `` `get_embedding_dimension()` `` | Returns the size of the output vector (e.g., 384, 768, 1536) |
-| `` `set_model(method, model_name, **config)` `` | Switches the underlying embedding model |
-| `` `get_method()` `` | Returns the current method name |
-| `` `get_model_info()` `` | Returns details about the current model |
-
-#### **Code Example**
-```python
-from semantica.embeddings import TextEmbedder
-
-# Initialize with FastEmbed (lightweight, fast)
-embedder = TextEmbedder(method="fastembed")
+---
-# Single text
-vector = embedder.embed_text("Semantica is powerful")
+## Similarity Computation
-# Batch processing (Recommended for speed)
-texts = ["Document 1", "Document 2", "Document 3"]
-vectors = embedder.embed_batch(texts)
+```python
+# Cosine similarity between two embeddings
+similarity = generator.similarity(embeddings[0], embeddings[1])
+print(f"Similarity: {similarity:.3f}") # 0.0 to 1.0
-print(f"Dimension: {embedder.get_embedding_dimension()}")
+# Find top-k most similar texts
+query_embedding = generator.generate(["machine learning"])[0]
+scores = generator.rank(query_embedding, embeddings)
```
---
-### VectorEmbeddingManager (The Bridge)
-A utility class that prepares raw embeddings for insertion into specific vector databases. It handles formatting differences between backends like FAISS and Weaviate.
-
-#### **Core Methods**
+## Batch Generation
-| Method | Description |
-|--------|-------------|
-| `prepare_for_vector_db(embeddings, metadata, backend)` | Formats data for the target DB. |
-| `validate_dimensions(embeddings, expected_dim)` | Ensures vectors match the index configuration. |
-| `batch_prepare(embeddings_list)` | Prepares a batch of embeddings for storage. |
-
-#### **Code Example**
```python
-from semantica.embeddings import VectorEmbeddingManager, TextEmbedder
-
-# 1. Generate Embeddings
-embedder = TextEmbedder()
-texts = ["Doc A", "Doc B"]
-embeddings = embedder.embed_batch(texts)
-
-# 2. Format for FAISS
-manager = VectorEmbeddingManager()
-formatted_data = manager.prepare_for_vector_db(
- embeddings,
- metadata=[{"id": 1, "text": "Doc A"}, {"id": 2, "text": "Doc B"}],
- backend="faiss"
-)
-
-# formatted_data is now ready to be passed to VectorStore
+# Efficient batched generation
+texts = ["Text 1", "Text 2", ..., "Text 10000"]
+embeddings = generator.generate_batch(texts, batch_size=128, show_progress=True)
```
---
-## βš™οΈ Configuration
-
-### Environment Variables
-
-```bash
-export EMBEDDING_MODEL=all-MiniLM-L6-v2
-export EMBEDDING_DEVICE=cuda
-export OPENAI_API_KEY=sk-...
-```
-
-### YAML Configuration
+## Caching
-```yaml
-embeddings:
- text:
- model: all-MiniLM-L6-v2
- method: sentence_transformers
- batch_size: 32
- normalize: true
+```python
+generator = EmbeddingGenerator(
+ model="sentence-transformers",
+ cache_dir=".embeddings_cache", # persist embeddings to disk
+ cache_ttl=3600 # cache TTL in seconds
+)
```
----
-
-## πŸš€ Best Practices
-
-1. **Batch Processing**: Always use `embed_batch` or `process_batch` when dealing with multiple items. It is significantly faster, especially on GPUs.
-2. **Normalization**: Keep `normalize=True` (default) if you intend to use Cosine Similarity.
-3. **Dimension Matching**: Ensure your `VectorStore` index is created with the same dimension as your embedding model (e.g., 384 for MiniLM, 1536 for OpenAI Ada).
-4. **Caching**: Embeddings are compute-intensive. Cache results where possible to avoid re-computing vectors for the same text.
+The distance intelligence feature (v0.5.0) uses embedding cache optimization to avoid recomputing embeddings for large distance matrix calculations.
---
-## 🧩 Advanced Usage
-
-### Checking Available Providers
-Dynamically check which embedding backends are installed and available.
+## GPU Acceleration
```python
-from semantica.embeddings import check_available_providers
-
-providers = check_available_providers()
-
-if providers["fastembed"]:
- print("FastEmbed is ready!")
-if providers["openai"]:
- print("OpenAI embeddings are available!")
-if providers["sentence_transformers"]:
- print("Sentence Transformers is installed!")
-
-# Check all providers
-for provider, available in providers.items():
- status = "βœ“" if available else "βœ—"
- print(f"{status} {provider}: {'Available' if available else 'Not installed'}")
+generator = EmbeddingGenerator(
+ model="sentence-transformers",
+ device="cuda" # "cpu" | "cuda" | "mps"
+)
```
-This is useful for checking which embedding providers are available before initializing an embedder, especially when working in different environments.
+---
## See Also
-- [Vector Store](vector_store.md) - Stores the generated embeddings
-- [Ingest](ingest.md) - Uses embeddings during processing
-
-## Cookbook
-
-Interactive tutorials to learn embeddings in practice:
-
-- **[Embedding Generation](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/12_Embedding_Generation.ipynb)**: Learn how to generate embeddings using different providers
- - **Topics**: FastEmbed, OpenAI, Sentence Transformers, batch processing, normalization
- - **Difficulty**: Intermediate
- - **Use Cases**: Understanding embedding generation, choosing the right provider
-
-- **[Vector Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/13_Vector_Store.ipynb)**: Set up and use vector stores for similarity search
- - **Topics**: FAISS, Weaviate, Qdrant, hybrid search, metadata filtering
- - **Difficulty**: Intermediate
- - **Use Cases**: Storing and searching embeddings, building RAG systems
-- **[Advanced Vector Store and Search](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/Advanced_Vector_Store_and_Search.ipynb)**: Advanced vector store operations and optimization
- - **Topics**: Index optimization, hybrid search, performance tuning, namespace management
- - **Difficulty**: Advanced
- - **Use Cases**: Production deployments, performance optimization
+<CardGroup cols={2}>
+ <Card title="Vector Store" icon="database" href="vector_store">
+ Store and search the generated embeddings.
+ </Card>
+ <Card title="Split" icon="scissors" href="split">
+ Chunk text before embedding.
+ </Card>
+ <Card title="KG Module" icon="diagram-project" href="kg">
+ Distance Intelligence uses embeddings for semantic neighborhoods.
+ </Card>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Semantic deduplication uses embeddings for entity resolution.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/evals.md b/docs/reference/evals.md
index 9ffe8ed6..7c9cdf5c 100644
--- a/docs/reference/evals.md
+++ b/docs/reference/evals.md
@@ -1,6 +1,44 @@
-# Evals
+---
+title: "Evals Module"
+description: "Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance."
+icon: "chart-line"
+---
-> **Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance.**
+> Measure and benchmark Knowledge Graph quality, extraction accuracy, and pipeline performance.
-!!! warning "Coming Soon"
- This module is currently in active development. Documentation will be available soon.
+<Warning>
+ **Coming Soon** β€” This module is currently in active development. Documentation will be available in an upcoming release.
+</Warning>
+
+---
+
+## Planned Capabilities
+
+The Evals module will provide a comprehensive evaluation framework covering:
+
+| Area | What It Measures |
+|------|-----------------|
+| **KG Quality** | Completeness, consistency, schema compliance |
+| **Extraction Accuracy** | NER precision/recall/F1, relation extraction metrics |
+| **Pipeline Performance** | Throughput, latency, error rates per step |
+| **Deduplication** | Merge accuracy, false positive/negative rates |
+| **Reasoning** | Inference correctness, rule coverage |
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Extraction module to evaluate.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ Graph quality assessment.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Pipeline performance metrics.
+ </Card>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Deduplication accuracy evaluation.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/explorer.md b/docs/reference/explorer.md
new file mode 100644
index 00000000..6367a438
--- /dev/null
+++ b/docs/reference/explorer.md
@@ -0,0 +1,146 @@
+---
+title: "Explorer"
+description: "Interactive FastAPI dashboard for knowledge graph exploration and the Ontology Hub."
+icon: "map"
+---
+
+`semantica.explorer` provides a browser-based dashboard for exploring knowledge graphs, managing ontologies, and running visual analyses β€” no code required.
+
+---
+
+## Installation
+
+```bash
+pip install "semantica[explorer]"
+```
+
+Requires `uvicorn` and `fastapi`. Included automatically with `pip install semantica[all]`.
+
+---
+
+## Launch
+
+<CodeGroup>
+
+```bash CLI
+# Start the explorer on a saved graph
+semantica-explorer --graph my_graph.json
+
+# Custom host and port
+semantica-explorer --graph my_graph.json --host 0.0.0.0 --port 8080
+
+# Don't auto-open browser
+semantica-explorer --graph my_graph.json --no-browser
+```
+
+```python Python
+from semantica.context import ContextGraph
+from semantica.explorer import start_explorer
+
+graph = ContextGraph(advanced_analytics=True)
+# ... build or load your graph ...
+graph.save("my_graph.json")
+
+# Launch the dashboard
+start_explorer(graph_path="my_graph.json", port=8000)
+```
+
+```python Module
+# Run directly as a Python module
+# python -m semantica.explorer --graph my_graph.json --port 8000
+import subprocess
+subprocess.run(["python", "-m", "semantica.explorer", "--graph", "my_graph.json"])
+```
+
+</CodeGroup>
+
+---
+
+## CLI Reference
+
+| Flag | Default | Description |
+|------|---------|-------------|
+| `--graph`, `-g` | *(required)* | Path to a ContextGraph JSON file |
+| `--port`, `-p` | `8000` | Port to bind the server |
+| `--host` | `127.0.0.1` | Host to bind the server |
+| `--no-browser` | `false` | Skip auto-opening the browser |
+
+---
+
+## Features
+
+### Graph Explorer
+
+The core dashboard for navigating knowledge graphs:
+
+- **Indexed search** β€” find any node by label or type; 0.004ms on 118k-node graphs
+- **Bidirectional path finding** β€” trace paths between any two nodes
+- **Neighbor expansion** β€” click any node to expand its connections
+- **Filter by entity type** β€” focus on specific node types (Person, Organization, Event, etc.)
+- **Edge label display** β€” relationship types shown on all edges
+- **Graph declutter** β€” workspace layout controls for dense graphs
+
+### Ontology Hub (v0.5.0)
+
+Full ontology lifecycle management in the browser:
+
+- **Visual ontology editor** β€” drag-and-drop class and property authoring
+- **SHACL Studio** β€” create, validate, and test SHACL shapes with live feedback
+- **Alignment authoring** β€” author ontology alignments across schemas
+- **Health dashboard** β€” graph quality metrics, validation status, coverage reports
+- **Version control** β€” snapshot, diff, and restore ontology versions
+
+### Distance Intelligence (v0.5.0)
+
+Semantic neighborhood analysis:
+
+- **NΓ—N distance matrices** β€” pairwise semantic distances across node sets
+- **Ego-mode visualization** β€” focus on a single node's semantic neighborhood
+- **Distance band classification** β€” nodes grouped as `near` / `mid` / `far`
+- **Embedding cache** β€” optimized embedding reuse for large graphs
+
+### Knowledge Explorer API
+
+Full FastAPI backend accessible at `http://localhost:8000/docs`:
+
+- 12+ export formats (RDF, Parquet, AQL, JSON-LD, and more)
+- WebSocket progress streaming for long operations
+- Thread-safe sessions with rollback protection
+- Audit trail for all operations
+
+---
+
+## API Endpoints
+
+The FastAPI server exposes a REST API alongside the browser dashboard:
+
+| Endpoint | Method | Description |
+|----------|--------|-------------|
+| `/api/graph/summary` | `GET` | Node count, edge count, entity types |
+| `/api/graph/search` | `GET` | Full-text and type-filtered node search |
+| `/api/graph/path` | `GET` | Bidirectional path between two nodes |
+| `/api/graph/neighbors` | `GET` | Neighbors of a node with optional depth |
+| `/api/ontology/validate` | `POST` | Run SHACL validation on the graph |
+| `/api/export/{format}` | `GET` | Export graph in specified format |
+| `/ws/progress` | `WS` | WebSocket stream for operation progress |
+
+Full OpenAPI docs available at `http://localhost:8000/docs` when the server is running.
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Context" icon="brain" href="context">
+ Build and save the ContextGraph that Explorer loads.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Programmatic ontology management and SHACL generation.
+ </Card>
+ <Card title="Visualization" icon="chart-network" href="visualization">
+ Programmatic graph rendering without the full Explorer server.
+ </Card>
+ <Card title="Export" icon="file-export" href="export">
+ Export to RDF, Parquet, AQL without launching a server.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/export.md b/docs/reference/export.md
index 61b944ab..c84c0b6c 100644
--- a/docs/reference/export.md
+++ b/docs/reference/export.md
@@ -1,951 +1,131 @@
-# Export
-
-> **Export knowledge graphs and data to multiple formats with W3C-compliant serialization.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-file-export:{ .lg .middle } **Multi-Format Export**
-
- ---
-
- Support for 10+ export formats including RDF, JSON, CSV, GraphML
-
-- :material-database-export:{ .lg .middle } **Graph Databases**
-
- ---
-
- Direct export to Neo4j, ArangoDB, Memgraph with Cypher generation
-
-- :material-code-json:{ .lg .middle } **RDF Serialization**
-
- ---
-
- W3C-compliant formats: Turtle, RDF/XML, JSON-LD, N-Triples
-
-- :material-cog:{ .lg .middle } **Custom Serializers**
-
- ---
-
- Extensible serialization framework for custom formats
-
-- :material-flash:{ .lg .middle } **Batch Export**
-
- ---
-
- Efficient large-scale data export with streaming support
-
-- :material-file-multiple:{ .lg .middle } **Multiple Outputs**
-
- ---
-
- Export to Cytoscape.js, D3.js, Gephi, Graphviz formats
-
-</div>
-
-!!! tip "Choosing Export Format"
- - **Development**: Use Turtle for human-readable RDF
- - **APIs**: Use JSON-LD for web services
- - **Visualization**: Use GraphML or Cytoscape.js
- - **Databases**: Use Neo4j Cypher or CSV for bulk import
-
+title: "Export Module"
+description: "Export knowledge graphs to RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, OWL, and CSV."
+icon: "file-export"
---
-## βš™οΈ Algorithms Used
-
-### Serialization Algorithms
-
-**RDF/XML Serialization**:
-- **Standard**: W3C RDF/XML specification
-- **Format**: XML-based RDF representation
-- **Use case**: Interoperability with XML-based systems
-
-**Turtle Serialization**:
-- **Standard**: W3C Turtle specification
-- **Format**: Compact RDF format with prefix compression
-- **Use case**: Human-readable RDF representation
-
-**JSON-LD Serialization**:
-- **Standard**: W3C JSON-LD specification
-- **Format**: JSON-based linked data with context
-- **Use case**: Web APIs and JavaScript applications
-
-**GraphML Generation**:
-- **Format**: XML-based graph format
-- **Use case**: Graph visualization tools (Gephi, Cytoscape)
-
-**Cypher Query Generation**:
-- **Format**: Neo4j query language
-- **Use case**: Direct import into Neo4j graph database
-
-### Export Optimization
-
-**Streaming Export**:
-- **Purpose**: Memory-efficient export for large graphs
-- **How it works**: Processes data in chunks without loading entire graph into memory
-- **Use case**: Exporting graphs with millions of nodes/edges
-
-**Batch Processing**:
-- **Purpose**: Efficient large-scale data export
-- **How it works**: Chunked export with configurable batch sizes
-- **Use case**: Exporting multiple graphs or large datasets
-
-**Compression**:
-- **Purpose**: Reduce file size for large exports
-- **How it works**: GZIP compression for large exports
-- **Use case**: Network transfer and storage optimization
-
-**Incremental Export**:
-- **Purpose**: Export only changed data
-- **How it works**: Tracks changes and exports only modified entities/relationships
-- **Use case**: Regular updates and synchronization
+> Export knowledge graphs and data to multiple formats with W3C-compliant serialization.
---
-## Main Classes
-
-### RDFExporter
-
-Export knowledge graphs to RDF formats (Turtle, RDF/XML, JSON-LD, N-Triples).
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to RDF format | RDF serialization with format-specific encoding |
-| `` `export_knowledge_graph(kg, filename, format)` `` | Export knowledge graph | Knowledge graph to RDF conversion |
-| `` `serialize(graph, format)` `` | Serialize to string | In-memory RDF generation |
-| `` `validate_rdf(rdf_data)` `` | Validate RDF syntax | RDF schema validation |
-
-### RDFSerializer
-
-RDF serialization engine for format conversion.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `serialize_to_turtle(rdf_data)` `` | Serialize to Turtle | Compact RDF format with prefix compression |
-| `` `serialize_to_rdfxml(rdf_data)` `` | Serialize to RDF/XML | XML-based RDF format |
-| `` `serialize_to_jsonld(rdf_data)` `` | Serialize to JSON-LD | JSON-based linked data format |
-
-### RDFValidator
-
-RDF validation engine for syntax and consistency checking.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `validate_rdf_syntax(rdf_data, format)` `` | Validate RDF syntax | Format-specific syntax validation |
-| `` `check_rdf_consistency(rdf_data)` `` | Check consistency | Entity reference and structure validation |
-
-### NamespaceManager
-
-RDF namespace management and conflict resolution.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `extract_namespaces(rdf_data)` `` | Extract namespaces | Namespace discovery from RDF data |
-| `` `generate_namespace_declarations(namespaces, format)` `` | Generate declarations | Format-specific namespace declaration |
-| `` `resolve_conflicts(namespaces)` `` | Resolve conflicts | Prefix conflict resolution |
-
-**Supported RDF Formats:**
-
-| Format | Extension | Description | Use Case |
-|--------|-----------|-------------|----------|
-| **Turtle** | .ttl | Compact, human-readable | Development, debugging |
-| **N-Triples** | .nt | Line-based, simple | Streaming, processing |
-| **RDF/XML** | .rdf | XML-based, verbose | Legacy systems |
-| **JSON-LD** | .jsonld | JSON with linked data | Web APIs, JavaScript |
-| **N-Quads** | .nq | N-Triples with graphs | Named graphs |
-
-**Example:**
+## RDFExporter
```python
from semantica.export import RDFExporter
-exporter = RDFExporter(
- base_uri="http://example.org/",
- namespaces={
- "ex": "http://example.org/",
- "foaf": "http://xmlns.com/foaf/0.1/"
- }
-)
-
-# Export to Turtle
-exporter.export(
- graph=kg,
- filename="output.ttl",
- format="turtle"
-)
-
-# Export to JSON-LD
-exporter.export(
- graph=kg,
- filename="output.jsonld",
- format="json-ld"
-)
-```
-
----
-
-### JSONExporter
+exporter = RDFExporter()
-Export knowledge graphs to JSON formats including JSON-LD, Cytoscape.js, and D3.js.
+# Turtle
+rdf = exporter.export_to_rdf(graph, format="turtle")
+exporter.export_to_file(graph, "output.ttl", format="turtle")
-**Methods:**
+# JSON-LD
+rdf = exporter.export_to_rdf(graph, format="json-ld")
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to JSON | JSON serialization with schema |
-| `` `export_nodes(graph)` `` | Export nodes only | Node extraction and serialization |
-| `` `export_edges(graph)` `` | Export edges only | Edge extraction and serialization |
-| `` `export_cytoscape(graph)` `` | Export Cytoscape.js format | Cytoscape JSON generation |
-| `export_d3(graph)` | Export D3.js format | D3 force-directed graph format |
+# N-Triples
+rdf = exporter.export_to_rdf(graph, format="nt")
-**JSON Formats:**
-
-- **Standard JSON**: Simple node/edge lists
-- **JSON-LD**: Linked data with @context
-- **Cytoscape.js**: For Cytoscape visualization
-- **D3.js**: For D3 force-directed graphs
-- **Neo4j JSON**: Neo4j-compatible format
-
-**Example:**
-
-```python
-from semantica.export import JSONExporter
-
-exporter = JSONExporter()
-
-# Standard JSON export
-exporter.export(kg, "output.json", format="standard")
-
-# JSON-LD export
-exporter.export(kg, "output.jsonld", format="json-ld")
-
-# Cytoscape format
-exporter.export_cytoscape(kg, "cytoscape.json")
+# RDF/XML
+rdf = exporter.export_to_rdf(graph, format="xml")
```
---
-### GraphExporter
-
-Export to graph visualization formats (GraphML, GEXF, DOT, Pajek).
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to graph format | Format-specific serialization |
-| `` `to_graphml(graph, filename)` `` | Export to GraphML | XML-based graph format |
-| `` `to_gexf(graph, filename)` `` | Export to GEXF | Gephi exchange format |
-| `` `to_dot(graph, filename)` `` | Export to DOT | Graphviz format |
-| `` `to_pajek(graph, filename)` `` | Export to Pajek | Pajek network format |
-
-**Graph Formats:**
-
-| Format | Tool | Use Case |
-|--------|------|----------|
-| **GraphML** | yEd, Gephi | General graph visualization |
-| **GEXF** | Gephi | Network analysis |
-| **DOT** | Graphviz | Diagram generation |
-| **Pajek** | Pajek | Large network analysis |
-| **GML** | Various | Graph Modeling Language |
-
-**Example:**
-
-```python
-from semantica.export import GraphExporter
-
-exporter = GraphExporter()
-
-# Export to GraphML
-exporter.to_graphml(kg, "graph.graphml")
-
-# Export to DOT for Graphviz
-exporter.to_dot(kg, "graph.dot")
-```
-
----
-
-### LPGExporter
-
-Export to LPG (Labeled Property Graph) format for Neo4j, Memgraph, and similar databases.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(knowledge_graph, file_path)` `` | Export to LPG format | Cypher query generation |
-| `` `export_knowledge_graph(kg, file_path)` `` | Export knowledge graph | Knowledge graph to Cypher conversion |
-| `` `generate_cypher(kg)` `` | Generate Cypher queries | CREATE/MERGE statement generation |
-
-**Cypher Generation:**
-```cypher
-// Node creation
-CREATE (n:Person {name: "Steve Jobs", born: 1955})
-
-// Relationship creation
-MATCH (a:Person {name: "Steve Jobs"}), (b:Organization {name: "Apple Inc."})
-CREATE (a)-[:FOUNDED]->(b)
-```
-
-**Example:**
-
-```python
-from semantica.export import LPGExporter
-
-exporter = LPGExporter(batch_size=1000, include_indexes=True)
-
-# Export to Cypher file
-exporter.export_knowledge_graph(kg, "graph.cypher")
-
-# Generate Cypher queries
-cypher_queries = exporter.generate_cypher(kg)
-print(cypher_queries)
-```
-
----
-
-### CSVExporter
-
-Export to CSV format for spreadsheets and database imports.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export_nodes(graph, filename)` `` | Export nodes to CSV | Node flattening and CSV writing |
-| `` `export_edges(graph, filename)` `` | Export edges to CSV | Edge list CSV generation |
-| `` `export_combined(graph, prefix)` `` | Export nodes + edges | Separate CSV files |
-| `` `flatten_properties(properties)` `` | Flatten nested properties | Recursive property flattening |
-
-**CSV Formats:**
-- **Nodes CSV**: id, label, properties (flattened)
-- **Edges CSV**: source, target, type, properties
-- **Neo4j Import Format**: Neo4j-compatible CSV
-
-**Example:**
-
-```python
-from semantica.export import CSVExporter
-
-exporter = CSVExporter()
-
-# Export nodes and edges separately
-exporter.export_nodes(kg, "nodes.csv")
-exporter.export_edges(kg, "edges.csv")
-
-# Or combined export
-exporter.export_combined(kg, prefix="graph")
-# Creates: graph_nodes.csv, graph_edges.csv
-```
-
----
-
-### VectorExporter
-
-Export vector embeddings to various formats.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(vectors, filename, format)` `` | Export vectors | Format-specific vector serialization |
-| `` `export_numpy(vectors, filename)` `` | Export to NumPy | .npy format |
-| `` `export_hdf5(vectors, filename)` `` | Export to HDF5 | Hierarchical data format |
-| `` `export_parquet(vectors, filename)` `` | Export to Parquet | Columnar storage format |
-
-**Example:**
-
-```python
-from semantica.export import VectorExporter
-
-exporter = VectorExporter(format="json", include_metadata=True)
-exporter.export(vectors, "vectors.json")
-```
-
----
-
-### OWLExporter
-
-Export ontologies to OWL format (OWL/XML, Turtle).
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(ontology, filename, format)` `` | Export ontology | OWL serialization |
-| `` `export_classes(classes, filename)` `` | Export classes | Class definition export |
-| `` `export_properties(properties, filename)` `` | Export properties | Property definition export |
-
-**Example:**
+## OWL Exporter
```python
from semantica.export import OWLExporter
-exporter = OWLExporter(ontology_uri="http://example.org/ontology#")
-exporter.export(ontology, "ontology.owl", format="owl-xml")
+exporter = OWLExporter()
+exporter.export(ontology, path="ontology.ttl", format="turtle")
+exporter.export(ontology, path="ontology.owl", format="xml")
```
---
-### SemanticNetworkYAMLExporter
+## Parquet Exporter
-Export semantic networks to YAML format.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(semantic_network, filename)` `` | Export semantic network | YAML serialization |
-| `` `export_semantic_network(semantic_network)` `` | Export to string | In-memory YAML generation |
-
-**Example:**
+For Spark, BigQuery, and Databricks pipelines.
```python
-from semantica.export import SemanticNetworkYAMLExporter
+from semantica.export import ParquetExporter
-exporter = SemanticNetworkYAMLExporter()
-exporter.export(semantic_network, "network.yaml")
-```
+exporter = ParquetExporter()
----
-
-### YAMLSchemaExporter
-
-Export ontology schemas to YAML format.
-
-**Methods:**
+# Export nodes
+exporter.export_nodes(graph, "nodes.parquet")
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export_ontology_schema(ontology, filename)` `` | Export ontology schema | YAML schema serialization |
+# Export edges
+exporter.export_edges(graph, "edges.parquet")
-**Example:**
-
-```python
-from semantica.export import YAMLSchemaExporter
-
-exporter = YAMLSchemaExporter()
-exporter.export_ontology_schema(schema, "schema.yaml")
+# Export full graph (partitioned)
+exporter.export(graph, output_dir="graph_parquet/", partition_by="node_type")
```
---
-### ReportGenerator
-
-Generate reports in multiple formats (HTML, Markdown, JSON, Text).
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `generate_report(data, filename, format)` `` | Generate report | Template-based report generation |
-| `` `generate_quality_report(metrics, filename, format)` `` | Generate quality report | Quality metrics aggregation |
-
-**Example:**
-
-```python
-from semantica.export import ReportGenerator
-
-generator = ReportGenerator(format="html", include_charts=True)
-generator.generate_report(data, "report.html")
-```
-
----
-
-### MethodRegistry
-
-Registry for custom export methods.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `register(task, name, method_func)` `` | Register method | Dictionary-based registration |
-| `` `get(task, name)` `` | Get method | Hash-based lookup |
-| `` `list_all(task)` `` | List methods | Method discovery |
-| `` `unregister(task, name)` `` | Unregister method | Method removal |
-| `` `clear(task)` `` | Clear methods | Registry cleanup |
-
-**Global Instance:**
-- `method_registry`: Global method registry instance
-
-**Example:**
-
-```python
-from semantica.export import method_registry
-
-method_registry.register("json", "custom_method", custom_json_export)
-method = method_registry.get("json", "custom_method")
-all_methods = method_registry.list_all()
-```
-
----
-
-### ExportConfig
-
-Configuration manager for export module.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `set(key, value)` `` | Set configuration | Configuration storage |
-| `` `get(key, default)` `` | Get configuration | Configuration retrieval |
-| `` `set_method_config(task, **config)` `` | Set method config | Method-specific configuration |
-| `` `get_method_config(task)` `` | Get method config | Method configuration retrieval |
-
-**Global Instance:**
-- `export_config`: Global export configuration instance
-
-**Example:**
-
-```python
-from semantica.export.config import export_config, ExportConfig
-
-# Using global instance
-export_config.set("default_format", "json")
-format = export_config.get("default_format", default="json")
-
-# Create custom instance
-config = ExportConfig(config_file="config.yaml")
-```
-
----
-
-## Convenience Functions
-
-### Export Functions
-
-| Function | Description | Format |
-|----------|-------------|--------|
-| `` `export_rdf(data, file_path, format)` `` | Export to RDF | turtle, rdfxml, jsonld, ntriples, n3 |
-| `` `export_json(data, file_path, format)` `` | Export to JSON | json, json-ld |
-| `` `export_csv(data, file_path)` `` | Export to CSV | csv |
-| `` `export_graph(graph_data, file_path, format)` `` | Export to graph format | graphml, gexf, dot |
-| `` `export_yaml(data, file_path, method)` `` | Export to YAML | semantic_network, schema |
-| `` `export_owl(ontology, file_path, format)` `` | Export to OWL | owl-xml, turtle |
-| `` `export_vector(vectors, file_path, format)` `` | Export vectors | json, numpy, binary, faiss |
-| `` `export_lpg(kg, file_path, method)` `` | Export to LPG | cypher, lpg |
-| `` `generate_report(data, file_path, format)` `` | Generate report | html, markdown, json, text |
-
-### Registry Functions
-
-| Function | Description |
-|----------|-------------|
-| `` `get_export_method(task, name)` `` | Get registered export method |
-| `` `list_available_methods(task)` `` | List all available methods |
-
-**Example:**
-
-```python
-from semantica.export.methods import (
- export_rdf, export_json, export_csv, export_graph,
- export_yaml, export_owl, export_vector, export_lpg,
- generate_report, get_export_method, list_available_methods
-)
-
-# Export functions
-export_rdf(kg, "output.ttl", format="turtle")
-export_json(kg, "output.json", format="json")
-export_lpg(kg, "graph.cypher", method="cypher")
-
-# Registry functions
-method = get_export_method("json", "custom_method")
-all_methods = list_available_methods()
-```
-
----
-
-## Configuration
-
-```yaml
-# config.yaml - Export Configuration
-
-export:
- rdf:
- default_format: turtle
- base_uri: "http://example.org/"
- include_provenance: true
- validate_output: true
-
- json:
- pretty_print: true
- indent: 2
- ensure_ascii: false
-
- graph:
- include_metadata: true
- export_properties: true
-
- neo4j:
- batch_size: 1000
- create_indexes: true
- create_constraints: true
-
- csv:
- delimiter: ","
- quote_char: "\""
- encoding: "utf-8"
- include_header: true
-```
-
----
-
-## Performance Characteristics
-
-### Export Speed
-
-| Format | Small Graph | Large Graph | Compression |
-|--------|-------------|-------------|-------------|
-| JSON | Fast | Medium | Good with gzip |
-| RDF/XML | Medium | Slow | Poor |
-| Turtle | Fast | Fast | Good |
-| CSV | Very Fast | Very Fast | Excellent |
-| Neo4j | Medium | Medium | N/A |
-
-### Memory Usage
-
-- **Streaming Export**: Constant memory usage
-- **Batch Export**: Memory proportional to batch size
-- **Full Export**: Memory proportional to graph size
-
----
-
-## See Also
-
-- [Knowledge Graph Module](kg.md) - Build graphs
-- [Visualization Module](visualization.md) - Visualize exported graphs
-- [Core Module](core.md) - Framework orchestration
-
-## Cookbook
-
-Interactive tutorials to learn export capabilities:
-
-- **[Export](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/15_Export.ipynb)**: Export knowledge graphs to various formats
- - **Topics**: RDF, JSON, CSV, OWL export, format conversion
- - **Difficulty**: Intermediate
- - **Use Cases**: Data export, format conversion, interoperability
-
-- **[Multi-Format Export](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)**: Exporting to RDF, OWL, JSON-LD, and NetworkX formats
- - **Topics**: Serialization, interoperability, multiple formats, batch export
- - **Difficulty**: Intermediate
- - **Use Cases**: Multi-format export, data interoperability
-
----
-
-## Algorithms Used
-
-### Serialization Algorithms
-- **RDF/XML Serialization**: W3C RDF/XML specification
-- **Turtle Serialization**: Compact RDF format with prefix compression
-- **JSON-LD Serialization**: JSON-based linked data with context
-- **GraphML Generation**: XML-based graph format
-- **Cypher Query Generation**: Neo4j query language generation
-
-### Export Optimization
-- **Streaming Export**: Memory-efficient export for large graphs
-- **Batch Processing**: Chunked export with configurable batch sizes
-- **Compression**: GZIP compression for large exports
-- **Incremental Export**: Export only changed data
-
----
-
-## Main Classes
-
-### RDFExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to RDF format | RDF serialization with format-specific encoding |
-| `` `serialize(graph, format)` `` | Serialize to string | In-memory RDF generation |
-| `` `validate(rdf_data)` `` | Validate RDF syntax | RDF schema validation |
-| `` `add_namespace(prefix, uri)` `` | Add namespace | Prefix registration |
-| `` `set_base_uri(uri)` `` | Set base URI | Base URI configuration |
-
-**Supported RDF Formats:**
-
-| Format | Extension | Description | Use Case |
-|--------|-----------|-------------|----------|
-| **Turtle** | .ttl | Compact, human-readable | Development, debugging |
-| **N-Triples** | .nt | Line-based, simple | Streaming, processing |
-| **RDF/XML** | .rdf | XML-based, verbose | Legacy systems |
-| **JSON-LD** | .jsonld | JSON with linked data | Web APIs, JavaScript |
-| **N-Quads** | .nq | N-Triples with graphs | Named graphs |
-
-**Example:**
+## ArangoDB AQL Exporter
```python
-from semantica.export import RDFExporter
+from semantica.export import ArangoExporter
-exporter = RDFExporter(
- base_uri="http://example.org/",
- namespaces={
- "ex": "http://example.org/",
- "foaf": "http://xmlns.com/foaf/0.1/"
- }
-)
-
-# Export to Turtle
-exporter.export(
- graph=kg,
- filename="output.ttl",
- format="turtle"
-)
-
-# Export to JSON-LD
-exporter.export(
- graph=kg,
- filename="output.jsonld",
- format="json-ld"
-)
+exporter = ArangoExporter()
+aql = exporter.export(graph) # returns ready-to-run INSERT statements
+exporter.export_to_file(graph, "arango_import.aql")
```
---
-### JSONExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to JSON | JSON serialization with schema |
-| `` `export_nodes(graph)` `` | Export nodes only | Node extraction and serialization |
-| `` `export_edges(graph)` `` | Export edges only | Edge extraction and serialization |
-| `` `export_cytoscape(graph)` `` | Export Cytoscape.js format | Cytoscape JSON generation |
-| `export_d3(graph)` | Export D3.js format | D3 force-directed graph format |
-
-**JSON Formats:**
-
-- **Standard JSON**: Simple node/edge lists
-- **JSON-LD**: Linked data with @context
-- **Cytoscape.js**: For Cytoscape visualization
-- **D3.js**: For D3 force-directed graphs
-- **Neo4j JSON**: Neo4j-compatible format
-
-**Example:**
+## CSV Exporter
```python
-from semantica.export import JSONExporter
-
-exporter = JSONExporter()
-
-# Standard JSON export
-exporter.export(kg, "output.json", format="standard")
-
-# JSON-LD export
-exporter.export(kg, "output.jsonld", format="json-ld")
-
-# Cytoscape format
-exporter.export_cytoscape(kg, "cytoscape.json")
-```
-
----
-
-### GraphExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, filename, format)` `` | Export to graph format | Format-specific serialization |
-| `` `to_graphml(graph, filename)` `` | Export to GraphML | XML-based graph format |
-| `` `to_gexf(graph, filename)` `` | Export to GEXF | Gephi exchange format |
-| `` `to_dot(graph, filename)` `` | Export to DOT | Graphviz format |
-| `` `to_pajek(graph, filename)` `` | Export to Pajek | Pajek network format |
-
-**Graph Formats:**
-
-| Format | Tool | Use Case |
-|--------|------|----------|
-| **GraphML** | yEd, Gephi | General graph visualization |
-| **GEXF** | Gephi | Network analysis |
-| **DOT** | Graphviz | Diagram generation |
-| **Pajek** | Pajek | Large network analysis |
-| **GML** | Various | Graph Modeling Language |
-
-**Example:**
-
-```python
-from semantica.export import GraphExporter
-
-exporter = GraphExporter()
-
-# Export to GraphML
-exporter.to_graphml(kg, "graph.graphml")
+from semantica.export import CSVExporter
-# Export to DOT for Graphviz
-exporter.to_dot(kg, "graph.dot")
+exporter = CSVExporter()
+exporter.export_nodes(graph, "nodes.csv")
+exporter.export_edges(graph, "edges.csv")
```
---
-### Neo4jExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(graph, uri, username, password)` `` | Export to Neo4j | Cypher query execution |
-| `` `generate_cypher(graph)` `` | Generate Cypher queries | CREATE/MERGE statement generation |
-| `` `batch_import(graph, batch_size)` `` | Batch import | Chunked Cypher execution |
-| `` `create_indexes(properties)` `` | Create indexes | Index creation for performance |
-| `` `create_constraints(constraints)` `` | Create constraints | Uniqueness constraint creation |
-
-**Cypher Generation:**
-```cypher
-// Node creation
-CREATE (n:Person {name: "Steve Jobs", born: 1955})
-
-// Relationship creation
-MATCH (a:Person {name: "Steve Jobs"}), (b:Organization {name: "Apple Inc."})
-CREATE (a)-[:FOUNDED]->(b)
-```
-
-**Example:**
+## GraphML Exporter
```python
-from semantica.export import Neo4jExporter
-
-exporter = Neo4jExporter()
-
-# Direct export to Neo4j
-exporter.export(
- graph=kg,
- uri="bolt://localhost:7687",
- username="neo4j",
- password="password"
-)
+from semantica.export import GraphMLExporter
-# Generate Cypher queries
-cypher_queries = exporter.generate_cypher(kg)
-print(cypher_queries)
+exporter = GraphMLExporter()
+exporter.export(graph, "graph.graphml")
```
---
-### CSVExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export_nodes(graph, filename)` `` | Export nodes to CSV | Node flattening and CSV writing |
-| `` `export_edges(graph, filename)` `` | Export edges to CSV | Edge list CSV generation |
-| `` `export_combined(graph, prefix)` `` | Export nodes + edges | Separate CSV files |
-| `` `flatten_properties(properties)` `` | Flatten nested properties | Recursive property flattening |
-
-**CSV Formats:**
-- **Nodes CSV**: id, label, properties (flattened)
-- **Edges CSV**: source, target, type, properties
-- **Neo4j Import Format**: Neo4j-compatible CSV
-
-**Example:**
+## Selective Export
```python
-from semantica.export import CSVExporter
-
-exporter = CSVExporter()
-
-# Export nodes and edges separately
-exporter.export_nodes(kg, "nodes.csv")
-exporter.export_edges(kg, "edges.csv")
+# Export subgraph by node IDs
+subgraph = graph.subgraph(node_ids=["apple_inc", "steve_jobs"])
+exporter.export_to_file(subgraph, "subgraph.ttl", format="turtle")
-# Or combined export
-exporter.export_combined(kg, prefix="graph")
-# Creates: graph_nodes.csv, graph_edges.csv
+# Export by node type
+org_nodes = graph.filter(node_type="Organization")
+exporter.export_nodes(org_nodes, "organizations.parquet")
```
---
-### VectorExporter
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `` `export(embeddings, filename, format)` `` | Export vectors | Format-specific vector serialization |
-| `` `export_numpy(embeddings, filename)` `` | Export to NumPy | .npy format |
-| `` `export_hdf5(embeddings, filename)` `` | Export to HDF5 | Hierarchical data format |
-| `` `export_parquet(embeddings, filename)` `` | Export to Parquet | Columnar storage format |
-
----
-
-## Configuration
-
-```yaml
-# config.yaml - Export Configuration
-
-export:
- rdf:
- default_format: turtle
- base_uri: "http://example.org/"
- include_provenance: true
- validate_output: true
-
- json:
- pretty_print: true
- indent: 2
- ensure_ascii: false
-
- graph:
- include_metadata: true
- export_properties: true
-
- neo4j:
- batch_size: 1000
- create_indexes: true
- create_constraints: true
-
- csv:
- delimiter: ","
- quote_char: "\""
- encoding: "utf-8"
- include_header: true
-```
-
----
-
-## Performance Characteristics
-
-### Export Speed
-
-| Format | Small Graph | Large Graph | Compression |
-|--------|-------------|-------------|-------------|
-| JSON | Fast | Medium | Good with gzip |
-| RDF/XML | Medium | Slow | Poor |
-| Turtle | Fast | Fast | Good |
-| CSV | Very Fast | Very Fast | Excellent |
-| Neo4j | Medium | Medium | N/A |
-
-### Memory Usage
-
-- **Streaming Export**: Constant memory usage
-- **Batch Export**: Memory proportional to batch size
-- **Full Export**: Memory proportional to graph size
-
----
-
## See Also
-- [Knowledge Graph Module](kg.md) - Build graphs
-- [Visualization Module](visualization.md) - Visualize exported graphs
-- [Core Module](core.md) - Framework orchestration
+<CardGroup cols={2}>
+ <Card title="Triplet Store" icon="table" href="triplet_store">
+ Store RDF exports in a SPARQL-queryable backend.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Export OWL ontologies.
+ </Card>
+ <Card title="Provenance" icon="link" href="provenance">
+ Include provenance in RDF exports.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Add export as a pipeline step.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/graph_store.md b/docs/reference/graph_store.md
index c436ca55..cef79b7b 100644
--- a/docs/reference/graph_store.md
+++ b/docs/reference/graph_store.md
@@ -1,436 +1,149 @@
-# Graph Store
-
-> **Unified interface for Property Graph Databases (Neo4j, FalkorDB).**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-database-search:{ .lg .middle } **Multi-Backend**
-
- ---
-
- Support for Neo4j (Enterprise) and FalkorDB (Redis-based)
-
-- :material-code-braces:{ .lg .middle } **Cypher Support**
-
- ---
-
- Execute standard Cypher queries across all supported backends
-
-- :material-graph:{ .lg .middle } **Graph Algorithms**
-
- ---
-
- Built-in support for PageRank, Community Detection, and Path Finding
-
-- :material-flash:{ .lg .middle } **Bulk Loading**
-
- ---
-
- Optimized batch processing for high-speed data ingestion
-
-- :material-lock:{ .lg .middle } **Transactions**
-
- ---
-
- ACID transaction support with rollback capabilities
-
-- :material-chart-bell-curve:{ .lg .middle } **Analytics**
-
- ---
-
- Centrality, Similarity, and Connectivity analysis
-
-</div>
-
-!!! tip "When to Use"
- - **Persistent Storage**: Storing the Knowledge Graph for long-term access
- - **Complex Queries**: Running multi-hop pattern matching queries
- - **Graph Analytics**: Performing global analysis on the graph structure
- - **Production**: Scaling to billions of nodes/edges (Neo4j/FalkorDB)
-
+title: "Graph Store Module"
+description: "Unified interface for Neo4j, FalkorDB, Apache AGE, and Amazon Neptune graph databases."
+icon: "server"
---
-## βš™οΈ Algorithms Used
-
-### Query Execution
-
-The module provides efficient query execution:
-
-- **Cypher Translation**: Adapting queries for specific backend nuances (though most support OpenCypher)
-- **Query Optimization**: Index utilization and execution plan analysis
-
-### Graph Analytics
-
-Built-in graph analytics algorithms include:
-
-- **PageRank**: Measuring node importance based on incoming links
-- **Louvain Modularity**: Detecting communities by optimizing modularity
-- **Shortest Path**: Dijkstra/A* for finding optimal routes
-- **Jaccard Similarity**: Measuring node similarity based on shared neighbors
-
-### Bulk Operations
-
-Efficient bulk loading capabilities:
-
-- **Chunking**: Splitting large datasets into optimal batch sizes (e.g., `` `5000` `` records) to prevent memory overflow
-- **Parallel Loading**: Concurrent batch insertion (backend dependent)
+> Unified interface for property graph databases.
---
-## Main Classes
+## Overview
-### Core Classes
+The **Graph Store Module** provides a single API for persisting and querying knowledge graphs in production graph databases.
-#### GraphStore
+Backends: **Neo4j**, **FalkorDB**, **Apache AGE** (PostgreSQL), **Amazon Neptune**, and in-memory **NetworkX** for development.
-The main facade for graph operations.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `connect(**options)` | Connect to the graph database |
-| `close()` | Close connection to the graph database |
-| `create_node(labels, properties, **options)` | Create a single node |
-| `create_nodes(nodes, **options)` | Create multiple nodes in batch |
-| `get_node(node_id, **options)` | Get a node by ID |
-| `get_nodes(labels, properties, limit, **options)` | Get nodes matching criteria |
-| `update_node(node_id, properties, merge, **options)` | Update node properties |
-| `delete_node(node_id, detach, **options)` | Delete a node |
-| `create_relationship(start_node_id, end_node_id, rel_type, properties, **options)` | Create a relationship |
-| `get_relationships(node_id, rel_type, direction, limit, **options)` | Get relationships |
-| `delete_relationship(rel_id, **options)` | Delete a relationship |
-| `execute_query(query, parameters, **options)` | Execute a Cypher/OpenCypher query |
-| `shortest_path(start_node_id, end_node_id, rel_type, max_depth, **options)` | Find shortest path between nodes |
-| `get_neighbors(node_id, rel_type, direction, depth, **options)` | Get neighboring nodes |
-| `get_stats()` | Get graph statistics |
-| `create_index(label, property_name, index_type, **options)` | Create an index |
-
-**Properties:**
-- `nodes` - Access to NodeManager
-- `relationships` - Access to RelationshipManager
-- `query_engine` - Access to QueryEngine
-- `analytics` - Access to GraphAnalytics
+---
-**Example:**
+## Basic Usage
```python
from semantica.graph_store import GraphStore
-store = GraphStore(backend="neo4j")
-store.connect()
-store.execute_query(
- "MATCH (n:Person {name: $name}) RETURN n",
- parameters={"name": "Alice"}
-)
-store.close()
-```
-
-#### GraphManager
-
-Manager for graph store operations. Provides access to node, relationship, query, and analytics managers.
-
-**Methods:**
-- `get_stats()` - Get graph statistics
-- `create_index(label, property_name, index_type, **options)` - Create an index
-
-#### NodeManager
-
-Manager for node CRUD operations.
-
-**Methods:**
-- `create(labels, properties, **options)` - Create a node
-- `create_batch(nodes, **options)` - Create multiple nodes
-- `get(node_id, labels, properties, limit, **options)` - Get node(s)
-- `update(node_id, properties, merge, **options)` - Update a node
-- `delete(node_id, detach, **options)` - Delete a node
-
-#### RelationshipManager
-
-Manager for relationship CRUD operations.
-
-**Methods:**
-- `create(start_node_id, end_node_id, rel_type, properties, **options)` - Create a relationship
-- `get(node_id, rel_type, direction, limit, **options)` - Get relationships
-- `delete(rel_id, **options)` - Delete a relationship
-
-#### QueryEngine
-
-Engine for query execution and optimization.
-
-**Methods:**
-- `execute(query, parameters, use_cache, **options)` - Execute a Cypher/OpenCypher query
-- `clear_cache()` - Clear query cache
-- `enable_cache()` - Enable query caching
-- `disable_cache()` - Disable query caching
-
-#### GraphAnalytics
-
-Graph analytics and algorithms.
+store = GraphStore(backend="neo4j", uri="bolt://localhost:7687", user="neo4j", password="password")
-**Methods:**
-- `shortest_path(start_node_id, end_node_id, rel_type, max_depth, **options)` - Find shortest path
-- `get_neighbors(node_id, rel_type, direction, depth, **options)` - Get neighboring nodes
-- `degree_centrality(labels, rel_type, direction, **options)` - Calculate degree centrality
-- `connected_components(labels, **options)` - Find connected components
+store.add_nodes(entities)
+store.add_edges(relationships)
-### Store Backends
-
-#### Neo4jStore
-
-Enterprise-grade Neo4j backend store.
-
-**Features:**
-- Bolt protocol support
-- Cluster awareness
-- APOC procedure integration
-- Multi-database support
-- Transaction support
-
-**Related Classes:**
-- `Neo4jDriver` - Neo4j driver wrapper
-- `Neo4jSession` - Session management wrapper
-- `Neo4jTransaction` - Transaction wrapper
-
-
-#### FalkorDBStore
-
-High-performance Redis-based FalkorDB backend store.
-
-**Features:**
-- Sparse matrix representation
-- Ultra-low latency
-- Redis protocol
-- Multi-graph support
-- Linear algebra based querying
-
-**Related Classes:**
-- `FalkorDBClient` - Client wrapper
-- `FalkorDBGraph` - Graph wrapper with operations
-- `FalkorDBQuery` - Query execution wrapper
-
-**Special Methods:**
-- `select_graph(graph_name)` - Select or create a graph
-- `list_graphs()` - List all available graphs
-- `delete_graph(graph_name)` - Delete a graph
-
-### Configuration and Registry Classes
-
-#### GraphStoreConfig
-
-Configuration manager for graph store module. Supports environment variables, config files (YAML, JSON, TOML), and programmatic configuration.
-
-**Methods:**
-- `get(key, default)` - Get configuration value
-- `set(key, value)` - Set configuration value
-- `update(config)` - Update configuration with dictionary
-- `get_method_config(method_name)` - Get method-specific configuration
-- `set_method_config(method_name, config)` - Set method-specific configuration
-- `get_all()` - Get all configuration
-- `get_neo4j_config()` - Get Neo4j-specific configuration
-- `get_falkordb_config()` - Get FalkorDB-specific configuration
-- `reset()` - Reset configuration to defaults
-
-**Global Instance:**
-- `graph_store_config` - Global configuration instance
-
-#### MethodRegistry
-
-Registry for custom graph store methods, enabling extensibility.
-
-**Methods:**
-- `register(task, method_name, method_func, **metadata)` - Register a method
-- `unregister(task, method_name)` - Unregister a method
-- `get(task, method_name)` - Get a registered method
-- `list_all(task)` - List all registered methods
-- `has(task, method_name)` - Check if a method is registered
-- `get_metadata(task, method_name)` - Get metadata for a registered method
-
-**Supported Task Types:**
-- `node` - Node CRUD methods
-- `relationship` - Relationship CRUD methods
-- `query` - Query execution methods
-- `traversal` - Graph traversal methods
-- `analytics` - Graph analytics methods
-- `bulk` - Bulk operation methods
-
-**Global Instance:**
-- `method_registry` - Global method registry instance
+results = store.query("MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 10")
+```
---
-## Convenience Functions
-
-The module provides convenience functions for common graph operations. These functions use a global GraphStore instance and support method registration for extensibility.
-
-### Node Operations
-
-| Function | Description |
-|----------|-------------|
-| `create_node(labels, properties, method, **options)` | Create a single node |
-| `create_nodes(nodes, method, **options)` | Create multiple nodes in batch |
-| `get_nodes(labels, properties, limit, method, **options)` | Get nodes matching criteria |
-| `update_node(node_id, properties, merge, method, **options)` | Update node properties |
-| `delete_node(node_id, detach, method, **options)` | Delete a node |
-
-### Relationship Operations
-
-| Function | Description |
-|----------|-------------|
-| `create_relationship(start_id, end_id, rel_type, properties, method, **options)` | Create a relationship |
-| `create_relationships(relationships, method, **options)` | Create multiple relationships in batch |
-| `get_relationships(node_id, rel_type, direction, limit, method, **options)` | Get relationships matching criteria |
-| `update_relationship(rel_id, properties, method, **options)` | Update relationship properties |
-| `delete_relationship(rel_id, method, **options)` | Delete a relationship |
-
-### Query Operations
+## Backends
+
+<Tabs>
+ <Tab title="Neo4j">
+ ```python
+ store = GraphStore(
+ backend="neo4j",
+ uri="bolt://localhost:7687",
+ user="neo4j",
+ password="password",
+ database="neo4j" # optional, default database
+ )
+ ```
+ </Tab>
+ <Tab title="FalkorDB">
+ ```python
+ store = GraphStore(
+ backend="falkordb",
+ host="localhost",
+ port=6379,
+ graph_name="semantica"
+ )
+ ```
+ </Tab>
+ <Tab title="Apache AGE">
+ ```python
+ store = GraphStore(
+ backend="apache_age",
+ connection_string="postgresql://user:pass@localhost/graphdb",
+ graph_name="semantica"
+ )
+ ```
+ See the [Apache AGE Guide](../graph_stores/apache_age) for setup.
+ </Tab>
+ <Tab title="In-Memory">
+ ```python
+ store = GraphStore(backend="networkx")
+ ```
+ For development and testing only β€” data is not persisted.
+ </Tab>
+</Tabs>
-| Function | Description |
-|----------|-------------|
-| `execute_query(query, parameters, method, **options)` | Execute a Cypher/OpenCypher query |
-
-### Analytics Operations
-
-| Function | Description |
-|----------|-------------|
-| `shortest_path(start_node_id, end_node_id, rel_type, max_depth, method, **options)` | Find shortest path between nodes |
-| `get_neighbors(node_id, rel_type, direction, depth, method, **options)` | Get neighboring nodes |
-| `run_analytics(algorithm, method, **options)` | Run graph analytics algorithm |
-
-### Utility Functions
-
-| Function | Description |
-|----------|-------------|
-| `get_graph_store_method(task, method_name)` | Get graph store method by task and name |
-| `list_available_methods(task)` | List all available graph store methods |
+---
-**Example:**
+## Querying
```python
-from semantica.graph_store import (
- create_node,
- create_nodes,
- create_relationship,
- execute_query,
- shortest_path,
- get_neighbors,
- run_analytics
+# Cypher (Neo4j, FalkorDB)
+results = store.query(
+ "MATCH (p:Person)-[:WORKS_FOR]->(o:Organization) WHERE o.name = $org RETURN p",
+ parameters={"org": "Apple Inc."}
)
-# Quick node creation
-alice = create_node(["Person"], {"name": "Alice", "age": 30})
-bob = create_node(["Person"], {"name": "Bob", "age": 25})
-
-# Batch node creation
-people = create_nodes([
- {"labels": ["Person"], "properties": {"name": "Charlie"}},
- {"labels": ["Person"], "properties": {"name": "Diana"}}
-])
-
-# Create relationship
-rel = create_relationship(
- start_id=alice["id"],
- end_id=bob["id"],
- rel_type="KNOWS",
- properties={"since": 2020}
-)
-
-# Quick query
-results = execute_query("MATCH (n:Person) RETURN count(n) as count")
-
-# Find shortest path
-path = shortest_path(
- start_node_id=alice["id"],
- end_node_id=bob["id"],
- max_depth=5
-)
-
-# Get neighbors
-neighbors = get_neighbors(node_id=alice["id"], depth=2)
-
-# Run analytics
-centrality = run_analytics(
- algorithm="degree_centrality",
- labels=["Person"]
+# Path traversal
+paths = store.find_paths(
+ start_node="steve_jobs",
+ end_node="apple_inc",
+ max_hops=3,
+ relationship_types=["FOUNDED", "WORKED_AT"]
)
```
---
-## Configuration
+## Graph Operations
+
+```python
+# Add a single node
+store.add_node("apple_inc", node_type="Organization", properties={"founded": 1976})
-### Environment Variables
+# Add a relationship
+store.add_edge("steve_jobs", "apple_inc", "FOUNDED", properties={"year": 1976})
-```bash
-export GRAPH_STORE_BACKEND=neo4j
-export NEO4J_URI=bolt://localhost:7687
-export NEO4J_USER=neo4j
-export NEO4J_PASSWORD=password
-```
+# Bulk operations
+store.add_nodes_bulk(entities, batch_size=1000)
+store.add_edges_bulk(relationships, batch_size=1000)
-### YAML Configuration
+# Delete
+store.delete_node("node_id")
+store.delete_edge("edge_id")
-```yaml
-graph_store:
- backend: neo4j
-
- neo4j:
- uri: bolt://localhost:7687
- pool_size: 50
-
+# Get neighbors
+neighbors = store.get_neighbors("apple_inc", relationship_type="HAS_EMPLOYEE", direction="in")
```
---
-## Integration Examples
-
-### Hybrid Search (Vector + Graph)
+## Schema Management
```python
-from semantica.graph_store import GraphStore
-from semantica.vector_store import VectorStore
-
-# 1. Find relevant nodes via Vector Search
-vector_store = VectorStore()
-results = vector_store.search(query_vec, k=5)
-node_ids = [r.metadata['node_id'] for r in results]
-
-# 2. Expand context via Graph Traversal
-graph_store = GraphStore()
-query = """
-MATCH (n)-[r]-(m)
-WHERE elementId(n) IN $ids
-RETURN n, r, m
-"""
-subgraph = graph_store.execute_query(query, parameters={"ids": node_ids})
-```
+# Create indexes for performance
+store.create_index(label="Person", property="name")
+store.create_constraint(label="Organization", property="id", constraint_type="unique")
----
-
-## Best Practices
-
-1. **Use Parameters**: Always use parameters in Cypher queries (`$name`) instead of string concatenation to prevent injection and improve caching.
-2. **Batch Writes**: Use `create_nodes` (plural) for bulk insertion instead of loop-inserting.
-3. **Create Indexes**: Ensure you have indexes on frequently queried properties (`id`, `name`).
-4. **Close Connections**: Use context managers (`with GraphStore() as store:`) or call `close()` to release resources.
+# Get schema
+schema = store.get_schema()
+```
---
## See Also
-- [Knowledge Graph Module](kg.md) - Logical layer above Graph Store
-- [Triplet Store Module](triplet_store.md) - RDF-based alternative
-- [Visualization Module](visualization.md) - Visualizing query results
-
-## Cookbook
-
-Interactive tutorials to learn graph storage:
-
-- **[Graph Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Graph_Store.ipynb)**: Persist knowledge graphs in Neo4j or FalkorDB
- - **Topics**: Neo4j, FalkorDB, Cypher, persistence, graph databases
- - **Difficulty**: Intermediate
- - **Use Cases**: Persistent storage, production deployments, graph database integration
+<CardGroup cols={2}>
+ <Card title="KG Module" icon="diagram-project" href="kg">
+ Build the graph before persisting it.
+ </Card>
+ <Card title="Apache AGE Guide" icon="database" href="../graph_stores/apache_age">
+ PostgreSQL-based graph storage setup.
+ </Card>
+ <Card title="Triplet Store" icon="table" href="triplet_store">
+ RDF triple store for semantic web.
+ </Card>
+ <Card title="Visualization" icon="chart-bar" href="visualization">
+ Visualize stored graphs.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/ingest.md b/docs/reference/ingest.md
index 57be5a0b..3d222e82 100644
--- a/docs/reference/ingest.md
+++ b/docs/reference/ingest.md
@@ -1,448 +1,199 @@
-# Ingest
-
-> **Universal data ingestion from files, XML, web, feeds, streams, repos, emails, and databases.**
-
---
-
-## 🎯 Overview
-
-The **Ingest Module** is the entry point for loading data into Semantica. It provides universal data ingestion from files, web content, feeds, streams, repositories, emails, databases, and more.
-
-### What is Data Ingestion?
-
-**Data ingestion** is the process of loading data from various sources into Semantica for processing. The ingest module handles:
-- **File Systems**: Local files, cloud storage (S3, GCS, Azure)
-- **Analytics Files**: Apache Parquet files and partitioned datasets
-- **Structured Files**: XML files with namespaces, attributes, XSD, and DTD validation
-- **Web Content**: Websites, RSS feeds, APIs
-- **Streams**: Real-time data from Kafka, RabbitMQ, etc.
-- **Databases**: SQL, NoSQL, and cloud data warehouses including Snowflake
-- **Repositories**: Git repositories (GitHub, GitLab)
-- **Email**: IMAP, POP3 servers
-- **MCP**: Model Context Protocol servers
-
-### Why Use the Ingest Module?
-
-- **Universal Support**: Handle multiple data formats and sources
-- **Automatic Detection**: Automatically detect file types and content
-- **Streaming Support**: Process real-time data streams
-- **Cloud Integration**: Direct support for cloud storage
-- **Rate Limiting**: Built-in rate limiting for web crawling
-- **Error Handling**: Robust error handling and retry logic
-
-### How It Works
-
-1. **Source Detection**: Automatically detect the type of data source
-2. **Connection**: Establish connection to the source (file system, web, database, etc.)
-3. **Loading**: Load data from the source
-4. **Format Detection**: Detect the format of the loaded data
-5. **Output**: Return data in a standardized format for processing
-
-<div class="grid cards" markdown>
-
-- :material-file-document-multiple:{ .lg .middle } **File Ingestion**
-
- ---
-
- Local and Cloud (S3/GCS/Azure) file processing with type detection
-
-- :material-web:{ .lg .middle } **Web Crawling**
-
- ---
-
- Scrape websites with rate limiting, robots.txt compliance, and JS rendering
-
-- :material-rss:{ .lg .middle } **Feed Monitoring**
-
- ---
-
- Consume RSS/Atom feeds with real-time update monitoring
-
-- :material-broadcast:{ .lg .middle } **Stream Processing**
-
- ---
-
- Ingest from Kafka, RabbitMQ, Kinesis, and Pulsar
-
-- :material-source-branch:{ .lg .middle } **Code Repos**
-
- ---
-
- Clone and analyze Git repositories (GitHub/GitLab)
-
-- :material-database:{ .lg .middle } **Databases**
-
- ---
-
- Ingest tables and query results from SQL, NoSQL, and cloud data warehouses including Snowflake
-
-- :material-table:{ .lg .middle } **Parquet Datasets**
-
- ---
-
- Read Parquet files, schemas, metadata, and Hive-style partitioned directories
-
-- :material-code-tags:{ .lg .middle } **XML Files**
-
- ---
-
- Parse XML into structured trees with namespaces, attributes, metadata, XSD, and DTD validation
-
-</div>
-
-!!! tip "When to Use"
- - **Data Onboarding**: The entry point for all external data into Semantica
- - **Crawling**: Building a dataset from the web
- - **Monitoring**: Listening to real-time data streams
- - **Migration**: Importing legacy data from databases
-
+title: "Ingest Module"
+description: "Universal data ingestion from files, Parquet, XML, web, feeds, streams, repositories, email, and databases."
+icon: "database"
---
-## βš™οΈ Algorithms Used
-
-### File Processing
-- **Magic Number Detection**: Identifying file types by binary signatures, not just extensions.
-- **Recursive Traversal**: Efficiently walking directory trees.
-
-### Web Ingestion
-- **Sitemap Parsing**: Discovering URLs via XML sitemaps.
-- **DOM Extraction**: Removing boilerplate (nav/ads) to extract main content.
-- **Politeness**: Respecting `robots.txt` and enforcing crawl delays.
-
-### Stream Processing
-- **Consumer Groups**: Managing offsets and scaling consumption (Kafka).
-- **Backpressure**: Handling high-velocity streams without crashing.
-
-### Repository Analysis
-- **AST Parsing**: Extracting code structure (classes/functions) without executing.
-- **Dependency Parsing**: Reading `requirements.txt`, `package.json`, etc.
+> Universal data ingestion β€” the entry point for loading data into Semantica.
---
-## Main Classes
-
-### FileIngestor
-
-Handles file systems and object storage.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_file(path)` | Process single file |
-| `ingest_directory(path)` | Process folder |
-
-### ParquetIngestor
-
-Handles Apache Parquet files and partitioned datasets.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_file(path, columns=None, limit=None)` | Read a Parquet file |
-| `ingest_directory(path, columns=None, limit=None)` | Read a partitioned Parquet directory |
-| `extract_schema(path)` | Extract column names, types, nullability, and schema metadata |
-| `extract_metadata(path)` | Extract row counts, row groups, compression, and partition info |
-
-### XMLIngestor
-
-Handles XML files and directories.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_file(path)` | Parse a single XML file into nested and flat structures |
-| `ingest_directory(path)` | Parse XML files from a folder |
-| `validate_file(path, schema_path=None, validate_dtd=False)` | Return XSD/DTD validation results |
-| `extract_metadata(path)` | Extract root, namespace, element, attribute, and DTD metadata |
-
-### WebIngestor
-
-Handles web content.
+## Overview
-**Methods:**
+The **Ingest Module** handles loading data from every common source into Semantica. All ingestors return a list of `DataSource` objects with content and metadata.
-| Method | Description |
-|--------|-------------|
-| `ingest_url(url)` | Scrape page |
-| `crawl(url, depth)` | Recursive crawl |
-
-### StreamIngestor
-
-Handles real-time data.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `consume(topic)` | Start consumption |
-
-### RepoIngestor
-
-Handles code repositories.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_repo(url)` | Clone and process |
-
-### FeedIngestor
-
-Handles RSS and Atom feeds.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_feed(url)` | Parse feed items |
-| `monitor(url)` | Watch for updates |
-
-### EmailIngestor
-
-Handles IMAP and POP3 servers.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `connect_imap(host)` | Connect to server |
-| `ingest_mailbox(name)` | Fetch emails |
-
-### DBIngestor
-
-Handles SQL and NoSQL databases including Snowflake.
+---
-**Methods:**
+## FileIngestor
-| Method | Description |
-|--------|-------------|
-| `ingest_database(conn)` | Export tables |
-| `execute_query(sql)` | Run custom SQL |
-| `connect_snowflake(account, user, password, warehouse)` | Connect to Snowflake |
-| `ingest_snowflake_table(table_name)` | Ingest Snowflake table |
-| `execute_snowflake_query(sql)` | Run Snowflake SQL |
+```python
+from semantica.ingest import FileIngestor
-**Supported Databases:**
-- **PostgreSQL**, **MySQL**, **SQLite**
-- **Microsoft SQL Server**, **Oracle**
-- **Snowflake** (Cloud Data Warehouse)
-- **MongoDB**, **Cassandra** (NoSQL)
-- **BigQuery**, **Redshift** (Cloud Data Warehouses)
+ingestor = FileIngestor()
-### MCPIngestor
+# Single file
+sources = ingestor.ingest("data/report.pdf")
-Handles Model Context Protocol servers.
+# Directory (recursive)
+sources = ingestor.ingest_directory("data/", recursive=True)
-**Methods:**
+# Glob pattern
+sources = ingestor.ingest("data/**/*.docx")
+```
-| Method | Description |
-|--------|-------------|
-| `connect(url)` | Connect to server |
-| `ingest_resources()` | Fetch resources |
-| `call_tool(name)` | Execute tool |
+Supported formats: PDF, DOCX, TXT, HTML, JSON, CSV, Excel (XLSX/XLS), PPTX, ZIP/TAR archives. File type is auto-detected.
---
-## Convenience Functions
+## ParquetIngestor (v0.5.0)
-```python
-from semantica.ingest import ingest
-
-# Auto-detect source type
-ingest("doc.pdf", source_type="file")
-ingest("events.parquet") # Auto-detects Parquet
-ingest("catalog.xml") # Auto-detects XML
-ingest("https://google.com", source_type="web")
-ingest("kafka://topic", source_type="stream")
-```
-
-### Parquet Dataset Ingestion
+PyArrow-based ingestion for Apache Parquet files.
```python
-from semantica.ingest import ParquetIngestor, ingest_parquet
+from semantica.ingest import ParquetIngestor
ingestor = ParquetIngestor()
-# Read selected columns from a local Parquet file
-events = ingestor.ingest_file(
- "events.parquet",
- columns=["event_id", "event_type"],
- limit=1000,
-)
+# Single file
+sources = ingestor.ingest("data/events.parquet")
-# Inspect schema and metadata without reading rows
-schema = ingestor.extract_schema("events.parquet")
-metadata = ingestor.extract_metadata("events.parquet")
+# Partitioned directory (Hive-style: year=2024/month=01/...)
+sources = ingestor.ingest("data/partitioned/")
-# Read a Hive-style partitioned directory such as country=US/year=2026/
-partitioned = ingest_parquet("./warehouse/events", method="directory")
+# Selective columns
+sources = ingestor.ingest("data/events.parquet", columns=["id", "text", "timestamp"])
```
-### XML File Ingestion
+---
-```python
-from semantica.ingest import XMLIngestor, ingest_xml
+## XMLIngestor (v0.5.0)
-ingestor = XMLIngestor()
+XXE-safe lxml-based ingestion with optional XSD/DTD validation.
-# Parse a local XML file into a nested tree and flat element list
-xml_data = ingestor.ingest_file("catalog.xml")
-
-print(xml_data.root_tag)
-print(xml_data.namespaces)
-print(xml_data.elements[0]["attributes"])
+```python
+from semantica.ingest import XMLIngestor
-# Validate with an XSD schema
-validated = ingest_xml("catalog.xml", schema_path="catalog.xsd")
-print(validated.validation["schema"]["valid"])
+# Basic ingestion
+ingestor = XMLIngestor()
+sources = ingestor.ingest("data/records.xml")
-# Validate an internal or local DTD declaration
-dtd_report = ingestor.validate_file("catalog.xml", validate_dtd=True)
+# With XSD validation
+ingestor = XMLIngestor(validate_xsd="schema.xsd")
+sources = ingestor.ingest("data/records/")
-# Extract metadata without returning the full tree
-metadata = ingest_xml("catalog.xml", method="metadata")
+# With DTD validation
+ingestor = XMLIngestor(validate_dtd=True)
+sources = ingestor.ingest("data/feed.xml")
```
----
+<Note>
+ The `XMLIngestor` uses lxml with XXE disabled (`resolve_entities=False`) to prevent XML External Entity injection attacks.
+</Note>
-## Configuration
+---
-### Environment Variables
+## WebIngestor
-```bash
-export INGEST_USER_AGENT="SemanticaBot/1.0"
-export AWS_ACCESS_KEY_ID=...
-export KAFKA_BOOTSTRAP_SERVERS=localhost:9092
-```
+```python
+from semantica.ingest import WebIngestor
-### YAML Configuration
+ingestor = WebIngestor(
+ rate_limit=1.0, # seconds between requests
+ respect_robots=True, # honor robots.txt
+ max_depth=2 # crawl depth
+)
-```yaml
-ingest:
- web:
- user_agent: "MyBot"
- rate_limit: 1.0 # seconds
+# Single URL
+sources = ingestor.ingest("https://example.com/about")
- files:
- max_size: 100MB
- allowed_extensions: [.pdf, .txt, .md]
+# Multiple URLs
+sources = ingestor.ingest_urls([
+ "https://example.com/page1",
+ "https://example.com/page2",
+])
```
---
-## Integration Examples
-
-### Continuous Feed Ingestion
+## FeedIngestor (RSS/Atom)
```python
from semantica.ingest import FeedIngestor
-from semantica.pipeline import Pipeline
-# 1. Setup Monitor
ingestor = FeedIngestor()
-pipeline = Pipeline()
+sources = ingestor.ingest("https://feeds.example.com/rss")
-def on_new_item(item):
- # 2. Trigger Pipeline on new content
- pipeline.run(item.content)
-
-# 3. Start Monitoring
-ingestor.monitor(
- "https://news.ycombinator.com/rss",
- callback=on_new_item,
- interval=300
-)
+# Monitor for updates
+ingestor.monitor("https://feeds.example.com/rss", interval=300, callback=process_new_items)
```
-### Snowflake Data Warehouse Integration
+---
+
+## DBIngestor (SQL / NoSQL)
```python
from semantica.ingest import DBIngestor
-# 1. Connect to Snowflake
-ingestor = DBIngestor()
-ingestor.connect_snowflake(
- account="your_account.snowflakecomputing.com",
- user="your_username",
- password="your_password",
- warehouse="ANALYTICS_WH",
- database="PRODUCTION_DB",
- schema="PUBLIC"
+# PostgreSQL
+ingestor = DBIngestor(
+ connection_string="postgresql://user:pass@localhost/db",
+ query="SELECT id, content, created_at FROM documents WHERE status='active'"
)
-
-# 2. Ingest entire table
-data = ingestor.ingest_snowflake_table("CUSTOMERS")
-
-# 3. Or run custom query
-results = ingestor.execute_snowflake_query("""
- SELECT
- CUSTOMER_ID,
- NAME,
- EMAIL,
- CREATED_AT
- FROM CUSTOMERS
- WHERE CREATED_AT > '2024-01-01'
-""")
-
-# 4. Process with pipeline
-for row in results:
- pipeline.process(row)
+sources = ingestor.ingest()
```
-!!! info "Comprehensive Snowflake Guide"
- For detailed Snowflake integration including authentication methods, advanced features, and best practices, see the **[Snowflake Integration Guide](../integrations/snowflake.md)**.
+---
-### Multi-Database Integration
+## SnowflakeIngestor
```python
-from semantica.ingest import DBIngestor
-
-ingestor = DBIngestor()
-
-# Connect to multiple databases
-connections = {
- "snowflake": ingestor.connect_snowflake(...),
- "postgres": ingestor.connect_database("postgresql://..."),
- "mysql": ingestor.connect_database("mysql://...")
-}
-
-# Ingest from all sources
-for name, conn in connections.items():
- data = ingestor.ingest_database(conn)
- print(f"Ingested {len(data)} records from {name}")
+from semantica.ingest import SnowflakeIngestor
+
+ingestor = SnowflakeIngestor(
+ account=os.getenv("SNOWFLAKE_ACCOUNT"),
+ user=os.getenv("SNOWFLAKE_USER"),
+ password=os.getenv("SNOWFLAKE_PASSWORD"),
+ warehouse="COMPUTE_WH",
+ database="ANALYTICS",
+ schema="PUBLIC"
+)
+sources = ingestor.ingest(query="SELECT * FROM documents")
```
---
-## Best Practices
+## Other Ingestors
-1. **Respect Rate Limits**: When crawling, always set a polite `rate_limit` to avoid getting banned.
-2. **Filter Content**: Use `allowed_extensions` or URL patterns to avoid ingesting junk data.
-3. **Handle Failures**: Stream ingestors should have error handlers for bad messages.
-4. **Use Credentials Securely**: Never hardcode API keys; use Environment Variables.
+| Class | Source |
+|-------|--------|
+| `StreamIngestor` | Kafka, RabbitMQ, Kinesis, Pulsar |
+| `RepoIngestor` | Git repositories (GitHub, GitLab) |
+| `EmailIngestor` | IMAP/POP3 servers |
+| `MCPIngestor` | Model Context Protocol servers |
+| `S3Ingestor` | AWS S3 buckets |
+| `GCSIngestor` | Google Cloud Storage |
---
-## See Also
+## DataSource Object
-- **[Snowflake Integration Guide](../integrations/snowflake.md)** - Comprehensive Snowflake integration with authentication, advanced features, and best practices
-- [Parse Module](parse.md) - Processes the raw data ingested here
-- [Split Module](split.md) - Chunks the ingested content
-- [Utils Module](utils.md) - Validation helpers
+All ingestors return a list of `DataSource` objects:
-## Cookbook
+```python
+@dataclass
+class DataSource:
+ content: str # raw text content
+ source_id: str # unique identifier
+ source_type: str # "file", "web", "database", etc.
+ metadata: Dict # title, author, url, date, etc.
+ raw_bytes: Optional[bytes]
+```
-Interactive tutorials to learn data ingestion:
+---
-- **[Data Ingestion](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/02_Data_Ingestion.ipynb)**: Comprehensive guide to data ingestion from multiple sources
- - **Topics**: File ingestion, web scraping, database integration, streams, feeds, repositories, email, MCP
- - **Difficulty**: Beginner
- - **Use Cases**: Loading data from various sources, understanding ingestion capabilities
+## See Also
-- **[Multi-Source Data Integration](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)**: Merge data from disparate sources into a unified graph
- - **Topics**: Entity resolution, merging, fusion, multi-source integration
- - **Difficulty**: Advanced
- - **Use Cases**: Combining data from multiple sources, data fusion
+<CardGroup cols={2}>
+ <Card title="Parse" icon="file-lines" href="parse">
+ Parse raw sources into structured text.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Orchestrate ingest as part of a pipeline.
+ </Card>
+ <Card title="Snowflake Integration" icon="snowflake" href="../integrations/snowflake">
+ Snowflake-specific setup guide.
+ </Card>
+ <Card title="Provenance" icon="link" href="provenance">
+ Track lineage from ingest to inference.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/kg.md b/docs/reference/kg.md
index 897c6e9c..04200630 100644
--- a/docs/reference/kg.md
+++ b/docs/reference/kg.md
@@ -1,286 +1,113 @@
-# Knowledge Graph
-
-> **High-level KG construction, management, and analysis system.**
-
+---
+title: "Knowledge Graph Module"
+description: "Graph construction, temporal models, analytics, and distance intelligence."
+icon: "diagram-project"
---
-## 🎯 Overview
-
-The **Knowledge Graph (KG) Module** is the core module for building, managing, and analyzing knowledge graphs. It transforms extracted entities and relationships into structured, queryable knowledge graphs.
-
-### What is a Knowledge Graph?
-
-A **knowledge graph** is a structured representation of information where:
-- **Nodes** represent entities (people, organizations, concepts, etc.)
-- **Edges** represent relationships between entities
-- **Properties** store additional information about nodes and edges
-
-Knowledge graphs enable semantic queries, relationship traversal, and complex reasoning that traditional databases cannot handle.
-
-### Why Use the KG Module?
-
-- **Structured Knowledge**: Transform unstructured data into structured, queryable graphs
-- **Entity Resolution**: Automatically merge duplicate entities using fuzzy matching
-- **Temporal Support**: Track how knowledge changes over time
-- **Graph Analytics**: Analyze graph structure, importance, and communities
-- **Provenance Tracking**: Know where every piece of information came from
-
-### How It Works
-
-1. **Input**: Entities and relationships from semantic extraction
-2. **Entity Resolution**: Merge similar entities to avoid duplicates
-3. **Graph Construction**: Build nodes and edges from entities and relationships
-4. **Enrichment**: Add temporal information, provenance, and metadata
-5. **Analysis**: Perform graph analytics (centrality, communities, etc.)
-
-<div class="grid cards" markdown>
-
-- :material-graph-outline:{ .lg .middle } **KG Construction**
-
- ---
-
- Build graphs from entities and relationships with automatic merging
-
-- :material-clock-time-four-outline:{ .lg .middle } **Temporal Graphs**
-
- ---
-
- Time-aware edges (`valid_from`, `valid_until`) and temporal queries
-
-- :material-account-multiple-check:{ .lg .middle } **Entity Resolution**
-
- ---
-
- Resolve entities using fuzzy matching and semantic similarity
-
-- :material-chart-network:{ .lg .middle } **Graph Analytics**
-
- ---
-
- Centrality, Community Detection, and Connectivity analysis
-
-- :material-history:{ .lg .middle } **Provenance**
-
- ---
-
- Track the source and lineage of every node and edge
-
-</div>
+> High-level KG construction, management, and analysis system.
-!!! tip "When to Use"
- - **KG Building**: The primary module for assembling a KG from extracted data
- - **Entity Resolution**: Resolving and merging similar entities
- - **Analysis**: Understanding the structure and importance of nodes
- - **Time-Series**: Modeling how the graph evolves over time
+---
-!!! note "Related Modules"
- - **Conflict Detection**: Use `semantica.conflicts` module for conflict detection and resolution
- - **Deduplication**: Use `semantica.deduplication` module for advanced deduplication
+## Overview
+
+The **Knowledge Graph (KG) Module** transforms extracted entities and relationships into structured, queryable knowledge graphs. It includes temporal support, graph analytics, node embeddings, and distance intelligence (v0.5.0).
+
+<CardGroup cols={2}>
+ <Card title="KG Construction" icon="hammer">
+ Build graphs from entities and relationships with automatic entity merging.
+ </Card>
+ <Card title="Temporal Graphs" icon="clock">
+ Time-aware edges (`valid_from`, `valid_until`) and point-in-time queries (v0.4.0).
+ </Card>
+ <Card title="Graph Analytics" icon="chart-bar">
+ Centrality, community detection, and connectivity analysis.
+ </Card>
+ <Card title="Distance Intelligence" icon="compass">
+ Semantic neighborhoods, distance matrices, and ego-mode exploration (v0.5.0).
+ </Card>
+ <Card title="Provenance" icon="link">
+ Track the source and lineage of every node and edge.
+ </Card>
+ <Card title="Entity Resolution" icon="user-check">
+ Resolve and merge similar entities using fuzzy matching and semantic similarity.
+ </Card>
+</CardGroup>
+
+<Tip>
+ **Related modules:** Use `semantica.conflicts` for conflict detection and `semantica.deduplication` for advanced entity resolution.
+</Tip>
---
-## βš™οΈ Algorithms & Components
-
-### πŸ—οΈ Graph Construction
+## GraphBuilder
-#### GraphBuilder
Constructs knowledge graphs from raw entities and relationships.
-**Key Features:**
-- Entity and relationship creation
-- Automatic entity resolution and merging
-- Provenance tracking for all operations
-- Temporal graph support
-- Multi-source data integration
-
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `build(sources)` | Build graph from multiple data sources |
-| `build_single_source(data)` | Build graph from single data source |
-| `merge_entities()` | Merge duplicate entities during building |
-
-**Example:**
```python
from semantica.kg import GraphBuilder
builder = GraphBuilder(merge_entities=True)
-kg = builder.build([source1, source2])
+kg = builder.build(entities=entities, relationships=relationships)
```
-### πŸ” Node Embeddings
-
-#### NodeEmbedder
-Generates node embeddings for structural similarity analysis.
-
-**Supported Algorithms:**
-- **Node2Vec**: Biased random walk based embeddings (high quality)
-- **DeepWalk**: Unbiased random walk based embeddings (simpler, faster)
-- **Word2Vec**: Neural network training on graph walks
-
-**Key Features:**
-- Configurable embedding dimensions and walk parameters
-- Biased and unbiased random walk generation
-- Embedding storage as node properties
-- Similarity search based on learned embeddings
-
-**Methods:**
| Method | Description |
|--------|-------------|
-| `compute_embeddings()` | Main interface for embedding computation |
-| `find_similar_nodes()` | Find structurally similar nodes |
-| `store_embeddings()` | Store embeddings as node properties |
-
-**Example:**
-```python
-from semantica.kg import NodeEmbedder
-
-embedder = NodeEmbedder(method="node2vec", embedding_dimension=128)
-embeddings = embedder.compute_embeddings(graph_store, ["Entity"], ["RELATED_TO"])
-similar_nodes = embedder.find_similar_nodes(graph_store, "entity_123", top_k=10)
-```
+| `build(sources)` | Build graph from multiple data sources |
+| `build_single_source(data)` | Build graph from single data source |
+| `merge_entities()` | Merge duplicate entities during building |
-### πŸ“ Similarity Analysis
+---
-#### SimilarityCalculator
-Computes similarity between node embeddings and vectors.
+## Temporal Knowledge Graphs (v0.4.0)
-**Supported Algorithms:**
-- **Cosine Similarity**: Measures angular similarity between vectors
-- **Euclidean Distance**: Calculates straight-line distance
-- **Manhattan Distance**: Computes L1 distance (sum of absolute differences)
-- **Pearson Correlation**: Measures linear correlation
-- **Batch Similarity**: Efficient computation for multiple embeddings
-- **Pairwise Similarity**: All-vs-all similarity matrix
+```python
+from semantica.kg import TemporalKnowledgeGraph, TemporalGraphQuery
+from datetime import datetime
-**Key Features:**
-- Individual and batch similarity calculations
-- Multiple similarity metrics
-- Performance optimization with sparse matrices
-- Top-k most similar node finding
+# Build temporal graph
+tkg = TemporalKnowledgeGraph()
+tkg.add_node("ceo_role", valid_from=datetime(2020, 1, 1), valid_until=datetime(2023, 6, 1))
+tkg.add_edge("alice", "acme_corp", "ceo_of",
+ valid_from=datetime(2020, 1, 1), valid_until=datetime(2023, 6, 1))
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `cosine_similarity()` | Calculate cosine similarity |
-| `euclidean_distance()` | Calculate Euclidean distance |
-| `manhattan_distance()` | Calculate Manhattan distance |
-| `correlation_similarity()` | Calculate Pearson correlation |
-| `batch_similarity()` | Batch similarity computation |
-| `find_most_similar()` | Find top-k similar nodes |
-
-**Example:**
-```python
-from semantica.kg import SimilarityCalculator
+# Point-in-time query
+snapshot = tkg.at(datetime(2021, 6, 15))
-calc = SimilarityCalculator()
-similarity = calc.cosine_similarity(embedding1, embedding2)
-similarities = calc.batch_similarity(embeddings, query_embedding)
-most_similar = calc.find_most_similar(embeddings, query_embedding, top_k=5)
+# Query evolution
+query = TemporalGraphQuery(tkg)
+snapshot_2020 = query.at_time("2020-01-01")
+snapshot_2023 = query.at_time("2023-01-01")
+diff = snapshot_2023.minus(snapshot_2020)
+print(f"New nodes since 2020: {len(diff.nodes)}")
```
-### πŸ›€οΈ Path Finding
+Supports all 13 Allen interval algebra relations (before, after, meets, overlaps, during, starts, finishes, equals, and their inverses). OWL-Time export available.
-#### PathFinder
-Discovers paths and routes in knowledge graphs.
-
-**Supported Algorithms:**
-- **Dijkstra's Algorithm**: Weighted shortest path finding
-- **A* Search**: Heuristic-based path finding
-- **BFS Shortest Path**: Unweighted shortest path finding
-- **All Shortest Paths**: Multiple path discovery
-- **K-Shortest Paths**: Top-k alternative paths
+---
-**Key Features:**
-- Weighted and unweighted graph support
-- Custom heuristic functions for A*
-- Multiple path discovery and ranking
-- Efficient path reconstruction
+## Distance Intelligence (v0.5.0)
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `dijkstra_shortest_path()` | Find weighted shortest path |
-| `a_star_search()` | Find path using heuristics |
-| `bfs_shortest_path()` | Find unweighted shortest path |
-| `all_shortest_paths()` | Find all shortest paths |
-| `find_k_shortest_paths()` | Find top-k alternative paths |
-| `path_length()` | Calculate total path distance |
-
-**Example:**
```python
-from semantica.kg import PathFinder
+from semantica.kg import DistanceCalculator
-finder = PathFinder()
-path = finder.dijkstra_shortest_path(graph, "node_a", "node_b")
-paths = finder.all_shortest_paths(graph, "source_node", "target_node")
-k_paths = finder.find_k_shortest_paths(graph, "source", "target", k=3)
-```
-
-### πŸ”— Link Prediction
+calc = DistanceCalculator(kg)
-#### LinkPredictor
-Predicts potential connections and missing relationships.
+# Semantic neighborhood of a node
+neighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)
-**Supported Algorithms:**
-- **Preferential Attachment**: Degree product scoring
-- **Common Neighbors**: Count of shared neighbors
-- **Jaccard Coefficient**: Jaccard similarity of neighbor sets
-- **Adamic-Adar Index**: Weighted neighbor count based on degree
-- **Resource Allocation**: Resource transfer probability
+# NΓ—N distance matrix
+matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])
-**Key Features:**
-- Multiple link prediction algorithms
-- Batch processing for multiple predictions
-- Top-k link prediction for targeted analysis
-- Scalable implementations for large graphs
-
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `predict_links()` | Predict potential links |
-| `score_link()` | Calculate link prediction score |
-| `predict_top_links()` | Find top-k links for specific node |
-| `batch_score_links()` | Batch scoring for multiple pairs |
-
-**Example:**
-```python
-from semantica.kg import LinkPredictor
-
-predictor = LinkPredictor(method="preferential_attachment")
-links = predictor.predict_links(graph, top_k=20)
-score = predictor.score_link(graph, "node_a", "node_b")
+# Distance band classification: "near" | "mid" | "far"
+bands = calc.classify_bands(neighborhood)
```
-### 🎯 Centrality Analysis
-
-#### CentralityCalculator
-Identifies important and influential nodes in graphs.
+---
-**Supported Algorithms:**
-- **Degree Centrality**: Measures node connectivity
-- **Betweenness Centrality**: Measures importance as bridge
-- **Closeness Centrality**: Measures average distance to all nodes
-- **Eigenvector Centrality**: Measures influence based on connections
-- **PageRank**: Importance based on link structure
+## Graph Analytics
-**Key Features:**
-- Multiple centrality algorithms
-- Centrality ranking and statistics
-- Configurable parameters for iterative algorithms
-- Batch calculation of all measures
+### Centrality Analysis
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `calculate_degree_centrality()` | Calculate degree-based importance |
-| `calculate_betweenness_centrality()` | Calculate bridge-based importance |
-| `calculate_closeness_centrality()` | Calculate distance-based importance |
-| `calculate_eigenvector_centrality()` | Calculate influence-based importance |
-| `calculate_pagerank()` | Calculate PageRank scores |
-| `calculate_all_centrality()` | Calculate all centrality measures |
-
-**Example:**
```python
from semantica.kg import CentralityCalculator
@@ -290,33 +117,17 @@ pagerank_scores = calculator.calculate_pagerank(graph, damping_factor=0.85)
top_nodes = calculator.get_top_nodes(centrality, top_k=10)
```
-### πŸ‘₯ Community Detection
-
-#### CommunityDetector
-Identifies clusters and communities in graphs.
-
-**Supported Algorithms:**
-- **Louvain**: Modularity optimization with hierarchical clustering
-- **Leiden**: Improved version of Louvain with guaranteed connectivity
-- **Label Propagation**: Fast, semi-supervised detection
-- **K-Clique Communities**: Overlapping community detection
+| Method | Algorithm |
+|--------|-----------|
+| `calculate_degree_centrality()` | Degree-based importance |
+| `calculate_betweenness_centrality()` | Bridge-based importance |
+| `calculate_closeness_centrality()` | Distance-based importance |
+| `calculate_eigenvector_centrality()` | Influence-based importance |
+| `calculate_pagerank()` | PageRank scores |
+| `calculate_all_centrality()` | All measures at once |
-**Key Features:**
-- Multiple community detection algorithms
-- Community quality metrics (modularity, size distribution)
-- Overlapping and non-overlapping communities
-- Configurable resolution parameters
+### Community Detection
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `detect_communities()` | Main interface for community detection |
-| `detect_communities_louvain()` | Louvain modularity optimization |
-| `detect_communities_leiden()` | Leiden algorithm with refinement |
-| `detect_communities_label_propagation()` | Fast label propagation |
-| `calculate_community_metrics()` | Community quality assessment |
-
-**Example:**
```python
from semantica.kg import CommunityDetector
@@ -326,134 +137,69 @@ metrics = detector.calculate_community_metrics(graph, communities)
leiden_communities = detector.detect_communities_leiden(graph, resolution=1.2)
```
-### πŸ”Œ Connectivity Analysis
+Algorithms: Louvain, Leiden, Label Propagation, K-Clique Communities.
-#### ConnectivityAnalyzer
-Analyzes graph connectivity and structural properties.
+### Path Finding
-**Supported Algorithms:**
-- **Connectivity Analysis**: Determine if graph is connected
-- **Connected Components**: Find all connected components using DFS
-- **Shortest Paths**: BFS-based shortest path finding
-- **Bridge Identification**: Find critical edges
-- **Graph Density**: Measure connectivity and sparsity
-- **Degree Statistics**: Analyze node degree distributions
+```python
+from semantica.kg import PathFinder
+
+finder = PathFinder()
+path = finder.dijkstra_shortest_path(graph, "node_a", "node_b")
+paths = finder.all_shortest_paths(graph, "source", "target")
+k_paths = finder.find_k_shortest_paths(graph, "source", "target", k=3)
+```
-**Key Features:**
-- Comprehensive connectivity analysis
-- Bridge edge identification for network robustness
-- Graph structure classification
-- NetworkX integration with fallback implementations
+Algorithms: Dijkstra, A\*, BFS, All Shortest Paths, K-Shortest Paths.
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `analyze_connectivity()` | Main connectivity analysis |
-| `find_connected_components()` | Detect connected components |
-| `calculate_shortest_paths()` | Find shortest paths |
-| `identify_bridges()` | Find critical bridge edges |
-| `calculate_graph_density()` | Compute density metrics |
+### Link Prediction
-**Example:**
```python
-from semantica.kg import ConnectivityAnalyzer
+from semantica.kg import LinkPredictor
-analyzer = ConnectivityAnalyzer()
-connectivity = analyzer.analyze_connectivity(graph)
-components = analyzer.find_connected_components(graph)
-bridges = analyzer.identify_bridges(graph)
+predictor = LinkPredictor(method="preferential_attachment")
+links = predictor.predict_links(graph, top_k=20)
+score = predictor.score_link(graph, "node_a", "node_b")
```
-### πŸ“ Provenance Tracking
-
-#### GraphBuilderWithProvenance & AlgorithmTrackerWithProvenance
-Tracks the origin and execution history of all KG operations.
+Algorithms: Preferential Attachment, Common Neighbors, Jaccard, Adamic-Adar, Resource Allocation.
-**Key Features:**
-- Complete provenance tracking for graph construction
-- Algorithm execution tracking with parameters
-- Execution IDs for workflow linking
-- Metadata and timestamp tracking
-- Error handling and graceful degradation
+### Node Embeddings
-**Methods:**
-| Method | Description |
-|--------|-------------|
-| `track_embedding_computation()` | Track embedding algorithm executions |
-| `track_similarity_calculation()` | Track similarity analysis |
-| `track_link_prediction()` | Track link prediction executions |
-| `track_centrality_calculation()` | Track centrality calculations |
-| `track_community_detection()` | Track community detection |
-
-**Example:**
```python
-from semantica.kg import GraphBuilderWithProvenance, AlgorithmTrackerWithProvenance
-
-# Graph building with provenance
-builder = GraphBuilderWithProvenance(provenance=True)
-result = builder.build_single_source(graph_data)
-
-# Algorithm tracking with provenance
-tracker = AlgorithmTrackerWithProvenance(provenance=True)
-embed_id = tracker.track_embedding_computation(
- graph=networkx_graph,
- algorithm='node2vec',
- embeddings=computed_embeddings,
- parameters={'embedding_dimension': 128}
-)
+from semantica.kg import NodeEmbedder
+
+embedder = NodeEmbedder(method="node2vec", embedding_dimension=128)
+embeddings = embedder.compute_embeddings(graph_store, ["Entity"], ["RELATED_TO"])
+similar_nodes = embedder.find_similar_nodes(graph_store, "entity_123", top_k=10)
```
+Algorithms: Node2Vec, DeepWalk, Word2Vec.
+
---
-## πŸ“Š Algorithm Categories Summary
+## Algorithm Summary
| Category | Algorithms | Use Cases |
|----------|------------|-----------|
-| **Node Embeddings** | Node2Vec, DeepWalk, Word2Vec | Structural similarity, node representation |
-| **Similarity Analysis** | Cosine, Euclidean, Manhattan, Correlation | Node similarity, recommendation systems |
-| **Path Finding** | Dijkstra, A*, BFS, K-Shortest | Route planning, network analysis |
-| **Link Prediction** | Preferential Attachment, Jaccard, Adamic-Adar | Network completion, recommendation |
-| **Centrality Analysis** | Degree, Betweenness, Closeness, PageRank | Influence analysis, importance ranking |
-| **Community Detection** | Louvain, Leiden, Label Propagation | Social analysis, clustering |
-| **Connectivity** | Components, Bridges, Density | Network robustness, structure analysis |
-
----
-
-## Using Classes
-
-```python
-from semantica.kg import GraphBuilder, GraphAnalyzer
-
-# Build using GraphBuilder
-builder = GraphBuilder(merge_entities=True)
-kg = builder.build(sources)
-
-# Analyze
-analyzer = GraphAnalyzer()
-stats = analyzer.analyze_graph(kg)
-print(f"Communities: {stats.get('communities', [])}")
-```
+| Node Embeddings | Node2Vec, DeepWalk, Word2Vec | Structural similarity, node representation |
+| Similarity Analysis | Cosine, Euclidean, Manhattan, Correlation | Node similarity, recommendation |
+| Path Finding | Dijkstra, A\*, BFS, K-Shortest | Route planning, network analysis |
+| Link Prediction | Preferential Attachment, Jaccard, Adamic-Adar | Network completion |
+| Centrality | Degree, Betweenness, Closeness, PageRank | Influence analysis |
+| Community Detection | Louvain, Leiden, Label Propagation | Social analysis, clustering |
+| Connectivity | Components, Bridges, Density | Network robustness |
---
## Configuration
-### Environment Variables
-
-```bash
-export KG_MERGE_STRATEGY=fuzzy
-export KG_TEMPORAL_GRANULARITY=day
-export KG_RESOLUTION_STRATEGY=fuzzy
-```
-
-### YAML Configuration
-
```yaml
kg:
resolution:
threshold: 0.9
strategy: semantic
-
+
temporal:
enabled: true
default_validity: infinite
@@ -461,73 +207,27 @@ kg:
---
-## Integration Examples
-
-### Temporal Analysis Pipeline
-
-```python
-from semantica.kg import GraphBuilder, TemporalGraphQuery
-
-# 1. Build Temporal Graph
-builder = GraphBuilder(enable_temporal=True)
-kg = builder.build(temporal_data)
-
-# 2. Query Evolution
-query = TemporalGraphQuery(kg)
-snapshot_2020 = query.at_time("2020-01-01")
-snapshot_2023 = query.at_time("2023-01-01")
-
-# 3. Compare
-diff = snapshot_2023.minus(snapshot_2020)
-print(f"New nodes since 2020: {len(diff.nodes)}")
-```
-
----
-
-## Best Practices
-
-1. **Clean Data First**: Use `EntityResolver` to resolve similar entities and prevent "entity explosion" (too many duplicate nodes).
-2. **Use Provenance**: Always track sources (`track_history=True`) to debug where bad data came from.
-3. **Temporal Granularity**: Choose the right granularity (Day vs Second) to balance performance and precision.
-4. **Deduplication**: Use `semantica.deduplication` module for advanced deduplication needs.
-5. **Conflict Resolution**: Use `semantica.conflicts` module for conflict detection and resolution.
-
----
-
## See Also
-- [Graph Store Module](graph_store.md) - Persistence layer
-- [Semantic Extract Module](semantic_extract.md) - Data source
-- [Visualization Module](visualization.md) - Visualizing the KG
-- [Conflicts Module](conflicts.md) - Conflict detection and resolution
-
-## Cookbook
-
-Interactive tutorials to learn knowledge graph construction and analysis:
-
-- **[Building Knowledge Graphs](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb)**: Learn the fundamentals of building knowledge graphs
- - **Topics**: Graph construction, entity resolution, relationship mapping
- - **Difficulty**: Beginner
- - **Use Cases**: Understanding graph construction basics
-
-- **[Your First Knowledge Graph](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb)**: Build your first knowledge graph from scratch
- - **Topics**: Entity extraction, relationship extraction, graph construction, visualization
- - **Difficulty**: Beginner
- - **Use Cases**: First-time users, quick start
-
-- **[Graph Analytics](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/10_Graph_Analytics.ipynb)**: Analyze knowledge graphs with centrality and community detection
- - **Topics**: Centrality measures, community detection, graph metrics
- - **Difficulty**: Intermediate
- - **Use Cases**: Understanding graph structure, finding important nodes
-
-- **[Advanced Graph Analytics](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb)**: Advanced graph analysis techniques
- - **Topics**: PageRank, Louvain algorithm, shortest path, graph mining
- - **Difficulty**: Advanced
- - **Use Cases**: Complex graph analysis, research applications
-
-- **[Temporal Knowledge Graphs](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/10_Temporal_Knowledge_Graphs.ipynb)**: Model and query data that changes over time
- - **Topics**: Time series, temporal logic, temporal queries, graph evolution
- - **Difficulty**: Advanced
- - **Use Cases**: Tracking changes over time, temporal reasoning
-
-- **[Deduplication Module](deduplication.md)**: Advanced deduplication techniques for entity resolution
+<CardGroup cols={2}>
+ <Card title="Graph Store" icon="server" href="graph_store">
+ Persistence layer (Neo4j, FalkorDB, Apache AGE).
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Data source for entities and relationships.
+ </Card>
+ <Card title="Visualization" icon="chart-bar" href="visualization">
+ Visualize knowledge graphs interactively.
+ </Card>
+ <Card title="Conflicts" icon="triangle-exclamation" href="conflicts">
+ Conflict detection and resolution.
+ </Card>
+</CardGroup>
+
+### Cookbook
+
+- [Building Knowledge Graphs](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) β€” fundamentals of KG construction Β· Beginner
+- [Your First Knowledge Graph](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb) β€” entity extraction to visualization Β· Beginner
+- [Graph Analytics](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/10_Graph_Analytics.ipynb) β€” centrality and community detection Β· Intermediate
+- [Advanced Graph Analytics](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb) β€” PageRank, Louvain, shortest path Β· Advanced
+- [Temporal Knowledge Graphs](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/10_Temporal_Knowledge_Graphs.ipynb) β€” temporal logic and graph evolution Β· Advanced
diff --git a/docs/reference/llms.md b/docs/reference/llms.md
index c5131e23..0a0e6a7f 100644
--- a/docs/reference/llms.md
+++ b/docs/reference/llms.md
@@ -1,330 +1,201 @@
-# LLM Providers Module
+---
+title: "LLMs Module"
+description: "Unified interface for Groq, OpenAI, Anthropic, Gemini, Ollama, DeepSeek, Novita AI, LiteLLM, and HuggingFace."
+icon: "microchip"
+---
-The `semantica.llms` module provides a unified interface for LLM providers, supporting Groq, OpenAI, HuggingFace, and LiteLLM (100+ LLMs) with clean imports and consistent API.
+The `semantica.llms` module provides a single consistent API across 8+ LLM providers. All providers are drop-in replacements for `llm_provider=` in extractors, reasoning engines, and agents.
-## Overview
-
-The **LLM Providers Module** provides a unified interface for Large Language Model (LLM) providers. It abstracts away provider-specific details, enabling you to switch between different LLM providers without changing your code.
-
-### What is the LLM Providers Module?
-
-The LLM Providers module provides:
-
-- **Unified LLM APIs**: Single interface for Groq, OpenAI, HuggingFace, and LiteLLM (100+ models)
-- **Easy Provider Switching**: Change providers without code changes
-- **Multiple Model Support**: Access to 100+ LLMs through LiteLLM
-- **GraphRAG Integration**: Seamless integration with GraphRAG reasoning features
-- **Structured Output**: Generate structured data with robust JSON parsing and automatic retries (3 attempts).
-
-### Why Use the LLM Providers Module?
-
-- **Flexibility**: Switch between providers based on cost, speed, or capability
-- **Consistency**: Same API regardless of provider
-- **Local Models**: Support for local HuggingFace models
-- **Fast Inference**: Groq for ultra-fast inference
-- **Enterprise Models**: Access to OpenAI, Anthropic, and other enterprise providers
-
-### How It Works
-
-The LLM Providers module follows a simple workflow:
-
-1. **Provider Selection**: Choose a provider (Groq, OpenAI, HuggingFace, LiteLLM)
-2. **Model Configuration**: Configure model name, API keys, and parameters
-3. **Text Generation**: Generate text using a consistent API
-4. **Structured Output**: Optionally generate structured data (JSON, entities, etc.)
-
-## Quick Start
-
-```python
-from semantica.llms import Groq, OpenAI, HuggingFaceLLM, LiteLLM
-import os
-
-# Groq - Fast inference
-groq = Groq(model="llama-3.1-8b-instant", api_key=os.getenv("GROQ_API_KEY"))
-response = groq.generate("What is AI?")
-
-# OpenAI
-openai = OpenAI(model="gpt-4", api_key=os.getenv("OPENAI_API_KEY"))
-response = openai.generate("What is AI?")
-
-# HuggingFace - Local models
-hf = HuggingFaceLLM(model_name="gpt2") # or model="gpt2"
-response = hf.generate("What is AI?")
-
-# LiteLLM - Unified interface to 100+ LLMs
-litellm = LiteLLM(model="openai/gpt-4o", api_key=os.getenv("OPENAI_API_KEY"))
-response = litellm.generate("What is AI?")
-```
+---
## Providers
-### Groq
-
-Fast inference provider using Groq's API.
+<CodeGroup>
-```python
+```python Groq
from semantica.llms import Groq
+import os
-groq = Groq(
- model="llama-3.1-8b-instant",
- api_key="your-api-key" # or use GROQ_API_KEY env var
+llm = Groq(
+ model="llama-3.3-70b-versatile", # default
+ api_key=os.getenv("GROQ_API_KEY"),
+ max_tokens=64000,
+ temperature=0.0,
)
-
-response = groq.generate("Hello, world!")
-structured = groq.generate_structured("Extract entities from: Apple Inc.")
+# Best for: high-throughput extraction, fast inference
```
-**Parameters:**
-- `model` (str): Model name (default: "llama-3.1-8b-instant")
-- `api_key` (str, optional): Groq API key (default: from GROQ_API_KEY env var)
-- `**kwargs`: Additional provider options
-
-**Methods:**
-- `generate(prompt: str, **kwargs) -> str`: Generate text from prompt
-- `generate_structured(prompt: str, **kwargs) -> Dict[str, Any]`: Generate structured JSON output
-- `is_available() -> bool`: Check if provider is available
-
-### OpenAI
-
-OpenAI API provider for GPT models.
-
-```python
+```python OpenAI
from semantica.llms import OpenAI
+import os
-openai = OpenAI(
- model="gpt-4",
- api_key="your-api-key" # or use OPENAI_API_KEY env var
+# pip install "semantica[llm-openai]"
+llm = OpenAI(
+ model="gpt-4o",
+ api_key=os.getenv("OPENAI_API_KEY"),
+ temperature=0.0,
)
-
-response = openai.generate("Hello, world!")
+# Best for: general purpose, function calling
```
-**Parameters:**
-- `model` (str): Model name (default: "gpt-3.5-turbo")
-- `api_key` (str, optional): OpenAI API key (default: from OPENAI_API_KEY env var)
-- `**kwargs`: Additional provider options
-
-**Methods:**
-- `generate(prompt: str, **kwargs) -> str`: Generate text from prompt
-- `generate_structured(prompt: str, **kwargs) -> Dict[str, Any]`: Generate structured JSON output
-- `is_available() -> bool`: Check if provider is available
-
-### HuggingFaceLLM
-
-Local LLM inference using HuggingFace Transformers.
-
-```python
-from semantica.llms import HuggingFaceLLM
+```python Anthropic
+from semantica.llms import Anthropic
+import os
-hf = HuggingFaceLLM(
- model_name="gpt2",
- device="cuda" # or "cpu", default: auto-detect
+# pip install "semantica[llm-anthropic]"
+llm = Anthropic(
+ model="claude-opus-4-7",
+ api_key=os.getenv("ANTHROPIC_API_KEY"),
+ max_tokens=8192,
)
-
-response = hf.generate("Hello, world!")
+# Best for: complex reasoning, long context, safety
```
-**Parameters:**
-- `model_name` (str, optional): HuggingFace model name (default: "gpt2")
-- `model` (str, optional): Alias for model_name (for consistency with other providers)
-- `device` (str, optional): Device to use ("cuda" or "cpu", default: auto-detect)
-- `**kwargs`: Additional provider options
-
-**Note:** Both `model` and `model_name` are supported for consistency with other providers.
-
-**Methods:**
-- `generate(prompt: str, **kwargs) -> str`: Generate text from prompt
-- `generate_structured(prompt: str, **kwargs) -> Dict[str, Any]`: Generate structured JSON output
-- `is_available() -> bool`: Check if provider is available
-
-### LiteLLM
-
-Unified interface to 100+ LLM providers via LiteLLM library.
-
-```python
-from semantica.llms import LiteLLM
+```python Gemini
+from semantica.llms import Gemini
+import os
-# Use any provider via LiteLLM
-litellm = LiteLLM(
- model="openai/gpt-4o", # Provider/model format
- api_key=os.getenv("OPENAI_API_KEY")
+# pip install "semantica[llm-gemini]"
+llm = Gemini(
+ model="gemini-1.5-pro",
+ api_key=os.getenv("GOOGLE_API_KEY"),
)
-
-# Or use other providers
-litellm = LiteLLM(model="anthropic/claude-sonnet-4-20250514")
-litellm = LiteLLM(model="groq/llama-3.1-8b-instant")
-litellm = LiteLLM(model="azure/gpt-4")
-
-response = litellm.generate("Hello, world!")
+# Best for: long context, multimodal tasks
```
-**Parameters:**
-- `model` (str): Model identifier in format "provider/model-name"
- - Examples: "openai/gpt-4o", "anthropic/claude-sonnet-4-20250514", "groq/llama-3.1-8b-instant", "azure/gpt-4"
-- `api_key` (str, optional): API key (can use environment variables)
-- `**kwargs`: Additional LiteLLM options (temperature, max_tokens, etc.)
-
-**Methods:**
-- `generate(prompt: str, **kwargs) -> str`: Generate text from prompt
-- `generate_structured(prompt: str, **kwargs) -> Dict[str, Any]`: Generate structured JSON output
-- `is_available() -> bool`: Check if provider is available
+```python Ollama (Local)
+from semantica.llms import Ollama
-**Supported Providers:**
-- OpenAI, Anthropic, Groq, Azure, Bedrock, Vertex AI, Cohere, Mistral, and 90+ more
-- See [LiteLLM Documentation](https://docs.litellm.ai/) for full list
-
-## Integration with GraphRAG
-
-The LLM providers integrate seamlessly with GraphRAG reasoning:
+# pip install "semantica[llm-ollama]"
+llm = Ollama(
+ model="llama3.2:3b",
+ base_url="http://localhost:11434",
+)
+# Best for: local inference, air-gapped environments
+# No API key required
+```
-```python
-from semantica.context import AgentContext
-from semantica.llms import Groq
-from semantica.vector_store import VectorStore
+```python DeepSeek
+from semantica.llms import DeepSeek
import os
-context = AgentContext(
- vector_store=VectorStore(backend="faiss"),
- knowledge_graph=kg
+llm = DeepSeek(
+ model="deepseek-chat",
+ api_key=os.getenv("DEEPSEEK_API_KEY"),
)
+# Best for: coding tasks, analysis at low cost
+```
-llm_provider = Groq(
- model="llama-3.1-8b-instant",
- api_key=os.getenv("GROQ_API_KEY")
-)
+```python LiteLLM (100+ models)
+from semantica.llms import LiteLLM
+import os
-result = context.query_with_reasoning(
- query="What IPs are associated with security alerts?",
- llm_provider=llm_provider,
- max_hops=2
+# pip install "semantica[llm-litellm]"
+llm = LiteLLM(
+ model="gpt-4o", # any LiteLLM-supported model string
+ api_key=os.getenv("OPENAI_API_KEY"),
)
-
-print(f"Response: {result['response']}")
-print(f"Reasoning Path: {result['reasoning_path']}")
+# Supports: OpenAI, Anthropic, Gemini, Cohere, Azure, Bedrock, and 90+ more
```
-## Common Parameters
-
-All providers support common generation parameters:
-
-- `temperature` (float): Sampling temperature (0.0-2.0)
-- `max_tokens` (int): Maximum tokens to generate
-- `top_p` (float): Nucleus sampling parameter
-- `frequency_penalty` (float): Frequency penalty
-- `presence_penalty` (float): Presence penalty
+```python HuggingFace (BYOM)
+from semantica.llms import HuggingFace
-Example:
-
-```python
-response = groq.generate(
- "What is AI?",
- temperature=0.7,
- max_tokens=500,
- top_p=0.9
+llm = HuggingFace(
+ model="mistralai/Mistral-7B-Instruct-v0.3",
+ device="cuda", # "cpu" | "cuda" | "mps"
+ max_new_tokens=512,
+ temperature=0.1,
)
+# Bring your own model β€” full local control
```
-## Error Handling
+</CodeGroup>
-All providers gracefully handle errors:
+---
+
+## Provider Factory
```python
-try:
- response = groq.generate("Hello")
-except ProcessingError as e:
- print(f"Generation failed: {e}")
+from semantica.llms import create_provider
+
+llm = create_provider("groq", model="llama-3.3-70b-versatile")
+llm = create_provider("openai", model="gpt-4o")
+llm = create_provider("anthropic", model="claude-opus-4-7")
+llm = create_provider("gemini", model="gemini-1.5-pro")
+llm = create_provider("ollama", model="llama3.2")
+llm = create_provider("deepseek", model="deepseek-chat", api_key=os.getenv("DEEPSEEK_API_KEY"))
+llm = create_provider("novita", model="deepseek/deepseek-v3.2", api_key=os.getenv("NOVITA_API_KEY"))
+llm = create_provider("litellm", model="gpt-4o")
```
-If a provider is not available (library not installed, API key missing), a `ProcessingError` is raised with a helpful message.
-
-### Built-in Retries
-The `generate_structured` method includes built-in retry logic for all providers:
-- **Attempts**: 3
-- **Wait Time**: 1 second base with exponential backoff
-- **Triggers**: Network errors, rate limits, and malformed JSON responses.
-
-### Robust JSON Parsing
-`BaseProvider` uses an enhanced `_parse_json` method that can handle:
-- Markdown code blocks (e.g., ```json ... ```)
-- Extra text before or after the JSON object
-- Common LLM formatting inconsistencies.
-
-## Examples
-
-### Basic Text Generation
+---
-```python
-from semantica.llms import Groq
+## Custom / Enterprise Gateways
-groq = Groq(model="llama-3.1-8b-instant")
-response = groq.generate("Explain quantum computing in simple terms.")
-print(response)
-```
-
-### Structured Output
+Any OpenAI-compatible gateway β€” internal routing layers, Qwen proxies, LLaMA proxies:
```python
from semantica.llms import OpenAI
-openai = OpenAI(model="gpt-4")
-result = openai.generate_structured(
- "Extract entities from: Apple Inc. was founded by Steve Jobs in 1976."
+llm = OpenAI(
+ model="qwen2.5-72b",
+ api_key=os.getenv("GATEWAY_API_KEY"),
+ base_url="https://my-internal-gateway.company.com/v1",
)
-# Returns: {"entities": [{"name": "Apple Inc.", "type": "Organization"}, ...]}
-```
-
-### Using LiteLLM for Multiple Providers
-
-```python
-from semantica.llms import LiteLLM
-
-# Switch between providers easily
-providers = [
- LiteLLM(model="openai/gpt-4o"),
- LiteLLM(model="anthropic/claude-sonnet-4-20250514"),
- LiteLLM(model="groq/llama-3.1-8b-instant")
-]
-
-for provider in providers:
- response = provider.generate("What is AI?")
- print(f"{provider.model}: {response[:50]}...")
```
-## Installation
-
-Most providers require additional dependencies:
+<Note>
+ `base_url` is validated at construction time. Non-HTTP(S) schemes raise `ValueError` to prevent SSRF attacks (fixed in v0.5.0).
+</Note>
-```bash
-# Groq
-pip install groq
+---
-# OpenAI
-pip install openai
+## Using in Extractors
-# HuggingFace
-pip install transformers torch
+```python
+from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor
-# LiteLLM (supports 100+ providers)
-pip install litellm
+ner = NERExtractor(method="llm", llm_provider=llm, max_retries=3)
+rel = RelationExtractor(method="llm", llm_provider=llm)
+trip = TripletExtractor(method="llm", llm_provider=llm)
```
-## Cookbook
+---
-Interactive tutorials that use LLM providers:
+## Provider Comparison
-- **[Advanced Extraction](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/01_Advanced_Extraction.ipynb)**: Custom extractors and LLM-based extraction
- - **Topics**: LLM extraction, custom models, complex pattern matching
- - **Difficulty**: Advanced
- - **Use Cases**: Domain-specific extraction, complex schemas
+| Provider | Speed | Cost | Local | Context | Best for |
+|----------|-------|------|-------|---------|----------|
+| Groq | Very fast | Low | No | 128k | High-throughput extraction |
+| OpenAI | Fast | Medium | No | 128k | General purpose, function calling |
+| Anthropic | Fast | Medium | No | 200k | Complex reasoning, safety |
+| Gemini | Fast | Low | No | 1M | Long context, multimodal |
+| Ollama | Medium | Free | Yes | Varies | Privacy, no API key |
+| DeepSeek | Fast | Very low | No | 64k | Coding, analysis |
+| Novita AI | Fast | Low | No | Varies | DeepSeek-based tasks |
+| LiteLLM | Varies | Varies | Varies | Varies | Multi-provider routing |
+| HuggingFace | Slow | Free | Yes | Varies | Custom models, BYOM |
-- **[GraphRAG Complete](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)**: Production-ready GraphRAG system using LLMs
- - **Topics**: GraphRAG, LLM integration, hybrid retrieval
- - **Difficulty**: Advanced
- - **Use Cases**: Building AI applications with knowledge graphs
+<Tip>
+ For production systems, Groq delivers the best throughput-to-cost ratio for extraction pipelines. For complex multi-hop reasoning tasks, Claude Opus or GPT-4o provide the highest accuracy.
+</Tip>
-## See Also
+---
-- [Context Module](context.md) - GraphRAG with multi-hop reasoning
-- [Semantic Extract Module](semantic_extract.md) - Entity and relationship extraction
-- [GraphRAG Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) - Complete GraphRAG example
+## See Also
+<CardGroup cols={2}>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Use LLMs for NER and relation extraction.
+ </Card>
+ <Card title="Agno Integration" icon="robot" href="../integrations/agno">
+ LLM providers in Agno multi-agent teams.
+ </Card>
+ <Card title="Reasoning" icon="brain" href="reasoning">
+ LLM-backed deductive and abductive reasoning.
+ </Card>
+ <Card title="Context" icon="diagram-project" href="context">
+ GraphRAG uses LLMs for reasoning over knowledge graphs.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/mcp_server.md b/docs/reference/mcp_server.md
new file mode 100644
index 00000000..0bc5423d
--- /dev/null
+++ b/docs/reference/mcp_server.md
@@ -0,0 +1,330 @@
+---
+title: "MCP Server"
+description: "Model Context Protocol server β€” expose Semantica's full capability set to Claude Desktop, VS Code, Cursor, and any MCP-aware tool."
+icon: "plug"
+---
+
+`semantica.mcp_server` exposes Semantica's knowledge graph, decision intelligence, semantic extraction, and reasoning capabilities as an [MCP (Model Context Protocol)](https://modelcontextprotocol.io) server over stdio.
+
+Compatible with **Claude Desktop**, **Windsurf**, **Cline**, **Continue**, **VS Code**, **Roo Code**, **Cursor**, and any other MCP-aware tool.
+
+---
+
+## Installation
+
+```bash
+pip install semantica
+```
+
+The MCP server is included in the base install β€” no extras required.
+
+---
+
+## Configuration
+
+Add Semantica to your MCP client's settings:
+
+<CodeGroup>
+
+```json Claude Desktop / Windsurf / Cline
+{
+ "mcpServers": {
+ "semantica": {
+ "command": "semantica-mcp"
+ }
+ }
+}
+```
+
+```json VS Code / Continue / Roo Code
+{
+ "mcpServers": {
+ "semantica": {
+ "command": "python",
+ "args": ["-m", "semantica.mcp_server"]
+ }
+ }
+}
+```
+
+```json With persistent graph
+{
+ "mcpServers": {
+ "semantica": {
+ "command": "semantica-mcp",
+ "env": {
+ "SEMANTICA_KG_PATH": "/path/to/my_graph.json",
+ "SEMANTICA_LOG_LEVEL": "INFO"
+ }
+ }
+ }
+}
+```
+
+</CodeGroup>
+
+---
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `SEMANTICA_KG_PATH` | *(none)* | Path to a persisted graph to load on startup |
+| `SEMANTICA_LOG_LEVEL` | `WARNING` | Log level: `DEBUG`, `INFO`, `WARNING` |
+
+---
+
+## Tools
+
+The MCP server exposes 12 tools that any connected AI assistant can call:
+
+### Knowledge Extraction
+
+<AccordionGroup>
+
+<Accordion title="extract_entities" icon="tag">
+
+Extract named entities (people, places, organisations, concepts) from text using Semantica NER.
+
+**Input:**
+```json
+{ "text": "Apple Inc. was founded by Steve Jobs in Cupertino in 1976." }
+```
+
+**Output:**
+```json
+{
+ "entities": [
+ { "label": "Apple Inc.", "type": "ORGANIZATION", "start": 0, "end": 10 },
+ { "label": "Steve Jobs", "type": "PERSON", "start": 26, "end": 36 },
+ { "label": "Cupertino", "type": "LOCATION", "start": 40, "end": 49 },
+ { "label": "1976", "type": "DATE", "start": 53, "end": 57 }
+ ]
+}
+```
+
+</Accordion>
+
+<Accordion title="extract_relations" icon="arrows-left-right">
+
+Extract typed relations and `(subject, predicate, object)` triplets from text.
+
+**Input:**
+```json
+{ "text": "Steve Jobs founded Apple Inc. and led it until 2011." }
+```
+
+**Output:**
+```json
+{
+ "relations": [
+ { "source": "Steve Jobs", "type": "founded", "target": "Apple Inc." }
+ ],
+ "triplets": [
+ { "subject": "Steve Jobs", "predicate": "founded", "object": "Apple Inc." }
+ ]
+}
+```
+
+</Accordion>
+
+</AccordionGroup>
+
+### Decision Intelligence
+
+<AccordionGroup>
+
+<Accordion title="record_decision" icon="check-circle">
+
+Record a decision with full context, reasoning, and metadata into the knowledge graph.
+
+**Input:**
+```json
+{
+ "category": "model_selection",
+ "scenario": "Choose LLM for production reasoning pipeline",
+ "reasoning": "GPT-4 benchmark advantage justifies 3x cost increase",
+ "outcome": "selected_gpt4",
+ "confidence": 0.91,
+ "decision_maker": "product_team"
+}
+```
+
+**Output:**
+```json
+{ "decision_id": "dec_a1b2c3", "status": "recorded" }
+```
+
+</Accordion>
+
+<Accordion title="query_decisions" icon="magnifying-glass">
+
+Query recorded decisions by natural language, category, or retrieve all recent decisions.
+
+**Input:**
+```json
+{ "query": "model selection", "limit": 5 }
+```
+
+</Accordion>
+
+<Accordion title="find_precedents" icon="clock-rotate-left">
+
+Find past decisions similar to a given scenario using hybrid similarity search.
+
+**Input:**
+```json
+{ "scenario": "Choose cloud provider for HIPAA workload", "max_results": 3 }
+```
+
+</Accordion>
+
+<Accordion title="get_causal_chain" icon="diagram-project">
+
+Trace the causal chain upstream or downstream from a decision.
+
+**Input:**
+```json
+{ "decision_id": "dec_a1b2c3", "direction": "downstream", "max_depth": 5 }
+```
+
+</Accordion>
+
+</AccordionGroup>
+
+### Graph Operations
+
+<AccordionGroup>
+
+<Accordion title="add_entity" icon="circle-plus">
+
+Add a node/entity to the live knowledge graph.
+
+**Input:**
+```json
+{
+ "id": "apple_inc",
+ "label": "Apple Inc.",
+ "type": "Organization",
+ "metadata": { "founded": 1976, "hq": "Cupertino" }
+}
+```
+
+</Accordion>
+
+<Accordion title="add_relationship" icon="arrow-right">
+
+Add a directed relationship (edge) between two existing entities.
+
+**Input:**
+```json
+{
+ "source": "steve_jobs",
+ "target": "apple_inc",
+ "type": "FOUNDED",
+ "metadata": { "year": 1976 }
+}
+```
+
+</Accordion>
+
+<Accordion title="get_graph_analytics" icon="chart-bar">
+
+Compute PageRank centrality and community detection over the current graph. Returns top nodes by influence and community count.
+
+</Accordion>
+
+<Accordion title="get_graph_summary" icon="info-circle">
+
+Return node count, decision count, and graph health status.
+
+</Accordion>
+
+</AccordionGroup>
+
+### Reasoning & Export
+
+<AccordionGroup>
+
+<Accordion title="run_reasoning" icon="brain">
+
+Run forward-chaining IF/THEN rules over a set of facts to derive new facts.
+
+**Input:**
+```json
+{
+ "facts": ["Employee(John)", "Manager(John)"],
+ "rules": ["IF Manager(?x) THEN HasAuthority(?x)"]
+}
+```
+
+**Output:**
+```json
+{ "derived_facts": ["HasAuthority(John)"] }
+```
+
+</Accordion>
+
+<Accordion title="export_graph" icon="file-export">
+
+Export the current knowledge graph.
+
+**Input:**
+```json
+{ "format": "json-ld" }
+```
+
+Supported formats: `turtle`, `ttl`, `nt`, `xml`, `json-ld`, `json`.
+
+</Accordion>
+
+</AccordionGroup>
+
+---
+
+## Resources
+
+The MCP server also exposes three readable resources:
+
+| URI | Description |
+|-----|-------------|
+| `semantica://graph/summary` | High-level graph statistics |
+| `semantica://decisions/list` | All recorded decisions (up to 50) |
+| `semantica://schema/info` | Server version and available tools |
+
+---
+
+## Test Locally
+
+```bash
+# Run the server directly for testing (reads from stdin, writes to stdout)
+semantica-mcp
+
+# Or with Python
+python -m semantica.mcp_server
+```
+
+Send a JSON-RPC `initialize` message to confirm it's working:
+
+```bash
+echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | semantica-mcp
+```
+
+---
+
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Context" icon="brain" href="context">
+ The ContextGraph that the MCP server operates on.
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ NER and relation extraction powering the MCP tools.
+ </Card>
+ <Card title="Reasoning" icon="microchip" href="reasoning">
+ Forward-chaining engine behind run_reasoning.
+ </Card>
+ <Card title="Agno Integration" icon="robot" href="../integrations/agno">
+ Use Semantica inside Agno multi-agent teams.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/normalize.md b/docs/reference/normalize.md
index 8b8084ad..99b45a78 100644
--- a/docs/reference/normalize.md
+++ b/docs/reference/normalize.md
@@ -1,601 +1,128 @@
-# Normalize
-
-> **Clean, standardize, and prepare text and data for semantic processing with comprehensive normalization capabilities.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-text-box-remove:{ .lg .middle } **Text Cleaning**
-
- ---
-
- Remove noise, fix encoding issues, and standardize whitespace for clean text
-
-- :material-format-text:{ .lg .middle } **Entity Normalization**
-
- ---
-
- Standardize entity names, abbreviations, and formats across documents
-
-- :material-calendar-clock:{ .lg .middle } **Date & Time**
-
- ---
-
- Parse and standardize date/time formats to ISO 8601
-
-- :material-numeric:{ .lg .middle } **Number Normalization**
-
- ---
-
- Standardize numeric values, units, and measurements
-
-- :material-translate:{ .lg .middle } **Language Detection**
-
- ---
-
- Automatically detect document language with confidence scoring
-
-- :material-file-code:{ .lg .middle } **Encoding Handling**
-
- ---
-
- Fix character encoding issues and ensure UTF-8 compliance
-
-</div>
-
-!!! tip "Why Normalize?"
- Normalization is crucial for:
-
- - **Consistency**: Ensure uniform data representation
- - **Accuracy**: Improve entity extraction and matching
- - **Quality**: Reduce noise and errors in downstream processing
- - **Performance**: Enable better deduplication and search
-
+title: "Normalize Module"
+description: "Text cleaning, entity standardization, date normalization, and encoding repair."
+icon: "broom"
---
-## βš™οΈ Algorithms Used
-
-### Text Normalization
-
-**Purpose**: Clean and standardize text for consistent processing.
-
-**How it works**:
-
-- **Unicode Normalization**: NFC, NFD, NFKC, NFKD forms using Unicode standard
-- **Whitespace Normalization**: Regex-based cleanup (`` `\s+` `` β†’ single space)
-- **Case Folding**: Locale-aware case normalization (Unicode case folding)
-- **Diacritic Removal**: Unicode decomposition and combining character removal
-- **Punctuation Handling**: Smart punctuation normalization preserving sentence structure
-
-### Entity Normalization
-
-**Purpose**: Standardize entity names and resolve variations to canonical forms.
-
-**How it works**:
-
-- **Fuzzy Matching**: Levenshtein distance with configurable threshold (default: `` `0.85` ``)
-- **Phonetic Matching**: Soundex and Metaphone algorithms for name variants
-- **Abbreviation Expansion**: Dictionary-based expansion with context awareness
-- **Canonical Form Selection**: Frequency-based or confidence-based selection
-- **Entity Linking**: Hash-based entity ID generation for cross-document linking
-
-### Date/Time Normalization
-
-**Purpose**: Parse and standardize date/time formats to ISO 8601.
-
-**How it works**:
-
-- **Parsing**: dateutil parser with 100+ format support
-- **Timezone Handling**: pytz for timezone conversion and DST handling
-- **Standardization**: ISO 8601 format output (`` `YYYY-MM-DDTHH:MM:SSZ` ``)
-- **Relative Date Resolution**: Convert "yesterday", "last week" to absolute dates
-- **Fuzzy Date Parsing**: Handle incomplete dates (e.g., "March 2024")
-
-### Number Normalization
-
-**Purpose**: Standardize numeric values, units, and measurements.
-
-**How it works**:
-
-- **Numeric Parsing**: Handle various formats (`` `1,000.00` ``, `` `1.000,00` ``, `` `1 000.00` ``)
-- **Unit Conversion**: Standardize units (km β†’ meters, lbs β†’ kg)
-- **Scientific Notation**: Parse and normalize scientific notation
-- **Percentage Handling**: Normalize percentage representations
-- **Currency Normalization**: Standardize currency symbols and amounts
-
-### Language Detection
-
-**Purpose**: Automatically detect document language with confidence scoring.
-
-**How it works**:
-
-- **N-gram Analysis**: Character and word n-gram frequency analysis
-- **Statistical Models**: Language-specific statistical models
-- **Confidence Scoring**: Probability-based confidence scores
-- **Multi-language Support**: 100+ languages supported
+> Clean, standardize, and prepare text and data for semantic processing.
---
-## Main Classes
-
-### TextNormalizer
-
-Main text normalization orchestrator with comprehensive cleaning capabilities.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `normalize_text(text, ...)` `` | Normalize single text using full pipeline |
-| `` `clean_text(text, ...)` `` | Clean text (HTML removal, sanitization) |
-| `` `standardize_format(text, format_type)` `` | Standardize formatting (standard/compact/preserve) |
-| `` `process_batch(texts, ...)` `` | Batch normalize multiple texts |
-
-**Example:**
+## DataNormalizer
```python
-from semantica.normalize import TextNormalizer
-
-normalizer = TextNormalizer()
-
-# Normalize
-normalized = normalizer.normalize_text(" Apple Inc. was founded in 1976. ", case="preserve")
-
-# Clean only
-cleaned = normalizer.clean_text("<p>Hello</p>", remove_html=True)
-
-# Batch
-texts = ["Hello World", "Another Example"]
-normalized_batch = normalizer.process_batch(texts, case="lower")
-```
+from semantica.normalize import DataNormalizer
----
-
-### EntityNormalizer
-
-Standardize entity names and resolve variations to canonical forms.
+normalizer = DataNormalizer()
-**Methods:**
+# Text cleaning
+clean = normalizer.normalize_text(" Hello, World!! \n\n")
+# β†’ "Hello, World!!"
-| Method | Description |
-|--------|-------------|
-| `` `normalize_entity(name, ...)` `` | Normalize entity name to canonical form |
-| `` `resolve_aliases(name, ...)` `` | Resolve aliases via alias map |
-| `` `disambiguate_entity(name, ...)` `` | Disambiguate using context and candidates |
-| `` `link_entities(names, ...)` `` | Link a list of names to canonical forms |
-
-**Configuration Options:**
-
-```python
-EntityNormalizer(
- fuzzy_matching=True, # Enable fuzzy matching
- similarity_threshold=0.85, # Similarity threshold (0-1)
- phonetic_matching=False, # Enable phonetic matching
- case_sensitive=False, # Case-sensitive matching
- preserve_case=True, # Preserve original case in output
- expand_abbreviations=True, # Expand common abbreviations
- canonical_dict=None # Custom canonical mappings
-)
-```
-
-**Example:**
-
-```python
-from semantica.normalize import EntityNormalizer
+# Date standardization
+date = normalizer.normalize_date("Jan 1st, 2020")
+# β†’ "2020-01-01"
-normalizer = EntityNormalizer(similarity_threshold=0.85)
-
-# Normalize single
-canonical = normalizer.normalize_entity("Apple, Inc.")
+# Entity normalization
+entity = normalizer.normalize_entity("Apple Computer Inc.")
+# β†’ "Apple Inc."
-# Link list
-linked = normalizer.link_entities(["Apple Inc.", "Apple", "AAPL"], entity_type="Organization")
+# Number normalization
+num = normalizer.normalize_number("$1,234.56")
+# β†’ 1234.56
```
---
-### DateNormalizer
-
-Parse and standardize date/time formats to ISO 8601.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `normalize_date(date_str, ...)` `` | Parse and normalize date |
-| `` `normalize_time(time_str, ...)` `` | Normalize time-only strings |
-| `` `parse_temporal_expression(expr)` `` | Parse date ranges and temporal phrases |
-
-**Configuration Options:**
+## Text Normalization
```python
-DateNormalizer(
- output_format="ISO8601", # ISO8601, UNIX, custom format
- timezone="UTC", # Target timezone
- handle_relative=True, # Parse "yesterday", "last week"
- fuzzy=True, # Fuzzy parsing
- default_day=1, # Default day for incomplete dates
- default_month=1 # Default month for incomplete dates
+text = normalizer.normalize_text(
+ raw_text,
+ lowercase=False, # convert to lowercase
+ remove_punctuation=False, # strip punctuation
+ remove_extra_whitespace=True,
+ fix_encoding=True, # repair cp1252/latin-1 mojibake
+ strip_html=True, # remove HTML tags
+ normalize_unicode=True # NFC normalization
)
```
-**Example:**
-
-```python
-from semantica.normalize import DateNormalizer
-
-normalizer = DateNormalizer()
-
-dates = ["Jan 1, 2024", "01/01/2024", "yesterday"]
-normalized = [normalizer.normalize_date(d) for d in dates]
-
-time = normalizer.normalize_time("10:30 AM")
-```
-
----
-
-### NumberNormalizer
-
-Standardize numeric values, units, and measurements.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `normalize_number(input, ...)` `` | Parse and normalize number |
-| `` `normalize_quantity(quantity, ...)` `` | Parse value with unit |
-| `` `convert_units(value, from_unit, to_unit)` `` | Convert units |
-| `` `process_currency(text, ...)` `` | Parse currency amount and code |
-
-**Example:**
-
-```python
-from semantica.normalize import NumberNormalizer
-
-normalizer = NumberNormalizer()
-
-numbers = ["1,000.50", "50%", "1.5e3"]
-normalized = [normalizer.normalize_number(n) for n in numbers]
-
-quantity = normalizer.normalize_quantity("5 kg")
-converted = normalizer.convert_units(5, "km", "m")
-currency = normalizer.process_currency("$1,234.56")
-```
+<Note>
+ **v0.5.0 fix:** The encoding repair now handles cp1252/latin-1 characters that previously caused crashes on Windows when processing documents with non-ASCII content.
+</Note>
---
-### LanguageDetector
-
-Detect document language with confidence scoring.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `detect(text)` `` | Detect language |
-| `` `detect_with_confidence(text)` `` | Detect with confidence score |
-| `` `detect_multiple(text, top_n)` `` | List top-N candidate languages |
-| `` `detect_batch(texts)` `` | Batch language detection |
-
-**Example:**
+## Entity Normalization
```python
-from semantica.normalize import LanguageDetector
-
-detector = LanguageDetector()
-
-# Detect language
-texts = [
- "Hello, how are you?",
- "Bonjour, comment allez-vous?",
- "Hola, ΒΏcΓ³mo estΓ‘s?",
- "Hallo, wie geht es dir?",
- "γ“γ‚“γ«γ‘γ―γ€γŠε…ƒζ°—γ§γ™γ‹οΌŸ"
+# Company name normalization
+companies = [
+ "Apple Computer, Inc.",
+ "Apple Inc",
+ "APPLE INC.",
]
+normalized = [normalizer.normalize_entity(c) for c in companies]
+# All β†’ "Apple Inc."
-for text in texts:
- result = detector.detect(text)
- print(f"{text[:30]:30} β†’ {result['language']} ({result['confidence']:.2f})")
-
-# Output:
-# Hello, how are you? β†’ en (0.99)
-# Bonjour, comment allez-vous? β†’ fr (0.98)
-# Hola, ΒΏcΓ³mo estΓ‘s? β†’ es (0.97)
-# Hallo, wie geht es dir? β†’ de (0.96)
-# γ“γ‚“γ«γ‘γ―γ€γŠε…ƒζ°—γ§γ™γ‹οΌŸ β†’ ja (0.99)
-```
-
----
-
-## Configuration
-
-### Environment Variables
-
-```bash
-# Normalization settings
-export NORMALIZE_DEFAULT_LOWERCASE=false
-export NORMALIZE_DEFAULT_ENCODING=utf-8
-export NORMALIZE_DEFAULT_TIMEZONE=UTC
-
-# Entity normalization
-export NORMALIZE_ENTITY_SIMILARITY_THRESHOLD=0.85
-export NORMALIZE_ENTITY_FUZZY_MATCHING=true
-
-# Language detection
-export NORMALIZE_LANGUAGE_DETECTOR=langdetect
-export NORMALIZE_LANGUAGE_CONFIDENCE_THRESHOLD=0.8
-```
-
-### YAML Configuration
-
-```yaml
-# config.yaml - Normalize Module Configuration
-
-normalize:
- text:
- lowercase: false
- remove_punctuation: false
- fix_encoding: true
- normalize_whitespace: true
- remove_urls: false
- expand_contractions: false
-
- entity:
- fuzzy_matching: true
- similarity_threshold: 0.85
- phonetic_matching: false
- expand_abbreviations: true
-
- date:
- output_format: "ISO8601"
- timezone: "UTC"
- handle_relative: true
- fuzzy: true
-
- number:
- decimal_separator: "."
- thousands_separator: ","
- normalize_units: true
-
- language:
- detector: "langdetect" # langdetect, fasttext
- confidence_threshold: 0.8
- fallback_language: "en"
+# Person name normalization
+name = normalizer.normalize_person_name("JOBS, STEVE")
+# β†’ "Steve Jobs"
```
---
-## Integration Examples
-
-### Complete Document Normalization Pipeline
-
-```python
-from semantica.normalize import TextNormalizer, EntityNormalizer, DateNormalizer, LanguageDetector
-from semantica.parse import DocumentParser
-
-# Parse documents
-parser = DocumentParser()
-documents = parser.parse(["document1.pdf", "document2.docx"])
-
-# Detect language
-detector = LanguageDetector()
-for doc in documents:
- lang_result = detector.detect(doc.content)
- doc.metadata["language"] = lang_result["language"]
- doc.metadata["language_confidence"] = lang_result["confidence"]
-
-text_normalizer = TextNormalizer()
-
-for doc in documents:
- doc.content = text_normalizer.normalize_text(doc.content)
-
-# Normalize dates in metadata
-date_normalizer = DateNormalizer(output_format="ISO8601")
-for doc in documents:
- if "date" in doc.metadata:
- doc.metadata["date"] = date_normalizer.normalize_date(doc.metadata["date"])
-
-# Normalize entities
-entity_normalizer = EntityNormalizer(similarity_threshold=0.85)
-# ... entity normalization logic
-```
-
-### Multi-Language Document Processing
+## Date & Time Normalization
```python
-from semantica.normalize import LanguageDetector, TextNormalizer
-
-detector = LanguageDetector()
-normalizers = {
- "en": TextNormalizer(expand_contractions=True),
- "fr": TextNormalizer(remove_diacritics=False),
- "de": TextNormalizer(lowercase=False)
-}
-
-def process_multilingual_document(text):
- # Detect language
- lang_result = detector.detect(text)
- language = lang_result["language"]
-
- # Use language-specific normalizer
- normalizer = normalizers.get(language, TextNormalizer())
- normalized = normalizer.normalize_text(text)
-
- return {
- "text": normalized,
- "language": language,
- "confidence": lang_result["confidence"]
- }
-
-# Process documents
-documents = ["Hello world", "Bonjour le monde", "Hallo Welt"]
-results = [process_multilingual_document(doc) for doc in documents]
-```
-
----
-
-## Best Practices
-
-### 1. Choose Appropriate Normalization Level
-
-```python
-# Minimal normalization for entity extraction
-minimal = TextNormalizer(
- fix_encoding=True,
- normalize_whitespace=True
-)
-
-# Moderate normalization for search
-moderate = TextNormalizer(
- fix_encoding=True,
- normalize_whitespace=True,
- lowercase=True,
- remove_urls=True
-)
-
-# Aggressive normalization for topic modeling
-aggressive = TextNormalizer(
- lowercase=True,
- remove_punctuation=True,
- remove_numbers=True,
- remove_urls=True,
- expand_contractions=True
-)
-```
-
-### 2. Preserve Original Data
-
-```python
-# Always keep original text
-doc.original_content = doc.content
-doc.content = normalizer.normalize_text(doc.content)
-
-# Store normalization metadata
-doc.metadata["normalized"] = True
-doc.metadata["normalization_config"] = normalizer.config
-```
-
-### 3. Batch Processing for Performance
-
-```python
-# Batch normalize for better performance
-texts = [doc.content for doc in documents]
-normalized_texts = normalizer.process_batch(texts)
-
-for doc, normalized in zip(documents, normalized_texts):
- doc.content = normalized
+dates = [
+ "January 1st, 2020",
+ "01/01/2020",
+ "2020-01-01T00:00:00Z",
+ "yesterday", # relative dates supported
+]
+normalized = [normalizer.normalize_date(d) for d in dates]
+# All β†’ "2020-01-01" (ISO 8601)
```
---
-## Troubleshooting
-
-### Common Issues
-
-**Issue**: Encoding errors with special characters
+## Quantity Normalization
```python
-# Solution: Enable encoding fix
-normalizer = TextNormalizer(fix_encoding=True)
+# Currency
+normalizer.normalize_number("$1,234.56M") # β†’ 1234560000.0
+normalizer.normalize_number("€42K") # β†’ 42000.0
-# Or manually fix encoding
-from semantica.normalize import handle_encoding
-fixed_text, confidence = handle_encoding(problematic_text, operation="convert", source_encoding="latin-1")
-```
-
-**Issue**: Over-normalization losing important information
-
-```python
-# Solution: Use conservative settings
-normalizer = TextNormalizer(
- lowercase=False, # Keep case
- remove_punctuation=False, # Keep punctuation
- remove_numbers=False # Keep numbers
-)
-```
-
-**Issue**: Slow processing for large documents
-
-```python
-# Solution: Use batch processing
-normalizer = TextNormalizer()
-normalized = normalizer.process_batch(documents)
+# Units
+normalizer.normalize_unit("100 km/h") # β†’ {"value": 100, "unit": "km/h", "si": 27.78}
```
---
-## Components
-
-Key supporting classes available in `semantica.normalize`:
-
-- `UnicodeNormalizer` β€” Unicode processing (NFC/NFD/NFKC/NFKD), special chars
-- `WhitespaceNormalizer` β€” Line breaks, indentation, whitespace cleanup
-- `SpecialCharacterProcessor` β€” Punctuation and diacritic handling
-- `TextCleaner` β€” HTML removal and sanitization utilities
-- `AliasResolver` β€” Entity alias mapping
-- `EntityDisambiguator` β€” Context-based entity disambiguation
-- `NameVariantHandler` β€” Title and name variant handling
-- `TimeZoneNormalizer` β€” Timezone conversion utilities
-- `RelativeDateProcessor` β€” Relative date expressions (e.g., "3 days ago")
-- `TemporalExpressionParser` β€” Date range and temporal phrase parsing
-- `UnitConverter` β€” Unit normalization and conversion
-- `CurrencyNormalizer` β€” Currency symbol/code parsing
-- `ScientificNotationHandler` β€” Scientific notation parsing
-- `DataCleaner` β€” General data cleaning utilities
-- `DuplicateDetector` β€” Duplicate record detection
-- `DataValidator` β€” Schema-based dataset validation
-- `MissingValueHandler` β€” Missing value strategies
-- `EncodingHandler` β€” Encoding detection and conversion
-- `MethodRegistry` β€” Register and retrieve custom normalization methods
-- `NormalizeConfig` β€” Module configuration manager
-
-## Performance Tips
-
-### Memory Optimization
-
-```python
-# Process documents in chunks
-def normalize_large_corpus(documents, chunk_size=1000):
- normalizer = TextNormalizer()
-
- for i in range(0, len(documents), chunk_size):
- chunk = documents[i:i + chunk_size]
- normalized_chunk = normalizer.process_batch(chunk)
- yield from normalized_chunk
-```
-
-### Speed Optimization
+## Batch Processing
```python
-# Disable unnecessary features
-fast_normalizer = TextNormalizer(
- fix_encoding=False, # Skip if encoding is known good
- normalize_unicode=False, # Skip if not needed
- remove_diacritics=False # Skip if not needed
-)
-
-# Use parallel processing
-# Batch processing
-normalized_docs = normalizer.process_batch(documents)
+texts = ["Text 1...", "Text 2...", "Text 3..."]
+normalized = normalizer.normalize_batch(texts, batch_size=100)
```
---
## See Also
-- [Parse Module](parse.md) - Document parsing and extraction
-- [Semantic Extract Module](semantic_extract.md) - Entity and relation extraction
-- [Split Module](split.md) - Text chunking and splitting
-- [Ingest Module](ingest.md) - Data ingestion
-
-## Cookbook
-
-Interactive tutorials to learn data normalization:
-
-- **[Data Normalization](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/04_Data_Normalization.ipynb)**: Pipelines for cleaning, normalizing, and preparing text
- - **Topics**: Text cleaning, Unicode, formatting, language detection, entity normalization
- - **Difficulty**: Beginner
- - **Use Cases**: Data preprocessing, text cleaning, standardization
+<CardGroup cols={2}>
+ <Card title="Parse" icon="file-lines" href="parse">
+ Parse documents before normalization.
+ </Card>
+ <Card title="Split" icon="scissors" href="split">
+ Chunk normalized text.
+ </Card>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Resolve duplicate entities post-normalization.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Include normalization in a pipeline.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/ontology.md b/docs/reference/ontology.md
index 8f72c3f2..7f8d8991 100644
--- a/docs/reference/ontology.md
+++ b/docs/reference/ontology.md
@@ -1,473 +1,182 @@
-# Ontology
-
-> **Automated ontology generation, validation, and management system.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-factory:{ .lg .middle } **Automated Generation**
-
- ---
-
- 6-stage pipeline to generate OWL ontologies from raw data
-
-- :material-sitemap:{ .lg .middle } **Inference Engine**
-
- ---
-
- Infer classes, properties, and hierarchies from entity patterns
-
-- :material-chart-bar:{ .lg .middle } **Evaluation**
-
- ---
-
- Assess ontology quality using coverage, completeness, and granularity metrics
-
-- :material-file-code:{ .lg .middle } **OWL/RDF Export**
-
- ---
-
- Export to Turtle, RDF/XML, and JSON-LD formats
-
-</div>
-
-!!! tip "When to Use"
- - **Schema Design**: When defining the structure of your Knowledge Graph
- - **Data Modeling**: To formalize domain concepts and relationships
- - **Interoperability**: To ensure your data follows standard semantic web practices
-
+title: "Ontology Module"
+description: "Automated ontology generation, SHACL validation, SKOS vocabularies, alignment, diff/migration, and the visual Ontology Hub."
+icon: "sitemap"
---
-## βš™οΈ Algorithms Used
-
-### 6-Stage Generation Pipeline
-
-The ontology generation process follows these stages:
-
-1. **Semantic Network Parsing**: Extract concepts and patterns from raw entity/relationship data
-2. **YAML-to-Definition**: Transform patterns into intermediate class definitions
-3. **Definition-to-Types**: Map definitions to OWL types (`` `owl:Class` ``, `` `owl:ObjectProperty` ``)
-4. **Hierarchy Generation**: Build taxonomy trees using transitive closure and cycle detection
-5. **TTL Generation**: Serialize to Turtle format using `` `rdflib` ``
-
-### Inference Algorithms
-
-The module uses several inference algorithms:
-
-- **Class Inference**: Clustering entities by type and attribute similarity
-- **Property Inference**: Determining domain/range based on connected entity types
-- **Hierarchy Inference**: `` `A is_a B` `` detection based on subset relationships
+> Automated ontology generation, validation, and management system.
---
-## Ontology Ingestion
-
-Ingest existing ontology files directly into usable data structures using `OntologyIngestor`.
+## Overview
-**Function:** `ingest_ontology(source, method="file")`
+The **Ontology Module** provides the full lifecycle for knowledge graph schemas β€” from auto-generation and SHACL validation to visual editing in the Ontology Hub (v0.5.0).
-| Argument | Description |
-|----------|-------------|
-| `source` | File path, directory path, or list of paths |
-| `method` | Ingestion method (default: "file") |
+<Tip>
+ **When to use:** Schema design (defining KG structure), data modeling (formalizing domain concepts), interoperability (semantic web standards), and SHACL-based data quality validation.
+</Tip>
-**Example:**
-
-```python
-from semantica.ontology import ingest_ontology
-
-# Ingest file
-data = ingest_ontology("ontology.ttl")
-
-# Ingest directory
-dataset = ingest_ontology("ontologies/")
-```
-
-## Main Classes
-
-### OntologyEngine
-
-Unified orchestration for generation, inference, validation, OWL export, and evaluation.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `from_data(data, **options)` | Generate ontology from structured data |
-| `from_text(text, provider=None, model=None, **options)` | LLM-based generation from text |
-| `validate(ontology, **options)` | Validate ontology consistency |
-| `infer_classes(entities, **options)` | Infer classes from entities |
-| `infer_properties(entities, relationships, classes, **options)` | Infer properties |
-| `evaluate(ontology, **options)` | Evaluate ontology quality |
-| `to_owl(ontology, format="turtle")` | Export OWL/RDF serialization |
-| `export_owl(ontology, path, format="turtle")` | Save OWL to file |
-
-**Quick Start:**
-
-```python
-from semantica.ontology import OntologyEngine
-
-engine = OntologyEngine(base_uri="https://example.org/ontology/")
-
-data = {"entities": entities, "relationships": relationships}
-ontology = engine.from_data(data, name="MyOntology")
-
-turtle = engine.to_owl(ontology, format="turtle")
-```
-
-### LLMOntologyGenerator
-
-LLM-based ontology generation with multi-provider support (`openai`, `groq`, `deepseek`, `huggingface_llm`).
+---
-**Example:**
+## OntologyManager
```python
-from semantica.ontology import OntologyEngine
-
-text = "Acme Corp. hired Alice in 2024. Alice works for Acme."
-engine = OntologyEngine()
-
-ontology = engine.from_text(
- text,
- provider="deepseek",
- model="deepseek-chat",
- name="EmploymentOntology",
- base_uri="https://example.org/employment/",
-)
-```
+from semantica.ontology import OntologyManager
-Environment variables:
+ontology = OntologyManager()
+ontology.add_class("Person", properties=["name", "birth_date"])
+ontology.add_class("Organization", properties=["name", "founded_date"])
+ontology.add_relationship("works_for", domain="Person", range="Organization")
+ontology.add_constraint("Person", "must_have_name")
-```bash
-export OPENAI_API_KEY=...
-export GROQ_API_KEY=...
-export DEEPSEEK_API_KEY=...
+is_valid = ontology.validate_graph(kg)
+owl_ttl = ontology.export_owl(format="turtle")
```
-### OntologyGenerator
-
-Main entry point for the generation pipeline.
-
-**Methods:**
+---
-| Method | Description |
-|--------|-------------|
-| `generate_ontology(data)` | Run full pipeline |
-| `generate_from_schema(schema)` | Generate from explicit schema |
+## Auto-Generation (6-Stage Pipeline)
-**Example:**
+Generate an ontology automatically from your knowledge graph data.
```python
from semantica.ontology import OntologyGenerator
-generator = OntologyGenerator(base_uri="http://example.org/onto/")
-ontology = generator.generate_ontology({
- "entities": entities,
- "relationships": relationships
-})
-print(ontology.serialize(format="turtle"))
+generator = OntologyGenerator()
+ontology = generator.generate_from_graph(kg)
```
-### OntologyEvaluator
-
-Scores ontology quality.
+The pipeline runs through these stages:
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `evaluate_ontology(ontology)` | Calculate evaluation metrics |
-| `calculate_coverage(ontology, questions)` | Verify coverage |
-
-### ReuseManager
-
-Manages external dependencies.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `import_external_ontology(uri, ontology)` | Load and merge external ontology |
-| `evaluate_alignment(uri, ontology)` | Assess alignment and compatibility |
-
-### OntologyIngestor
-
-Handles ingestion of existing ontologies from files and directories.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `ingest_ontology(file_path)` | Ingest a single ontology file |
-| `ingest_directory(directory_path)` | Recursively ingest ontology files from a directory |
+1. **Semantic Network Parsing** β€” extract concepts and patterns from entity/relationship data
+2. **YAML-to-Definition** β€” transform patterns into intermediate class definitions
+3. **Definition-to-Types** β€” map definitions to OWL types (`owl:Class`, `owl:ObjectProperty`)
+4. **Hierarchy Generation** β€” build taxonomy trees using transitive closure and cycle detection
+5. **TTL Generation** β€” serialize to Turtle format using `rdflib`
+6. **Quality Evaluation** β€” assess coverage, completeness, and granularity metrics
---
-## Unified Engine Examples
+## SHACL Validation
```python
-from semantica.ontology import OntologyEngine
-
-engine = OntologyEngine(base_uri="https://example.org/ontology/")
+from semantica.ontology import SHACLGenerator, SHACLValidator
-# Generate
-ontology = engine.from_data({
- "entities": entities,
- "relationships": relationships,
-})
+# Generate SHACL shapes from an ontology
+generator = SHACLGenerator()
+shapes = generator.generate(ontology)
+shapes_ttl = shapes.serialize(format="turtle")
-# Validate
-result = engine.validate(ontology, reasoner="hermit")
-print("valid=", result.valid, "consistent=", result.consistent)
+# Validate a graph against shapes
+validator = SHACLValidator()
+report = validator.validate(kg, shapes=shapes)
-# Export
-turtle = engine.to_owl(ontology, format="turtle")
+if not report.conforms:
+ for violation in report.violations:
+ print(f"Violation: {violation.message} on {violation.node}")
```
---
-## Configuration
+## SKOS Vocabularies
-### Environment Variables
-
-```bash
-export ONTOLOGY_BASE_URI="http://my-org.com/ontology/"
-export ONTOLOGY_STRICT_MODE=true
-```
+```python
+from semantica.ontology import SKOSVocabulary
-### YAML Configuration
+vocab = SKOSVocabulary()
+vocab.add_concept("Machine Learning", broader="Artificial Intelligence")
+vocab.add_concept("Deep Learning", broader="Machine Learning")
+vocab.add_alt_label("ML", for_concept="Machine Learning")
-```yaml
-ontology:
- base_uri: "http://example.org/"
- generation:
- min_class_size: 5
- infer_hierarchy: true
+skos_ttl = vocab.export(format="turtle")
```
---
## Ontology Alignment
-Semantica supports mapping and connecting different ontologies to unify data across systems, standards, and domains. This enables cross-system interoperability, allowing a single semantic layer to span multiple standards (e.g., internal models and industry standards).
-
-Alignments are represented using standard RDF predicates such as `owl:equivalentClass`, `owl:equivalentProperty`, and `skos:exactMatch`.
-
-### Creating and Managing Alignments
-
-You can create and query alignments programmatically using the `OntologyEngine`:
-
```python
-from semantica.ontology.engine import OntologyEngine
-from semantica.triplet_store.triplet_store import TripletStore
-
-# Setup the store and engine (using Blazegraph as an example)
-my_triplet_store = TripletStore(backend="blazegraph")
-engine = OntologyEngine(store=my_triplet_store)
-
-# Create an alignment between an internal class and a standard schema
-engine.create_alignment(
- source_uri="http://internal.org/ontology/Employee",
- target_uri="http://schema.org/Person",
- predicate="http://www.w3.org/2002/07/owl#equivalentClass"
-)
-
-# Retrieve all bidirectional alignments for a specific entity
-alignments = engine.get_alignments("http://internal.org/ontology/Employee")
-```
-### Automated Alignment Suggestions
-
-When importing or merging external ontologies, the ReuseManager can automatically suggest alignments based on heuristic matching (such as identical labels with differing URIs).
-
-```python
-from semantica.ontology.reuse_manager import ReuseManager
-
-manager = ReuseManager()
-
-# Merge ontologies and auto-compute alignment suggestions
-merged_ontology = manager.merge_ontology_data(
- target=internal_ontology,
- source=industry_ontology,
- compute_alignments=True
-)
-
-# Suggestions are stored in merged_ontology["suggested_alignments"]
-```
+from semantica.ontology import OntologyAligner
-For executing SPARQL queries that utilize these alignments to retrieve cross-ontology results, see the [Triplet Store Alignment-Aware Queries](triplet_store.md#alignment-aware-queries)
+aligner = OntologyAligner()
+alignment = aligner.align(source_ontology, target_ontology)
+for mapping in alignment.mappings:
+ print(f"{mapping.source} β†’ {mapping.target} (confidence: {mapping.confidence:.2f})")
-## Integration Examples
-
-### Schema-First Knowledge Graph
-
-```python
-from semantica.ontology import OntologyEngine
-from semantica.kg import GraphBuilder, GraphValidator
-
-# 1. Generate Ontology from Sample Data
-engine = OntologyEngine()
-ontology = engine.from_data(sample_data)
-
-# 2. Extract schema for validation
-schema = {
- "entity_types": [c["name"] for c in ontology["classes"]],
- "relationship_types": [p["name"] for p in ontology["properties"]]
-}
-
-# 3. Initialize Validator and Builder
-validator = GraphValidator(schema=schema, strict=True)
-builder = GraphBuilder()
-
-# 4. Build Knowledge Graph
-kg = builder.build(full_dataset)
-
-# 5. Validate against Ontology Schema
-validation_result = validator.validate(kg)
-if validation_result.is_valid:
- print("Knowledge Graph matches the ontology schema!")
-else:
- print(f"Validation issues found: {validation_result.issues}")
+merged = aligner.merge(source_ontology, target_ontology, alignment)
```
---
-## SKOS Vocabulary Management
-
-Semantica supports [SKOS (Simple Knowledge Organization System)](https://www.w3.org/TR/skos-reference/) vocabularies as first-class semantic assets. SKOS triples are stored in the existing RDF triplet store and queried through the `OntologyEngine` β€” no additional packages are required.
-
-### Concepts and data model
-
-| SKOS element | RDF type / predicate |
-|---|---|
-| ConceptScheme | `skos:ConceptScheme` |
-| Concept | `skos:Concept` |
-| Preferred label | `skos:prefLabel` |
-| Alternative label | `skos:altLabel` |
-| Broader concept | `skos:broader` |
-| Narrower concept | `skos:narrower` |
-| Related concept | `skos:related` |
-| Human definition | `skos:definition` |
-| Notation / code | `skos:notation` |
-
-### Importing a SKOS vocabulary
-
-Use `TripletStore.add_skos_concept()` to load individual concepts. The method automatically asserts the parent `skos:ConceptScheme` triple the first time any concept for that scheme is added.
+## Diff & Migration
```python
-from semantica.triplet_store import TripletStore
-
-store = TripletStore(backend="blazegraph", endpoint="http://localhost:9999/blazegraph")
-
-SCHEME = "https://vocab.example.org/colours"
-
-store.add_skos_concept(
- concept_uri="https://vocab.example.org/colours/red",
- scheme_uri=SCHEME,
- pref_label="Red",
- alt_labels=["Crimson", "Rouge"],
- broader=["https://vocab.example.org/colours/warm"],
- definition="The colour at the long-wavelength end of the visible spectrum.",
- notation="RED",
-)
-
-store.add_skos_concept(
- concept_uri="https://vocab.example.org/colours/blue",
- scheme_uri=SCHEME,
- pref_label="Blue",
- alt_labels=["Azure", "Cerulean"],
-)
-```
-
-For bulk ingestion of an existing SKOS/Turtle file use `TripletStore.add_triplets()` after parsing the file with [rdflib](https://rdflib.readthedocs.io/):
+from semantica.ontology import OntologyDiff, OntologyMigrator
-```python
-import rdflib
-from semantica.semantic_extract.triplet_extractor import Triplet
+diff = OntologyDiff()
+changes = diff.compare(ontology_v1, ontology_v2)
-g = rdflib.Graph()
-g.parse("my_vocabulary.ttl", format="turtle")
+for change in changes:
+ print(f"{change.type}: {change.element} β€” {change.description}")
-triplets = [
- Triplet(subject=str(s), predicate=str(p), object=str(o))
- for s, p, o in g
-]
-store.add_triplets(triplets)
+migrator = OntologyMigrator()
+migration_script = migrator.generate_migration(changes)
+migrator.apply(kg, migration_script)
```
-### Listing and searching concepts
+---
-Once a vocabulary is loaded, use `OntologyEngine` to browse and search it:
+## OWL/RDF Export
```python
-from semantica.ontology import OntologyEngine
+from semantica.ontology import OWLExporter
-engine = OntologyEngine(store=store)
+exporter = OWLExporter()
+exporter.export(ontology, path="ontology.ttl", format="turtle")
+exporter.export(ontology, path="ontology.xml", format="xml")
+exporter.export(ontology, path="ontology.json", format="json-ld")
+```
-# 1. List all ConceptSchemes in the store
-vocabularies = engine.list_vocabularies()
-# [{"uri": "https://vocab.example.org/colours", "label": "Colours"}, ...]
+---
-# 2. List every concept in a specific scheme
-concepts = engine.list_concepts("https://vocab.example.org/colours")
-# [{"uri": "...", "pref_label": "Red", "alt_labels": ["Crimson", "Rouge"]}, ...]
+## Ontology Hub (v0.5.0)
-# 3. Case-insensitive substring search across prefLabel and altLabel
-results = engine.search_concepts("crimson")
-# [{"uri": "https://vocab.example.org/colours/red", "label": "Crimson"}]
+The Ontology Hub is a visual browser UI for the full ontology lifecycle, available via `semantica.explorer`.
-# 4. Restrict search to one scheme
-results = engine.search_concepts("azure", scheme_uri="https://vocab.example.org/colours")
+```bash
+pip install semantica[explorer]
```
-### Building SKOS URIs with NamespaceManager
-
-`NamespaceManager` provides helpers for constructing well-formed SKOS IRIs:
-
```python
-from semantica.ontology import NamespaceManager
+from semantica.explorer import start_explorer
-nm = NamespaceManager(base_uri="https://vocab.example.org/")
-
-# Full SKOS predicate URI
-nm.get_skos_uri("prefLabel")
-# "http://www.w3.org/2004/02/skos/core#prefLabel"
-
-# Slug-based ConceptScheme URI anchored at the base
-nm.build_concept_scheme_uri("ISO 3166 Countries")
-# "https://vocab.example.org/vocab/iso-3166-countries"
+start_explorer(graph=kg, port=8080)
+# Opens at http://localhost:8080 β€” navigate to the Ontology Hub tab
```
----
-
-## Best Practices
-
-1. **Reuse Standard Ontologies**: Don't reinvent `Person` or `Organization`; import FOAF or Schema.org using `ReuseManager`.
-2. **Validate Early**: Run validation during generation to catch logical errors before populating the graph.
-3. **Use Competency Questions**: Define what questions your ontology should answer and use `OntologyEvaluator` to verify.
-4. **Version Control**: Treat ontologies like code. Use `VersionManager` to track changes.
+Features:
+- **Visual Editor** β€” create and edit classes, properties, and relationships in the browser
+- **SHACL Studio** β€” author and validate SHACL shapes visually
+- **Alignment Authoring** β€” map concepts across ontologies with drag-and-drop
+- **Health Dashboard** β€” coverage, completeness, and granularity metrics
+- **Version Control** β€” track ontology changes with diff visualization
---
## See Also
-- [Knowledge Graph Module](kg.md) - The instance data following the ontology
-- [Reasoning Module](reasoning.md) - Uses the ontology for inference
-- [Visualization Module](visualization.md) - Visualizing the class hierarchy
-
-## Cookbook
-
-Interactive tutorials to learn ontology generation and management:
-
-- **[Ontology](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb)**: Define domain schemas and ontologies to structure your data
- - **Topics**: OWL, RDF, schema design, ontology generation
- - **Difficulty**: Intermediate
- - **Use Cases**: Structuring domain knowledge, schema definition
-
-- **[Unstructured to Ontology](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/12_Unstructured_to_Ontology.ipynb)**: Generate ontologies automatically from unstructured data
- - **Topics**: Automatic ontology generation, 6-stage pipeline, OWL validation
- - **Difficulty**: Advanced
- - **Use Cases**: Domain modeling, automatic schema generation
\ No newline at end of file
+<CardGroup cols={2}>
+ <Card title="Reasoning" icon="microchip" href="reasoning">
+ Apply inference rules over ontology axioms.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The graph being modeled by the ontology.
+ </Card>
+ <Card title="Export" icon="file-export" href="export">
+ Export ontologies as RDF, OWL, or JSON-LD.
+ </Card>
+ <Card title="Conflicts" icon="triangle-exclamation" href="conflicts">
+ Detect ontology constraint violations.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/parse.md b/docs/reference/parse.md
index f39b43f2..1611aab0 100644
--- a/docs/reference/parse.md
+++ b/docs/reference/parse.md
@@ -1,386 +1,133 @@
-# Parse
-
-> **Universal data parser supporting documents, web content, structured data, emails, code, and media.**
-
---
-
-## 🎯 Overview
-
-The **Parse Module** extracts structured content from raw files and data sources. It converts various file formats (PDF, DOCX, HTML, JSON, etc.) into usable text and structured data for semantic processing.
-
-### What is Document Parsing?
-
-**Document parsing** is the process of extracting text, structure, and metadata from files. The parse module handles:
-- **Documents**: PDF, DOCX, PPTX, Excel, TXT, RTF
-- **Web Content**: HTML, XML, JavaScript-rendered pages
-- **Structured Data**: JSON, CSV, XML, YAML
-- **Email**: MIME messages with attachments
-- **Code**: Source code parsing into ASTs
-- **Media**: OCR for images, metadata for audio/video
-
-### Why Use the Parse Module?
-
-- **Universal Format Support**: Handle dozens of file formats
-- **Structure Preservation**: Maintain document structure (tables, headings, etc.)
-- **OCR Support**: Extract text from scanned documents and images
-- **Metadata Extraction**: Extract document metadata (author, date, etc.)
-- **Code Analysis**: Parse source code for structure and dependencies
-- **Error Handling**: Robust handling of corrupted or malformed files
-
-### How It Works
-
-1. **Format Detection**: Automatically detect file format
-2. **Parser Selection**: Choose appropriate parser for the format
-3. **Content Extraction**: Extract text, structure, and metadata
-4. **Normalization**: Normalize extracted content
-5. **Output**: Return structured data ready for semantic processing
-
-<div class="grid cards" markdown>
-
-- :material-file-document:{ .lg .middle } **Document Parsing**
-
- ---
-
- Extract text, tables, and metadata from PDF, DOCX, PPTX, Excel, and TXT
-
-- :material-web:{ .lg .middle } **Web Content**
-
- ---
-
- Parse HTML, XML, and JavaScript-rendered pages with Selenium/Playwright
-
-- :material-code-json:{ .lg .middle } **Structured Data**
-
- ---
-
- Handle JSON, CSV, XML, and YAML with nested structure preservation
-
-- :material-email:{ .lg .middle } **Email Parsing**
-
- ---
-
- Extract headers, bodies, attachments, and thread structure from MIME messages
-
-- :material-code-braces:{ .lg .middle } **Code Analysis**
-
- ---
-
- Parse source code (Python, JS, etc.) into ASTs, extracting functions and dependencies
-
-- :material-image:{ .lg .middle } **Media Processing**
-
- ---
-
- OCR for images and metadata extraction for audio/video files
-
-</div>
-
-!!! tip "When to Use"
- - **After Ingestion**: The first step after loading raw files to convert them into usable text/data
- - **Data Extraction**: Pulling specific fields from structured files (JSON/CSV)
- - **Content Analysis**: Analyzing codebases or email archives
- - **OCR**: Extracting text from scanned documents or images
-
+title: "Parse Module"
+description: "Document parsing and text extraction β€” DocumentParser for standard formats and DoclingParser for complex layouts."
+icon: "file-lines"
---
-## βš™οΈ Algorithms Used
-
-### Document Parsing
-- **PDF**: `pdfplumber` for precise layout preservation, table extraction, and image handling. Fallback to `PyPDF2`.
-- **Docling**: `docling` integration for advanced document structure understanding and high-accuracy table extraction across PDF, DOCX, PPTX, XLSX, and HTML.
-- **Office (DOCX/PPTX/XLSX)**: XML-based parsing of OpenXML formats to extract text, styles, and properties.
-- **OCR**: Tesseract-based optical character recognition for image-based PDFs and image files.
-
-### Web Parsing
-- **DOM Traversal**: BeautifulSoup for static HTML parsing and element extraction.
-- **Headless Browser**: Selenium/Playwright for rendering dynamic JavaScript content before extraction.
-- **Content Cleaning**: Heuristic removal of boilerplates (navbars, footers, ads).
-
-### Code Parsing
-- **AST Traversal**: Abstract Syntax Tree parsing to identify classes, functions, and imports.
-- **Dependency Graphing**: Static analysis of import statements to build dependency networks.
-- **Comment Extraction**: Regex and parser-based extraction of docstrings and inline comments.
+> Universal data parser supporting documents, web content, structured data, emails, code, and media.
---
-## Main Classes
+## DocumentParser
-### DocumentParser
-
-Unified interface for document formats.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_document(path)` `` | Auto-detect format and parse |
-| `` `extract_text(path)` `` | Extract text from PDF/DOCX/HTML/TXT |
-| `` `extract_metadata(path)` `` | Extract document metadata |
-| `` `parse_batch(paths)` `` | Parse multiple documents |
-
-**Example:**
+Standard parser for clean, machine-readable documents.
```python
from semantica.parse import DocumentParser
parser = DocumentParser()
-doc = parser.parse_document("report.pdf")
-print(doc.get("metadata", {}).get("title"))
-print(doc.get("full_text", "")[:100])
-```
-
-### DoclingParser
-
-Specialized parser using Docling for enhanced layout understanding and table extraction. It is independent of `DocumentParser` and optimized for complex document structures.
+parsed = parser.parse("data/report.pdf")
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse(path)` `` | Full parse including text, tables, and metadata |
-| `` `parse_batch(paths)` `` | Parse multiple documents in parallel |
-| `` `extract_text(path)` `` | Extract clean text in Markdown/HTML/JSON format |
-| `` `extract_tables(path)` `` | High-accuracy table extraction |
-| `` `extract_metadata(path)` `` | Extract document properties |
-
-**Configuration:**
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `export_format` | `str` | `"markdown"` | Output format: `"markdown"`, `"html"`, `"json"` |
-| `enable_ocr` | `bool` | `False` | Enable OCR for scanned documents |
-
-**Example:**
-
-```python
-from semantica.parse import DoclingParser
-
-parser = DoclingParser()
-result = parser.parse("complex_table.pdf")
-
-# Access high-accuracy tables
-for table in result["tables"]:
- print(table["headers"])
-
-# Get markdown representation
-print(result["full_text"])
+print(parsed.text) # full clean text
+print(parsed.metadata) # title, author, date, page_count, etc.
+print(parsed.sections) # document structure
```
-### WebParser
-
-Parses web content.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_web_content(content, content_type)` `` | Parse HTML/XML |
-| `` `extract_text(content)` `` | Clean text from HTML |
-| `` `extract_links(content)` `` | Extract hyperlinks |
-| `` `render_javascript(url)` `` | Render JS for dynamic pages |
-
-### StructuredDataParser
-
-Parses data files.
+Supported formats: PDF, DOCX, HTML, TXT, JSON, CSV, PPTX, XLSX.
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_data(path, data_format)` `` | Parse JSON/CSV/XML/YAML |
+---
-**Example:**
+## DoclingParser
-```python
-from semantica.parse import StructuredDataParser
+Advanced parser for complex layouts using the Docling backend.
-parser = StructuredDataParser()
-data = parser.parse_data("data.json", data_format="json")
-print(type(data.get("data"))).__name__
+```bash
+pip install "semantica[docling]"
```
-### CodeParser
-
-Parses source code.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_code(path)` `` | Parse code file; returns structure, comments, dependencies |
-
-**Example:**
-
```python
-from semantica.parse import CodeParser
-
-parser = CodeParser()
-data = parser.parse_code("script.py", language="python")
-print(data.get("structure", {}).get("functions", []))
-print(data.get("dependencies", {}))
-```
-
-### EmailParser
-
-Parses email messages.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_email(path)` `` | Parse full email (headers/body/attachments) |
-| `` `parse_headers(path)` `` | Extract headers only |
-| `` `extract_body(path)` `` | Extract text/HTML body |
-| `` `analyze_thread(path)` `` | Thread reconstruction |
+from semantica.parse import DoclingParser
-**Example:**
+parser = DoclingParser(
+ extract_tables=True, # structured table extraction
+ extract_images=True, # image OCR
+ output_format="markdown", # "markdown" | "html" | "json"
+)
-```python
-from semantica.parse import EmailParser
+parsed = parser.parse("data/annual_report.pdf")
-parser = EmailParser()
-email = parser.parse_email("email.eml", extract_attachments=True)
-print(email.headers.subject)
-print(email.body.text[:120])
+print(parsed.text) # full clean text
+print(parsed.tables) # structured table data
+print(parsed.sections) # document structure
```
-### MediaParser
-
-Parses media files.
+Use DoclingParser for: multi-column PDFs, tables with merged cells, PPTX slides, XLSX spreadsheets, images with OCR, and scanned documents.
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `parse_media(path, media_type)` `` | Parse image/audio/video |
+---
-**Example:**
+## OCR Support
```python
-from semantica.parse import MediaParser
+parser = DoclingParser(
+ ocr=True,
+ ocr_language=["en"],
+ extract_tables=True,
+)
-parser = MediaParser()
-image = parser.parse_media("image.jpg", media_type="image")
-print(image.get("metadata", {}))
-```
-
-### Format-Specific Parsers
-
-- `PDFParser`, `DOCXParser`, `PPTXParser`, `ExcelParser`
-- `HTMLParser`, `XMLParser`
-- `JSONParser`, `CSVParser`
-- `ImageParser`
-
-**Examples:**
-
-```python
-from semantica.parse import DocumentParser, WebParser, StructuredDataParser
-
-# Document
-doc = DocumentParser().parse_document("document.pdf")
-print(doc.get("full_text", "")[:120])
-
-# Web
-web = WebParser().parse_web_content("https://example.com", content_type="html")
-print(web.get("text", "")[:120])
-
-# Structured Data (JSON)
-data = StructuredDataParser().parse_data("data.json", data_format="json")
-print(list(data.get("data", {}).keys()))
+parsed = parser.parse("data/scanned_contract.pdf")
```
---
-## Usage Examples
-
-### WebParser
-
-```python
-from semantica.parse import WebParser
-
-parser = WebParser()
-html = parser.parse_web_content("https://example.com", content_type="html")
-links = parser.extract_links("https://example.com")
-```
-
-### StructuredDataParser
+## Parsed Document Object
```python
-from semantica.parse import StructuredDataParser
-
-parser = StructuredDataParser()
-json = parser.parse_data("data.json", data_format="json")
-csv = parser.parse_data("data.csv", data_format="csv")
-xml = parser.parse_data("data.xml", data_format="xml")
+@dataclass
+class ParsedDocument:
+ text: str
+ sections: List[Section]
+ tables: List[TableData]
+ metadata: DocumentMetadata
+ source_id: str
+
+@dataclass
+class DocumentMetadata:
+ title: Optional[str]
+ author: Optional[str]
+ created_date: Optional[datetime]
+ page_count: int
+ language: Optional[str]
+ has_tables: bool
+ has_images: bool
+ word_count: int
+ format: str # "pdf" | "docx" | "pptx" | ...
```
---
-## Configuration
+## Integration with FileIngestor
-### Environment Variables
+```python
+from semantica.ingest import FileIngestor
+from semantica.parse import DoclingParser
-```bash
-export PARSE_OCR_ENABLED=true
-export PARSE_OCR_LANG=eng
-export PARSE_USER_AGENT="SemanticaBot/1.0"
-```
+ingestor = FileIngestor()
+parser = DoclingParser(extract_tables=True)
-### YAML Configuration
-
-```yaml
-parse:
- ocr:
- enabled: true
- language: eng
-
- web:
- user_agent: "MyBot/1.0"
- timeout: 30
-
- pdf:
- extract_tables: true
- extract_images: false
+sources = ingestor.ingest("data/reports/")
+for source in sources:
+ parsed = parser.parse(source)
```
----
-
-## Integration
-
-Use parser classes directly in pipelines and services. Avoid convenience functions for stronger type clarity and consistency.
-
----
-
-## Best Practices
-
-1. Disable OCR if not needed; enable only for scanned documents.
-2. Use specific parser classes like `JSONParser` or `PDFParser` when format is known.
-3. Handle encodings explicitly for CSV/TXT where auto-detect may fail.
-4. Clean web content using `WebParser` utilities rather than raw HTML parsing.
-
----
-
-## Troubleshooting
-
-**Issue**: `TesseractNotFoundError`
-**Solution**: Install Tesseract OCR on your system (`apt-get install tesseract-ocr` or brew).
-
-**Issue**: PDF tables are messy.
-**Solution**: Try `pdfplumber` settings in config or use specialized table extraction tools if layout is complex.
+<Note>
+ Docling is an optional dependency. If `docling` is not installed, `DoclingParser` raises an `ImportError` with installation instructions. Standard `DocumentParser` is used as the fallback.
+</Note>
---
## See Also
-- [Ingest Module](ingest.md) - Handles file downloading/loading
-- [Split Module](split.md) - Chunks the parsed text
-- [Semantic Extract Module](semantic_extract.md) - Extracts entities from text
-
-## Cookbook
-
-Interactive tutorials to learn document parsing:
-
-- **[Document Parsing](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/03_Document_Parsing.ipynb)**: Extract clean text from complex formats
- - **Topics**: OCR, PDF parsing, text extraction, format detection
- - **Difficulty**: Beginner
- - **Use Cases**: Processing documents, extracting text from various formats
+<CardGroup cols={2}>
+ <Card title="Ingest" icon="database" href="ingest">
+ Load files before parsing.
+ </Card>
+ <Card title="Split" icon="scissors" href="split">
+ Chunk parsed text for embedding.
+ </Card>
+ <Card title="Docling Integration" icon="file-pdf" href="../integrations/docling">
+ Full Docling integration guide.
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Extract entities from parsed text.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/pipeline.md b/docs/reference/pipeline.md
index ca73cef5..3c15db51 100644
--- a/docs/reference/pipeline.md
+++ b/docs/reference/pipeline.md
@@ -1,482 +1,141 @@
-# Pipeline
-
-> **Robust orchestration engine for building, executing, and managing complex data processing workflows.**
-
---
-
-## 🎯 Overview
-
-The **Pipeline Module** provides a robust orchestration engine for building, executing, and managing complex data processing workflows. It enables you to create reusable, scalable pipelines with error handling, parallel execution, and resource management.
-
-### What is Pipeline Orchestration?
-
-**Pipeline orchestration** is the process of coordinating multiple processing steps into a workflow. The Pipeline module enables:
-- **DAG Construction**: Build directed acyclic graphs (DAGs) of processing steps
-- **Parallel Execution**: Run independent steps simultaneously
-- **Error Handling**: Retry, fallback, and recovery strategies
-- **Resource Management**: CPU and memory allocation
-- **Progress Tracking**: Monitor pipeline execution
-
-### Why Use the Pipeline Module?
-
-- **Complex Workflows**: Coordinate multi-step data processing
-- **Reusability**: Create reusable pipeline templates
-- **Reliability**: Built-in error handling and retry logic
-- **Performance**: Parallel execution for faster processing
-- **Monitoring**: Track progress and performance
-- **Scalability**: Handle large-scale data processing
-
-### How It Works
-
-1. **Pipeline Definition**: Define steps and their dependencies
-2. **Validation**: Validate pipeline structure (no cycles, valid dependencies)
-3. **Execution**: Execute steps in dependency order
-4. **Parallelization**: Run independent steps in parallel
-5. **Error Handling**: Retry failed steps, apply fallbacks
-6. **Monitoring**: Track progress and resource usage
-
-<div class="grid cards" markdown>
-
-- :material-pipe:{ .lg .middle } **Pipeline Builder**
-
- ---
-
- Fluent API for constructing complex DAG workflows
-
-- :material-play-circle:{ .lg .middle } **Execution Engine**
-
- ---
-
- Robust execution with status tracking and progress monitoring
-
-- :material-alert-circle-check:{ .lg .middle } **Error Handling**
-
- ---
-
- Configurable retry policies, fallbacks, and error recovery
-
-- :material-fast-forward:{ .lg .middle } **Parallel Execution**
-
- ---
-
- Execute independent steps in parallel for maximum performance
-
-- :material-cpu-64-bit:{ .lg .middle } **Resource Scheduling**
-
- ---
-
- Manage CPU/Memory allocation for resource-intensive tasks
-
-- :material-file-document-edit:{ .lg .middle } **Templates**
-
- ---
-
- Pre-built templates for common workflows (ETL, GraphRAG)
-
-</div>
-
-!!! tip "When to Use"
- - **ETL Workflows**: Ingest -> Parse -> Split -> Embed -> Store
- - **Graph Construction**: Extract Entities -> Extract Relations -> Build Graph
- - **Batch Processing**: Processing large volumes of documents reliably
-
+title: "Pipeline Module"
+description: "Pipeline DSL with parallel workers, retry policies, failure handling, and progress tracking."
+icon: "gear"
---
-## βš™οΈ Algorithms Used
-
-### Execution Management
-
-**Purpose**: Manage pipeline execution order and state tracking.
-
-**How it works**:
-
-- **DAG Topological Sort**: Determines execution order of steps based on dependencies
-- **State Management**: Tracks `` `PENDING` ``, `` `RUNNING` ``, `` `COMPLETED` ``, `` `FAILED` `` states
-- **Checkpointing**: Saves intermediate results to allow resuming failed pipelines
-
-### Parallelism
-
-**Purpose**: Execute independent steps concurrently for maximum performance.
-
-**How it works**:
-
-- **ThreadPoolExecutor**: For I/O-bound tasks (network requests, DB writes)
-- **ProcessPoolExecutor**: For CPU-bound tasks (parsing, embedding generation)
-- **Dependency Resolution**: Identifies steps that can run concurrently
-
-### Error Handling
-
-**Purpose**: Robust error recovery with configurable retry policies.
-
-**How it works**:
-
-- **Exponential Backoff**: `` `wait = base * (factor ^ attempt)` ``
-- **Jitter**: Randomization to prevent thundering herd problem
-- **Circuit Breaker**: Stops execution after threshold failures to prevent cascading issues
-
-### Resource Scheduling
-
-**Purpose**: Manage CPU/Memory allocation for resource-intensive tasks.
-
-**How it works**:
-
-- **Token Bucket**: Rate limiting for API calls
-- **Semaphore**: Concurrency limiting for resource constraints
-- **Priority Queue**: Scheduling critical tasks first
+> Robust orchestration engine for building and executing complex data processing workflows.
---
-## API Reference
-
-### Types
-
-- `Pipeline` β€” Pipeline definition dataclass
-- `PipelineStep` β€” Pipeline step definition dataclass, Supports `delta_mode` (bool), `base_version_id` (str), and `target_version_id` (str) for incremental processing.
-- `StepStatus` β€” Enum: `pending`, `running`, `completed`, `failed`, `skipped`
-- `ExecutionResult` β€” Execution result dataclass
-- `PipelineStatus` β€” Enum: `pending`, `running`, `paused`, `completed`, `failed`, `stopped`
-- `ValidationResult` β€” Validation result dataclass
-- `RetryPolicy` β€” Retry policy dataclass
-- `RetryStrategy` β€” Enum: `linear`, `exponential`, `fixed`
-- `ErrorSeverity` β€” Enum: `low`, `medium`, `high`, `critical`
-- `FailureRecovery` β€” Failure recovery dataclass
-- `Task` β€” Parallel task dataclass
-- `ParallelExecutionResult` β€” Parallel execution result dataclass
-- `ResourceType` β€” Enum: `cpu`, `gpu`, `memory`, `disk`, `network`
-- `Resource` β€” Resource definition dataclass
-- `ResourceAllocation` β€” Resource allocation record dataclass
-
-### PipelineBuilder
-
-Fluent interface for constructing pipelines.
-
-**Methods:**
-
-- `add_step(step_name, step_type, **config)` β€” Add a step
-- `connect_steps(from_step, to_step, **options)` β€” Add dependency
-- `set_parallelism(level)` β€” Configure parallelism
-- `build(name="default_pipeline")` β€” Build pipeline
-- `build_pipeline(pipeline_config, **options)` β€” Build from dict
-- `register_step_handler(step_type, handler)` β€” Register handler
-- `get_step(step_name)` β€” Get step by name
-- `serialize(format="json")` β€” Serialize builder state
-- `validate_pipeline()` β€” Validate pipeline
-
-**Example:**
-
-```python
-from semantica.pipeline import PipelineBuilder
-
-builder = (
- PipelineBuilder()
- .add_step("ingest", "ingest", handler=ingest_handler)
- .add_step("parse", "parse", dependencies=["ingest"], handler=parse_handler)
- .add_step("embed", "embed", dependencies=["parse"], model="text-embedding-3-large")
- .set_parallelism(2)
-)
-pipeline = builder.build(name="MyPipeline")
-
-step = builder.get_step("parse")
-serialized = builder.serialize(format="json")
-validation = builder.validate_pipeline()
-```
-
-### PipelineSerializer
-
-Serialization utilities for pipelines.
-
-**Methods:**
-
-- `serialize_pipeline(pipeline, format="json")`
-- `deserialize_pipeline(serialized_pipeline, **options)`
-- `version_pipeline(pipeline, version_info)`
-
-**Example:**
-
-```python
-from semantica.pipeline import PipelineBuilder, PipelineSerializer
-
-builder = PipelineBuilder()
-pipeline = builder.add_step("step1", "type1").build()
-
-serializer = PipelineSerializer()
-serialized = serializer.serialize_pipeline(pipeline, format="json")
-restored = serializer.deserialize_pipeline(serialized)
-versioned = serializer.version_pipeline(restored, {"version": "1.1"})
-```
-
-### ExecutionEngine
-
-Executes pipelines and manages lifecycle.
+## Overview
-**Methods:**
+The **Pipeline Module** lets you chain Semantica components into reproducible, fault-tolerant workflows with parallel execution and configurable error handling.
-- `execute_pipeline(pipeline, data=None, **options)` β€” Run pipeline
-- `pause_pipeline(pipeline_id)` β€” Pause execution
-- `resume_pipeline(pipeline_id)` β€” Resume execution
-- `stop_pipeline(pipeline_id)` β€” Stop execution
-- `get_pipeline_status(pipeline_id)` β€” Get status
-- `get_progress(pipeline_id)` β€” Get progress
+---
-**Example:**
+## Basic Pipeline
```python
-from semantica.pipeline import ExecutionEngine
-
-engine = ExecutionEngine(max_workers=4)
-result = engine.execute_pipeline(pipeline, data={"path": "document.pdf"})
-
-status = engine.get_pipeline_status(pipeline.name)
-progress = engine.get_progress(pipeline.name)
-
-engine.pause_pipeline(pipeline.name)
-engine.resume_pipeline(pipeline.name)
-engine.stop_pipeline(pipeline.name)
+from semantica.pipeline import Pipeline
+from semantica.ingest import FileIngestor
+from semantica.parse import DocumentParser
+from semantica.semantic_extract import NERExtractor
+from semantica.kg import GraphBuilder
+
+pipeline = Pipeline()
+pipeline.add_step("ingest", FileIngestor())
+pipeline.add_step("parse", DocumentParser())
+pipeline.add_step("extract", NERExtractor(method="llm", llm_provider=llm))
+pipeline.add_step("build_kg", GraphBuilder(merge_entities=True))
+
+result = pipeline.run("data/")
+kg = result.output
```
-### Failure Handling
-
-**Classes:** `FailureHandler`, `RetryHandler`, `FallbackHandler`, `ErrorRecovery`
-
-**FailureHandler Methods:**
-
-- `handle_step_failure(step, error, **options)`
-- `classify_error(error)`
-- `set_retry_policy(step_type, policy)`
-- `get_retry_policy(step_type)`
-- `retry_failed_step(step, error, **options)`
-- `get_error_history(step_name=None)`
-- `clear_error_history()`
-
-**Example:**
-
-```python
-from semantica.pipeline import FailureHandler, RetryPolicy, RetryStrategy
-
-handler = FailureHandler(default_max_retries=3, default_backoff_factor=2.0)
-policy = RetryPolicy(max_retries=5, strategy=RetryStrategy.EXPONENTIAL, initial_delay=1.0)
-handler.set_retry_policy("network", policy)
-
-classification = handler.classify_error(RuntimeError("timeout"))
-history_before = handler.get_error_history()
-handler.clear_error_history()
-```
-
-### Parallelism
-
-**Classes:** `ParallelismManager`, `ParallelExecutor`
-
-**ParallelismManager Methods:**
-
-- `execute_parallel(tasks, **options)`
-- `execute_pipeline_steps_parallel(steps, data, **options)`
-- `identify_parallelizable_steps(pipeline)`
-- `optimize_parallel_execution(pipeline, available_workers)`
+---
-**Example:**
+## Parallel Processing
```python
-from semantica.pipeline import ParallelismManager, Task, ParallelExecutor
+pipeline = Pipeline(workers=4) # run steps in parallel across documents
-def work(x):
- return x * 2
+pipeline.add_step("ingest", FileIngestor())
+pipeline.add_step("parse", DocumentParser())
+pipeline.add_step("extract", NERExtractor(), parallel=True, batch_size=10)
+pipeline.add_step("build", GraphBuilder())
-manager = ParallelismManager(max_workers=4)
-tasks = [Task(task_id=f"t{i}", handler=work, args=(i,)) for i in range(4)]
-results = manager.execute_parallel(tasks)
-
-executor = ParallelExecutor(max_workers=2)
-exec_results = executor.execute_parallel(tasks)
+result = pipeline.run("data/")
```
-### Resources
-
-**Class:** `ResourceScheduler`
-
-**Methods:**
-
-- `allocate_resources(pipeline, **options)`
-- `allocate_cpu(cores, pipeline_id, step_name=None)`
-- `allocate_memory(memory_gb, pipeline_id, step_name=None)`
-- `allocate_gpu(device_id, pipeline_id, step_name=None)`
-- `release_resources(allocations)`
-- `get_resource_usage()`
-- `optimize_resource_allocation(pipeline, **options)`
+---
-**Example:**
+## Retry & Error Handling
```python
-from semantica.pipeline import ResourceScheduler, ResourceType
-
-scheduler = ResourceScheduler()
-cpu = scheduler.allocate_cpu(cores=2, pipeline_id="p1")
-mem = scheduler.allocate_memory(memory_gb=1.0, pipeline_id="p1")
-usage = scheduler.get_resource_usage()
-scheduler.release_resources({cpu.allocation_id: cpu, mem.allocation_id: mem})
-```
-
-### Validation
-
-**Class:** `PipelineValidator`
-
-**Methods:**
-
-- `validate_pipeline(pipeline_or_builder, **options)`
-- `validate_step(step, **constraints)`
-- `check_dependencies(pipeline_or_builder)`
-- `validate_performance(pipeline, **options)`
-
-**Example:**
+from semantica.pipeline import Pipeline, RetryPolicy, FailureHandler
-```python
-from semantica.pipeline import PipelineValidator, PipelineBuilder
+retry = RetryPolicy(
+ max_retries=3,
+ backoff="exponential", # "fixed" | "linear" | "exponential"
+ initial_delay=1.0
+)
-builder = PipelineBuilder()
-builder.add_step("a", "type")
-builder.add_step("b", "type", dependencies=["a"])
+handler = FailureHandler(
+ strategy="skip", # "skip" | "stop" | "retry"
+ log_failures=True
+)
-validator = PipelineValidator()
-result = validator.validate_pipeline(builder)
-deps = validator.check_dependencies(builder)
-perf = validator.validate_performance(builder.build())
+pipeline = Pipeline(retry_policy=retry, failure_handler=handler)
```
-### Templates
-
-**Classes:** `PipelineTemplateManager`, `PipelineTemplate`
-
-**PipelineTemplateManager Methods:**
-
-- `get_template(template_name)`
-- `create_pipeline_from_template(template_name, **overrides)`
-- `register_template(template)`
-- `list_templates(category=None)`
-- `get_template_info(template_name)`
+---
-**Example:**
+## Progress Tracking
```python
-from semantica.pipeline import PipelineTemplateManager
-
-tm = PipelineTemplateManager()
-names = tm.list_templates()
-info = tm.get_template_info(names[0])
-builder = tm.create_pipeline_from_template(names[0])
-pipeline = builder.build()
-```
+# Print progress to console
+result = pipeline.run("data/", show_progress=True)
----
-
-## Configuration
-
-### Environment Variables
+# WebSocket progress (via Knowledge Explorer)
+result = pipeline.run("data/", websocket_port=8080)
-```bash
-export PIPELINE_MAX_WORKERS=4
-export PIPELINE_DEFAULT_TIMEOUT=300
-export PIPELINE_CHECKPOINT_DIR=./checkpoints
+print(f"Processed: {result.processed_count}")
+print(f"Failed: {result.failed_count}")
+print(f"Duration: {result.duration_seconds:.1f}s")
```
-### YAML Configuration
-
-This module does not include built-in YAML loaders. Use your own configuration system to populate arguments for `PipelineBuilder`, `ExecutionEngine`, and related classes.
-
---
-## Integration Examples
-
-### RAG-Style Pipeline
+## Pipeline DSL
```python
-from semantica.pipeline import PipelineBuilder, ExecutionEngine
+from semantica.pipeline import PipelineBuilder
-builder = (
+pipeline = (
PipelineBuilder()
- .add_step("ingest", "ingest")
- .add_step("chunk", "chunk", dependencies=["ingest"])
- .add_step("embed", "embed", dependencies=["chunk"])
- .add_step("store_vectors", "store_vectors", dependencies=["embed"])
+ .ingest(FileIngestor())
+ .parse(DocumentParser())
+ .normalize()
+ .extract(NERExtractor(method="llm", llm_provider=llm))
+ .extract_relations(RelationExtractor(method="llm", llm_provider=llm))
+ .build_kg(merge_entities=True)
+ .deduplicate(strategy="semantic_v2")
+ .export(format="turtle", path="output.ttl")
+ .build()
)
-pipeline = builder.build(name="RAGPipeline")
-engine = ExecutionEngine(max_workers=4)
-result = engine.execute_pipeline(pipeline, data={"path": "document.pdf"})
+result = pipeline.run("data/")
```
---
-### Incremental / Delta-Aware Pipeline
-
-Use `delta_mode` to process only the differences between two graph versions, drastically reducing compute costs for large datasets.
+## Saving & Loading Pipelines
```python
-from semantica.pipeline import PipelineBuilder, ExecutionEngine
+# Save pipeline definition
+pipeline.save("pipeline_config.yaml")
-builder = (
- PipelineBuilder()
- # Adding delta_mode=True tells the execution engine to intercept this step,
- # compute the diff between v1 and v2, and pass ONLY the delta payload to the handler.
- .add_step(
- "validate_diff",
- "validation",
- delta_mode=True,
- base_version_id="v1",
- target_version_id="v2",
- handler=diff_validator
- )
- .add_step(
- "alert_on_removals",
- "alerting",
- dependencies=["validate_diff"],
- handler=alert_handler
- )
-)
-
-pipeline = builder.build(name="IncrementalJob")
-engine = ExecutionEngine()
-
-# Execution requires version_manager and triplet_store injected via options
-# so the engine can resolve URIs and compute the graph differences natively.
-result = engine.execute_pipeline(
- pipeline,
- version_manager=my_version_manager,
- triplet_store=my_triplet_store
-)
+# Load and run
+pipeline = Pipeline.load("pipeline_config.yaml")
+result = pipeline.run("data/")
```
---
-## Best Practices
-
-1. **Idempotency**: Ensure steps are idempotent (can be run multiple times without side effects) to support retries.
-2. **Granularity**: Keep steps focused on a single task. Smaller steps are easier to debug and retry.
-3. **Context Passing**: Use the execution context to pass metadata between steps, not just return values.
-4. **Error Handling**: Always define specific exceptions for retries; don't retry on `ValueError` or `TypeError`.
-
----
-
-## Troubleshooting
-
-**Issue**: Pipeline stuck in `RUNNING` state.
-**Solution**: Check for deadlocks in dependency graph or infinite loops in steps. Use `timeout_seconds`.
-
-**Issue**: `PickleError` during parallel execution.
-**Solution**: Ensure all data passed between steps is serializable. Avoid passing open file handles or database connections.
-
----
-
-## Cookbook
-
-Interactive tutorials to learn pipeline orchestration:
-
-- **[Pipeline Orchestration](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/07_Pipeline_Orchestration.ipynb)**: Build robust, automated data processing pipelines
- - **Topics**: Workflows, automation, error handling, pipeline orchestration, DAG construction
- - **Difficulty**: Advanced
- - **Use Cases**: Complex multi-step workflows, production pipelines, ETL processes
-
## See Also
-- [Ingest Module](ingest.md) - Common first step
-- [Split Module](split.md) - Common processing step
-- [Vector Store Module](vector_store.md) - Common sink step
-
+<CardGroup cols={2}>
+ <Card title="Ingest" icon="database" href="ingest">
+ First step in most pipelines.
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Core extraction step.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ Graph construction step.
+ </Card>
+ <Card title="Export" icon="file-export" href="export">
+ Final output step.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/provenance.md b/docs/reference/provenance.md
index d1aed5e2..bd431d3c 100644
--- a/docs/reference/provenance.md
+++ b/docs/reference/provenance.md
@@ -1,737 +1,123 @@
-# Provenance Tracking Module
-
-**W3C PROV-O compliant provenance tracking for high-stakes domains requiring complete traceability**
-
-## Overview
-
-The Semantica provenance module provides W3C PROV-O compliant tracking for knowledge graphs, enabling complete end-to-end lineage from source documents to query responses. Designed for high-stakes domains where every decision must be explainable and auditable.
-
-<div class="grid cards" markdown>
-
-- :material-web:{ .lg .middle } **W3C PROV-O Compliant**
-
- ---
-
- Implements PROV-O ontology (prov:Entity, prov:Activity, prov:Agent, prov:wasDerivedFrom)
-
-- :material-all-inclusive:{ .lg .middle } **Complete Coverage**
-
- ---
-
- All 17 Semantica modules integrated for comprehensive tracking
-
-- :material-file-document:{ .lg .middle } **Source Tracking**
-
- ---
-
- Document identifiers, page numbers, sections, and direct quotes supported
-
-- :material-backup-restore:{ .lg .middle } **Backward Compatible**
-
- ---
-
- 100% backward compatible, opt-in only with zero breaking changes
-
-- :material-database:{ .lg .middle } **Multiple Storage**
-
- ---
-
- InMemory (fast) and SQLite (persistent) backends available
-
-- :material-share-variant:{ .lg .middle } **Bridge Axiom Support**
-
- ---
-
- Translation chain tracking for domain transformations (L1 β†’ L2 β†’ L3)
-
-- :material-shield-check:{ .lg .middle } **Integrity Verification**
-
- ---
-
- SHA-256 checksums for tamper detection and verification
-
-- :material-link-variant:{ .lg .middle } **Complete Lineage**
-
- ---
-
- End-to-end tracing from document to AI response
-
-</div>
-
-### Key Features
-
-- βœ… **W3C PROV-O Compliant** β€” Implements PROV-O ontology (prov:Entity, prov:Activity, prov:Agent, prov:wasDerivedFrom)
-- βœ… **All 17 Modules Integrated** β€” Complete coverage across Semantica
-- βœ… **Source Tracking** β€” Document identifiers, page numbers, sections, and direct quotes supported
-- βœ… **Zero Breaking Changes** β€” 100% backward compatible, opt-in only
-- βœ… **Multiple Storage Backends** β€” InMemory (fast) and SQLite (persistent)
-- βœ… **Bridge Axiom Support** β€” Translation chain tracking for domain transformations (L1 β†’ L2 β†’ L3)
-- βœ… **Integrity Verification** β€” SHA-256 checksums for tamper detection
-- βœ… **Complete Lineage Tracing** β€” End-to-end from document to response
-
---
-
-## Installation
-
-The provenance module is included with Semantica. No additional installation required.
-
-```python
-from semantica.provenance import ProvenanceManager
-```
-
+title: "Provenance Module"
+description: "W3C PROV-O compliant lineage tracking, source attribution, and audit trails across all 17 modules."
+icon: "link"
---
-## Core Components
-
-### ProvenanceManager
-
-Central manager for all provenance tracking operations.
-
-```python
-from semantica.provenance import ProvenanceManager
-
-# Initialize with in-memory storage (default)
-manager = ProvenanceManager()
-
-# Initialize with persistent SQLite storage
-manager = ProvenanceManager(storage_path="provenance.db")
-```
-
-**Key capabilities:**
-- Track entities and relationships with complete lineage
-- Store provenance data in memory or persistent SQLite storage
-- Query provenance information for audit and compliance
-- Maintain W3C PROV-O compliant records
-
-**Methods:**
-- `track_entity(entity_id, source, entity_type, **metadata)` β€” Track entity provenance
-- `track_relationship(relationship_id, source, subject, predicate, obj, **metadata)` β€” Track relationship provenance
-- `track_chunk(chunk_id, source_document, chunk_text, start_char, end_char, **metadata)` β€” Track document chunk provenance
-- `track_property_source(entity_id, property_name, value, source, **metadata)` β€” Track property-level provenance
-- `get_lineage(entity_id)` β€” Retrieve complete lineage for an entity
-- `get_statistics()` β€” Get provenance statistics
-- `get_all_entries()` β€” Retrieve all provenance entries
-
-### Storage Backends
-
-#### InMemoryStorage
-
-Fast, non-persistent storage for development and testing.
-
-```python
-from semantica.provenance import ProvenanceManager, InMemoryStorage
-
-manager = ProvenanceManager(storage=InMemoryStorage())
-```
-
-**Best for:**
-- Development and testing environments
-- Temporary provenance tracking
-- High-performance scenarios where persistence isn't required
-- Rapid prototyping and debugging
-
-#### SQLiteStorage
-
-Persistent storage for production use.
-
-```python
-from semantica.provenance import ProvenanceManager, SQLiteStorage
-
-storage = SQLiteStorage("provenance.db")
-manager = ProvenanceManager(storage=storage)
-```
-
-**Best for:**
-- Production deployments requiring persistence
-- Long-term provenance storage
-- Compliance and audit requirements
-- Multi-process environments
-
-### Data Schemas
-
-#### ProvenanceEntry
-
-Core data structure for provenance tracking.
-
-```python
-from semantica.provenance import ProvenanceEntry
-from datetime import datetime
-
-entry = ProvenanceEntry(
- entity_id="entity_1",
- source="document.pdf",
- timestamp=datetime.now(),
- entity_type="named_entity",
- metadata={"text": "Apple Inc.", "confidence": 0.95}
-)
-```
-
-#### SourceReference
-
-Structured source information with page and section details.
-
-```python
-from semantica.provenance import SourceReference
-
-source = SourceReference(
- document="research_paper.pdf",
- page=5,
- section="Results",
- confidence=0.98
-)
-```
+> W3C PROV-O compliant provenance tracking for high-stakes domains requiring complete traceability.
---
-## Module Integrations
-
-All Semantica modules have provenance-enabled versions. Enable tracking by setting `provenance=True`.
-
-### Semantic Extract
-
-```python
-from semantica.semantic_extract.semantic_extract_provenance import (
- NERExtractorWithProvenance,
- RelationExtractorWithProvenance,
- EventDetectorWithProvenance,
- CoreferenceResolverWithProvenance,
- TripletExtractorWithProvenance
-)
-
-# Named Entity Recognition with provenance
-ner = NERExtractorWithProvenance(provenance=True)
-entities = ner.extract(
- text="Apple Inc. was founded by Steve Jobs in Cupertino.",
- source="company_history.pdf"
-)
-
-# Access provenance manager
-prov_manager = ner._prov_manager
-lineage = prov_manager.get_lineage("entity_id")
-```
-
-**Tracks:** Entity text, labels, confidence scores, source documents, character positions, extraction timestamps
-
-### LLM Providers
-
-```python
-from semantica.llms.llms_provenance import (
- GroqLLMWithProvenance,
- OpenAILLMWithProvenance,
- HuggingFaceLLMWithProvenance,
- LiteLLMWithProvenance
-)
-
-# Groq LLM with provenance
-llm = GroqLLMWithProvenance(
- provenance=True,
- model="llama-3.1-70b"
-)
-
-response = llm.generate("What is artificial intelligence?")
-
-# Access cost and performance data
-stats = llm._prov_manager.get_statistics()
-```
-
-**Tracks:** Model name, prompt/completion tokens, API costs, latency, generation parameters, prompts and responses
-
-### Pipeline Execution
-
-```python
-from semantica.pipeline.pipeline_provenance import PipelineWithProvenance
-
-pipeline = PipelineWithProvenance(provenance=True)
-result = pipeline.run(data=input_data, source="input_file.json")
-```
-
-**Tracks:** Pipeline steps executed, duration, input/output data, execution status
-
-### Context Management
-
-```python
-from semantica.context.context_provenance import ContextManagerWithProvenance
-
-ctx = ContextManagerWithProvenance(provenance=True)
-ctx.add_context("Relevant background information", source="knowledge_base.txt")
-```
-
-**Tracks:** Context additions, sources, timestamps
-
-### Document Ingestion
-
-```python
-from semantica.ingest.ingest_provenance import PDFIngestorWithProvenance
-
-ingestor = PDFIngestorWithProvenance(provenance=True)
-documents = ingestor.ingest("research_paper.pdf")
-```
-
-**Tracks:** File paths, page counts, file metadata, ingestion timestamps
-
-### Embeddings Generation
-
-```python
-from semantica.embeddings.embeddings_provenance import EmbeddingGeneratorWithProvenance
-
-embedder = EmbeddingGeneratorWithProvenance(
- provenance=True,
- model="sentence-transformers/all-mpnet-base-v2"
-)
-embeddings = embedder.embed(["Text 1", "Text 2"], source="corpus.txt")
-```
-
-**Tracks:** Model name, embedding dimensions, generation timestamps
-
-### Graph Store
-
-```python
-from semantica.graph_store.graph_store_provenance import GraphStoreWithProvenance
-
-store = GraphStoreWithProvenance(provenance=True)
-store.add_node(entity_node, source="knowledge_graph.json")
-```
-
-**Tracks:** Nodes added, node properties, graph structure changes
-
-### Vector Store
-
-```python
-from semantica.vector_store.vector_store_provenance import VectorStoreWithProvenance
-
-store = VectorStoreWithProvenance(provenance=True)
-store.add_vectors(embedding_vectors, source="embeddings.npy")
-```
-
-**Tracks:** Vectors stored, dimensions, storage timestamps
-
-### Triplet Store
-
-```python
-from semantica.triplet_store.triplet_store_provenance import TripletStoreWithProvenance
-
-store = TripletStoreWithProvenance(provenance=True)
-store.add_triplet("Steve_Jobs", "founded", "Apple_Inc", source="knowledge_base.ttl")
-```
-
-**Tracks:** Subject, predicate, object, confidence scores, timestamps
-
-### Other Modules
-
-All remaining modules follow the same pattern:
+## Overview
-- **Reasoning** β€” `ReasoningEngineWithProvenance`
-- **Conflicts** β€” `SourceTrackerWithUnifiedBackend`
-- **Deduplication** β€” `DeduplicatorWithProvenance`
-- **Export** β€” `ExporterWithProvenance`
-- **Parse** β€” `ParserWithProvenance`
-- **Normalize** β€” `NormalizerWithProvenance`
-- **Ontology** β€” `OntologyManagerWithProvenance`
-- **Visualization** β€” `VisualizerWithProvenance`
+The **Provenance Module** tracks the full lineage of every fact β€” from raw ingestion through extraction, reasoning, and export. Compliant with W3C PROV-O, suitable for HIPAA, SOX, GDPR, and FDA 21 CFR Part 11 environments.
---
-## Usage Examples
-
-### Basic Entity Tracking
+## ProvenanceManager
```python
from semantica.provenance import ProvenanceManager
manager = ProvenanceManager()
-# Track entity
+# Track an entity
manager.track_entity(
- entity_id="entity_1",
- source="document.pdf",
- entity_type="organization",
- metadata={
- "name": "Apple Inc.",
- "confidence": 0.95,
- "extraction_method": "NER"
- }
+ entity_id="apple_inc",
+ source="annual_report_2023.pdf",
+ entity_type="Organization",
+ extraction_method="llm",
+ confidence=0.98
)
-# Retrieve lineage
-lineage = manager.get_lineage("entity_1")
-print(f"Source: {lineage['source']}")
-print(f"Timestamp: {lineage['timestamp']}")
-print(f"Metadata: {lineage['metadata']}")
-```
-
-### Relationship Tracking
-
-```python
-# Track entities
-manager.track_entity("steve_jobs", "biography.pdf", "person")
-manager.track_entity("apple_inc", "biography.pdf", "organization")
-
-# Track relationship
+# Track a relationship
manager.track_relationship(
- relationship_id="rel_1",
- source="biography.pdf",
- subject="steve_jobs",
- predicate="founded",
- obj="apple_inc",
- metadata={"confidence": 0.92}
-)
-```
-
-### Lineage Chain Tracking
-
-```python
-# Create lineage chain: document β†’ chunk β†’ entity
-manager.track_entity("doc_1", "research_paper.pdf", "document")
-
-manager.track_chunk(
- chunk_id="chunk_1",
- source_document="doc_1",
- chunk_text="Sample text content",
- start_char=0,
- end_char=100
+ rel_id="steve_jobs_founded_apple",
+ source="annual_report_2023.pdf",
+ extraction_method="llm",
+ confidence=0.92
)
-manager.track_entity(
- entity_id="entity_1",
- source="chunk_1",
- entity_type="named_entity",
- metadata={"text": "Apple"}
-)
-
-# Retrieve complete lineage
-lineage = manager.get_lineage("entity_1")
-print(f"Lineage chain: {lineage['lineage_chain']}")
-```
-
-### Property-Level Provenance
-
-```python
-from semantica.provenance import SourceReference
-
-# Track entity
-manager.track_entity("company_1", "doc.pdf", "organization")
-
-# Track property sources
-manager.track_property_source(
- entity_id="company_1",
- property_name="revenue",
- value="$394.3B",
- source=SourceReference(
- document="annual_report_2023.pdf",
- page=5,
- section="Financial Summary",
- confidence=0.98
- )
-)
-
-manager.track_property_source(
- entity_id="company_1",
- property_name="employees",
- value="500",
- source=SourceReference(
- document="company_profile.pdf",
- page=2,
- confidence=0.90
- )
-)
-```
-
-### End-to-End Workflow
-
-```python
-from semantica.provenance import ProvenanceManager
-from semantica.ingest.ingest_provenance import PDFIngestorWithProvenance
-from semantica.semantic_extract.semantic_extract_provenance import NERExtractorWithProvenance
-from semantica.llms.llms_provenance import GroqLLMWithProvenance
-from semantica.graph_store.graph_store_provenance import GraphStoreWithProvenance
-
-# Initialize
-manager = ProvenanceManager()
-
-# Step 1: Ingest
-ingestor = PDFIngestorWithProvenance(provenance=True)
-documents = ingestor.ingest("research_paper.pdf")
-
-# Step 2: Extract
-ner = NERExtractorWithProvenance(provenance=True)
-entities = ner.extract(documents[0].text, source="research_paper.pdf")
-
-# Step 3: LLM Analysis
-llm = GroqLLMWithProvenance(provenance=True)
-summary = llm.generate(f"Summarize: {documents[0].text[:500]}")
-
-# Step 4: Store
-graph = GraphStoreWithProvenance(provenance=True)
-for entity in entities:
- graph.add_node(entity, source="research_paper.pdf")
-
-# Step 5: Retrieve provenance
-lineage = ner._prov_manager.get_lineage("entity_id")
-stats = ner._prov_manager.get_statistics()
-print(f"Total operations: {stats['total_entries']}")
+# Get full lineage
+lineage = manager.get_lineage("apple_inc")
+print(f"Source: {lineage.source}")
+print(f"Extracted: {lineage.extracted_at}")
+print(f"Method: {lineage.extraction_method}")
```
---
-## Bridge Axioms
-
-Bridge axioms enable translation chain tracking across multiple abstraction layers.
+## Activity Tracking
```python
-from semantica.provenance.bridge_axiom import BridgeAxiom, TranslationChain
-
-# Create bridge axiom
-axiom = BridgeAxiom(
- source_layer="L1_ecological",
- target_layer="L2_financial",
- translation_rule="fish_biomass_to_revenue",
- confidence=0.89
-)
-
-# Add provenance
-axiom.add_source_provenance(
- document="DOI:10.1371/journal.pone.0023601",
- location="Figure 2",
- quote="Total fish biomass increased by 463%"
+# Track a pipeline activity
+activity_id = manager.start_activity(
+ activity_type="ner_extraction",
+ used=["annual_report_2023.pdf"],
+ generated=["apple_inc", "steve_jobs"]
)
-# Create translation chain
-chain = TranslationChain()
-chain.add_axiom(axiom)
+manager.end_activity(activity_id)
-# Track complete chain
-provenance_data = chain.get_complete_provenance()
+# Query activities
+activities = manager.get_activities(entity_id="apple_inc")
```
-**Use Cases:**
-- Blue Finance: Ecological data β†’ Financial metrics
-- Healthcare: Clinical data β†’ Treatment recommendations
-- Legal: Evidence β†’ Legal conclusions
-- Pharmaceutical: Research data β†’ Drug efficacy claims
-
---
-## Best Practices
-
-### 1. Always Provide Source Information
-
-```python
-# βœ… GOOD - Provides source
-entities = ner.extract(text, source="document.pdf")
-
-# ❌ BAD - No source information
-entities = ner.extract(text)
-```
-
-### 2. Use Descriptive Entity IDs
-
-```python
-# βœ… GOOD - Descriptive IDs
-manager.track_entity("company_apple_inc", source, "organization")
-
-# ❌ BAD - Generic IDs
-manager.track_entity("entity_1", source, "organization")
-```
-
-### 3. Include Rich Metadata
+## Lineage Graph
```python
-# βœ… GOOD - Rich metadata
-manager.track_entity(
- entity_id="person_steve_jobs",
- source="biography.pdf",
- entity_type="person",
- metadata={
- "full_name": "Steve Jobs",
- "birth_year": 1955,
- "confidence": 0.95,
- "extraction_method": "NER_spacy"
- }
-)
-```
-
-### 4. Enable Provenance for High-Stakes Operations
+# Full lineage from source to current state
+lineage_graph = manager.get_lineage_graph("apple_inc")
-```python
-# For high-stakes requirements
-llm = GroqLLMWithProvenance(provenance=True) # Track all LLM calls
-ner = NERExtractorWithProvenance(provenance=True) # Track all extractions
-```
-
-### 5. Use Persistent Storage for Production
-
-```python
-from semantica.provenance import ProvenanceManager, SQLiteStorage
-
-# Use SQLite for persistence
-storage = SQLiteStorage("provenance.db")
-manager = ProvenanceManager(storage=storage)
+for node in lineage_graph.nodes:
+ print(f"{node.id}: {node.type} β€” {node.timestamp}")
```
---
-## Performance
-
-### Benchmarks
-
-- **Entity tracking:** Fast per operation
-- **Lineage retrieval:** Quick retrieval for long chains
-- **Batch operations:** High-throughput batch processing
-- **Storage:** InMemory (fastest), SQLite (persistent)
-
-### Optimization Tips
-
-1. **Batch Operations:** Use batch methods for multiple entities
-2. **Selective Tracking:** Only track provenance for critical entities
-3. **Storage Choice:** Use InMemory for development, SQLite for production
-4. **Index Optimization:** SQLite automatically indexes entity_id and source_document
-
----
-
-## Compliance Standards Support
-
-The provenance module provides **technical infrastructure** that supports compliance efforts:
-
-- **W3C PROV-O** β€” Implements PROV-O ontology data structures and relationships
-- **FDA 21 CFR Part 11** β€” Provides audit trails, checksums, and temporal tracking for electronic records
-- **SOX** β€” Enables financial data lineage tracking and integrity verification
-- **HIPAA** β€” Supports healthcare data integrity through checksums and source tracking
-- **TNFD** β€” Enables bridge axiom tracking for nature-to-financial translations
-
-**Important:** This module provides the *technical capabilities* for compliance. Organizations must implement additional policies, procedures, validation, and controls to meet specific regulatory requirements. Semantica does not provide regulatory certification or legal compliance guarantees.
-
----
-
-## API Reference
-
-### ProvenanceManager
-
-#### `__init__(storage=None, storage_path=None)`
-
-Initialize provenance manager.
-
-**Parameters:**
-- `storage` (ProvenanceStorage, optional): Storage backend instance
-- `storage_path` (str, optional): Path for SQLite storage
-
-#### `track_entity(entity_id, source, entity_type, **metadata)`
-
-Track entity provenance.
-
-**Parameters:**
-- `entity_id` (str): Unique identifier for entity
-- `source` (str): Source document or identifier
-- `entity_type` (str): Type of entity
-- `**metadata`: Additional metadata
-
-**Returns:** ProvenanceEntry
-
-#### `track_relationship(relationship_id, source, subject, predicate, obj, **metadata)`
+## W3C PROV-O Export
-Track relationship provenance.
-
-**Parameters:**
-- `relationship_id` (str): Unique identifier for relationship
-- `source` (str): Source document
-- `subject` (str): Subject entity ID
-- `predicate` (str): Relationship type
-- `obj` (str): Object entity ID
-- `**metadata`: Additional metadata
-
-**Returns:** ProvenanceEntry
-
-#### `track_chunk(chunk_id, source_document, chunk_text, start_char, end_char, **metadata)`
-
-Track document chunk provenance.
-
-**Parameters:**
-- `chunk_id` (str): Unique identifier for chunk
-- `source_document` (str): Source document ID
-- `chunk_text` (str): Text content of chunk
-- `start_char` (int): Start character position
-- `end_char` (int): End character position
-- `**metadata`: Additional metadata
-
-**Returns:** ProvenanceEntry
-
-#### `get_lineage(entity_id)`
-
-Retrieve complete lineage for an entity.
-
-**Parameters:**
-- `entity_id` (str): Entity identifier
-
-**Returns:** dict with lineage information
-
-#### `get_statistics()`
-
-Get provenance statistics.
-
-**Returns:** dict with statistics (total_entries, entities, relationships, chunks)
-
----
-
-## Testing
-
-Run the provenance test suite:
-
-```bash
-# All provenance tests
-pytest tests/provenance/ -v
-
-# Specific test categories
-pytest tests/provenance/test_manager.py -v
-pytest tests/provenance/test_storage.py -v
-pytest tests/provenance/test_bridge_axiom.py -v
-pytest tests/provenance/test_integration.py -v
+```python
+# Export provenance as W3C PROV-O Turtle
+prov_ttl = manager.export_prov_o("apple_inc", format="turtle")
-# Module integration tests
-pytest tests/provenance/test_semantic_extract_provenance.py -v
-pytest tests/provenance/test_llms_provenance.py -v
+# Export full provenance graph
+manager.export_all(path="provenance.ttl", format="turtle")
```
---
-## Troubleshooting
-
-### Provenance Not Being Tracked
-
-```python
-# Check if provenance is enabled
-print(f"Provenance enabled: {obj.provenance}")
-print(f"Manager available: {obj._prov_manager is not None}")
-```
+## Integration with Other Modules
-### Performance Issues
+Provenance is automatically tracked when using `GraphBuilderWithProvenance`:
```python
-# Use batch operations
-entities = [{"id": f"entity_{i}"} for i in range(1000)]
-manager.track_entities_batch(entities, source="doc_1")
-```
+from semantica.kg import GraphBuilderWithProvenance
-### Storage Growing Too Large
+builder = GraphBuilderWithProvenance(provenance=True)
+result = builder.build_single_source(graph_data)
-```python
-# Use separate databases for different time periods
-manager_2026 = ProvenanceManager(storage_path="provenance_2026.db")
+# The builder records what was used to produce each node/edge
+lineage = result.provenance_manager.get_lineage("entity_id")
```
---
## See Also
-- [Provenance Usage Guide](https://github.com/Hawksight-AI/semantica/blob/main/semantica/provenance/provenance_usage.md) β€” Comprehensive usage documentation
-- [Change Management](change_management.md) β€” Version control and audit trails
-- [Conflicts Module](conflicts.md) β€” Source tracking and conflict resolution
-- [Knowledge Graph](kg.md) β€” Entity and relationship tracking
-
----
-
-## License
-
-MIT License - See [LICENSE](../../LICENSE) for details.
-
-## Support
-
-For issues or questions, please open an issue on GitHub or join our [Discord](https://discord.gg/sV34vps5hH).
+<CardGroup cols={2}>
+ <Card title="Change Management" icon="clock-rotate-left" href="change_management">
+ Version control and audit trails.
+ </Card>
+ <Card title="Ingest" icon="database" href="ingest">
+ Provenance begins at ingestion.
+ </Card>
+ <Card title="Export" icon="file-export" href="export">
+ Include provenance in exports.
+ </Card>
+ <Card title="Context" icon="brain" href="context">
+ Decision provenance via AgentContext.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.md
index 85fe4d32..f4afd6a4 100644
--- a/docs/reference/reasoning.md
+++ b/docs/reference/reasoning.md
@@ -1,241 +1,186 @@
-# Reasoning
-
-> **Simplified reasoning module supporting rule-based inference, SPARQL, and high-performance pattern matching.**
-
---
-
-## 🎯 Overview
-
-The **Reasoning Module** provides logical inference capabilities for deriving new knowledge from existing facts. It supports rule-based inference, SPARQL-based reasoning, and high-performance pattern matching.
-
-### What is Reasoning?
-
-**Reasoning** is the process of deriving new facts from existing knowledge using logical rules. For example:
-- **Given**: `` `Parent(Alice, Bob)` `` and `` `Parent(Bob, Charlie)` ``
-- **Rule**: `` `IF Parent(?x, ?y) AND Parent(?y, ?z) THEN Grandparent(?x, ?z)` ``
-- **Inferred**: `` `Grandparent(Alice, Charlie)` ``
-
-### Why Use the Reasoning Module?
-
-- **Knowledge Discovery**: Find implicit relationships not explicitly stored
-- **Query Expansion**: Answer queries that require inference
-- **Validation**: Check logical consistency of knowledge graphs
-- **Explanation**: Understand how facts were derived
-- **Rule-Based Logic**: Define domain-specific inference rules
-
-### How It Works
-
-1. **Rule Definition**: Define inference rules (IF-THEN patterns)
-2. **Fact Matching**: Match facts against rule conditions
-3. **Variable Binding**: Bind variables in rules to actual entities
-4. **Inference**: Derive new facts from matched rules
-5. **Explanation**: Generate explanations for inferred facts
-
-<div class="grid cards" markdown>
-
-- :material-brain:{ .lg .middle } **Rule-based Inference**
-
- ---
-
- Forward-chaining inference engine with variable substitution
-
-- :material-database-search:{ .lg .middle } **SPARQL Reasoning**
-
- ---
-
- Query expansion and property chain inference for RDF graphs
-
-- :material-flash:{ .lg .middle } **Rete Algorithm**
-
- ---
-
- High-performance pattern matching for large rule sets
-
-- :material-text-box-search:{ .lg .middle } **Explanation**
-
- ---
-
- Generate natural language explanations for inferred facts
-
-</div>
-
-!!! tip "When to Use"
- - **Inference**: Deriving new facts from existing data (e.g., `` `Parent(A,B) & Parent(B,C) -> Grandparent(A,C)` ``)
- - **Query Expansion**: Finding results that aren't explicitly stored but implied
- - **Explanation**: Understanding the reasoning path for any derived fact
- - **Validation**: Checking logical consistency of the knowledge graph
-
+title: "Reasoning Module"
+description: "Forward chaining, Rete, deductive, abductive, SPARQL, and Datalog reasoning with explainable inference paths."
+icon: "microchip"
---
-## βš™οΈ Algorithms Used
-
-### Forward Chaining
-
-**Purpose**: Derive new facts from existing knowledge using logical rules.
+> Logical inference engine supporting rule-based inference, SPARQL, Rete, and Datalog reasoning.
-**How it works**:
+---
-- **Variable Substitution**: Supports patterns like `` `Person(?x)` `` to match facts and bind variables
-- **Recursive Inference**: Continues deriving facts until no new information can be found
-- **Priority-based Execution**: Rules can be prioritized to control the inference flow
+## Overview
+
+The **Reasoning Module** derives new knowledge from existing facts using logical rules. All engines produce **explainable inference paths** β€” not black-box conclusions.
+
+<CardGroup cols={2}>
+ <Card title="Rule-Based Inference" icon="brain">
+ Forward-chaining inference with variable substitution.
+ </Card>
+ <Card title="SPARQL Reasoning" icon="database">
+ Query expansion and property chain inference over RDF graphs.
+ </Card>
+ <Card title="Rete Algorithm" icon="bolt">
+ High-performance pattern matching for large rule sets.
+ </Card>
+ <Card title="Datalog Engine" icon="code">
+ Recursive Horn clause rules with bottom-up fixpoint semantics (v0.4.0).
+ </Card>
+</CardGroup>
-**Complexity**: `` `O(n * m)` `` where n is the number of facts and m is the number of rules
+---
-**Example**:
+## ReasoningEngine (Forward Chaining)
```python
-# Forward chaining implementation
-reasoner = Reasoner()
-rules = ["IF Person(?x) THEN Human(?x)"]
-facts = ["Person(John)"]
-new_facts = reasoner.infer_facts(facts, rules)
+from semantica.reasoning import ReasoningEngine
+
+engine = ReasoningEngine()
+engine.add_rule({
+ "if": [
+ {"subject": "?person", "predicate": "parent_of", "object": "?child"},
+ {"subject": "?child", "predicate": "parent_of", "object": "?grandchild"}
+ ],
+ "then": {"subject": "?person", "predicate": "grandparent_of", "object": "?grandchild"}
+})
+
+inferences = engine.infer(kg)
+for inf in inferences:
+ print(f"{inf['subject']} {inf['predicate']} {inf['object']}")
+ print(f" Derived via: {inf['explanation']}")
```
-### Rete Algorithm
+---
-**Purpose**: High-performance pattern matching for large rule sets with frequent fact updates.
+## ReteEngine (High Performance)
-**How it works**:
+```python
+from semantica.reasoning import ReteEngine
-- **Alpha Nodes**: Filter facts by single attributes (e.g., `` `type=Person` ``)
-- **Beta Nodes**: Join results from Alpha nodes (e.g., `` `Person.id == Parent.child_id` ``)
-- **Memory**: Stores partial matches to avoid re-computation
-- **Efficiency**: Optimal for scenarios with many rules and frequent fact updates
+engine = ReteEngine()
+engine.load_rules("rules/domain_rules.json")
+results = engine.run(kg)
+```
-**Complexity**: `` `O(n + m)` `` where n is the number of facts and m is the number of rules (amortized)
+The Rete algorithm efficiently evaluates large rule sets by caching partial matches β€” far faster than naive forward chaining for hundreds of rules.
---
-## Main Classes
-
-### Reasoner (Facade)
+## DeductiveEngine
-The high-level interface for the reasoning module.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `` `infer_facts(facts, rules)` `` | Derive new facts from initial state |
-| `` `backward_chain(goal)` `` | Prove a goal using backward chaining |
-| `` `add_rule(rule)` `` | Add a new inference rule |
-| `` `add_fact(fact)` `` | Add a fact to working memory |
-| `` `clear()` `` | Reset the reasoner state |
+```python
+from semantica.reasoning import DeductiveEngine
-### ReteEngine
+engine = DeductiveEngine()
+engine.add_axiom("Person", "is_a", "Agent")
+engine.add_axiom("Employee", "is_a", "Person")
-High-performance pattern matching engine.
+# Infer: Employee is_a Agent (transitivity)
+inferences = engine.close_under_transitivity(kg)
+```
-**Methods:**
+---
-| Method | Description |
-|--------|-------------|
-| `` `build_network(rules)` `` | Compile rules into a Rete network |
-| `` `add_fact(fact)` `` | Propagate fact through the network |
-| `` `match_patterns()` `` | Get triggered rules |
+## AbductiveEngine
-### ExplanationGenerator
+```python
+from semantica.reasoning import AbductiveEngine
-Explains *why* a fact was inferred.
+engine = AbductiveEngine()
+hypotheses = engine.explain(
+ observation=("apple_inc", "high_revenue", True),
+ knowledge_graph=kg
+)
-**Methods:**
+for h in hypotheses:
+ print(f"Hypothesis: {h['explanation']} (probability: {h['probability']:.2f})")
+```
-| Method | Description |
-|--------|-------------|
-| `` `generate_explanation(result)` `` | Generate reasoning trace for an InferenceResult |
+Abductive reasoning infers the most likely explanation for an observation given the current knowledge graph.
---
-## Usage Examples
+## DatalogEngine (v0.4.0)
-### Simple Rule-based Inference
+Pure-Python bottom-up semi-naive fixpoint evaluation for recursive Horn clause rules.
```python
-from semantica.reasoning import Reasoner
+from semantica.reasoning import DatalogEngine
-reasoner = Reasoner()
+datalog = DatalogEngine()
-# Define rules
-rules = [
- "IF Person(?x) THEN Human(?x)",
- "IF Human(?x) AND Parent(?x, ?y) THEN Human(?y)"
-]
+# Add facts
+datalog.add_fact("parent(alice, bob).")
+datalog.add_fact("parent(bob, charlie).")
-# Initial facts
-facts = ["Person(John)", "Parent(John, Jane)"]
+# Add recursive rule
+datalog.add_rule("ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).")
+datalog.add_rule("ancestor(X, Y) :- parent(X, Y).")
-# Run inference
-new_facts = reasoner.infer_facts(facts, rules)
-# Result: ["Human(John)", "Human(Jane)"]
+# Query
+results = datalog.query("ancestor(alice, ?)")
+# Returns: [("charlie",), ("bob",)]
```
-### Goal-driven Reasoning (Backward Chaining)
+<Note>
+ Datalog termination is guaranteed β€” the engine detects fixpoint convergence and stops. No infinite loops.
+</Note>
+
+---
+
+## SPARQLReasoner
```python
-from semantica.reasoning import Reasoner
+from semantica.reasoning import SPARQLReasoner
-reasoner = Reasoner()
-reasoner.add_rule("IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)")
-reasoner.add_fact("Parent(Alice, Bob)")
-reasoner.add_fact("Parent(Bob, Charlie)")
+reasoner = SPARQLReasoner(graph=rdf_graph)
-# Prove a goal
-proof = reasoner.backward_chain("Grandparent(Alice, Charlie)")
+query = """
+SELECT ?person ?company WHERE {
+ ?person :founded ?company .
+ ?company :located_in :SiliconValley .
+}
+"""
-if proof:
- print(f"Proven: {proof.conclusion}")
- print(f"Steps: {proof.premises}")
+results = reasoner.query(query)
```
-### Knowledge Graph Enrichment
+Also supports property chain inference:
```python
-from semantica.reasoning import Reasoner
-from semantica.kg import GraphBuilder
-
-# 1. Define Rules
-rules = [
- "IF Sibling(?x, ?y) THEN Sibling(?y, ?x)",
- "IF Ancestor(?x, ?y) AND Ancestor(?y, ?z) THEN Ancestor(?x, ?z)"
-]
-
-# 2. Build Graph and Run Inference
-builder = GraphBuilder()
-kg = builder.build(sources=data)
-
-reasoner = Reasoner()
-# Infer new facts from entities and relationships
-inferred = reasoner.infer_facts(kg["entities"] + kg["relationships"], rules)
-
-# 3. Update Graph with Inferred Facts
-for fact_str in inferred:
- # Add new inferred facts back to the graph
- # For a production app, you'd parse these into entities/relationships
- kg["entities"].append({"type": "InferredFact", "name": fact_str})
+reasoner.add_property_chain("knows", ["friend_of", "colleague_of"])
+inferences = reasoner.infer_property_chains()
```
---
-## Best Practices
-
-1. **Limit Recursion**: Be careful with recursive rules (e.g., `` `A(x,y) -> A(y,x)` ``) which can cause infinite loops in naive implementations
-2. **Use Rete for Scale**: For >100 rules or >10k facts, always use the Rete engine
-3. **Materialize vs. Query**: Materialize (pre-compute) for read-heavy workloads; Query-rewrite for write-heavy workloads
-4. **Validate Rules**: Ensure rules are logically consistent to avoid exploding the fact space
+## Built-In Rule Templates
----
+```python
+from semantica.reasoning import ReasoningEngine, RuleTemplates
-## Cookbook
+engine = ReasoningEngine()
-Interactive tutorials to learn reasoning and inference:
+# Apply common logical patterns
+engine.apply_template(RuleTemplates.TRANSITIVITY, predicate="located_in")
+engine.apply_template(RuleTemplates.SYMMETRY, predicate="knows")
+engine.apply_template(RuleTemplates.INVERSE, predicate1="parent_of", predicate2="child_of")
+```
-- **[Reasoning and Inference](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb)**: Use logical reasoning to infer new knowledge from existing facts
- - **Topics**: Logic rules, inference engines, forward chaining, SPARQL reasoning, Rete algorithm
- - **Difficulty**: Advanced
- - **Use Cases**: Deriving new facts, query expansion, logical validation
+---
## See Also
-- [Ontology Module](ontology.md) - Source of schema-based rules
-- [Triplet Store Module](triplet_store.md) - Backend for SPARQL reasoning
-- [Modules Guide](../modules.md#quality-assurance) - Consistency checking overview
+<CardGroup cols={2}>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The knowledge graph being reasoned over.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Ontology rules that constrain reasoning.
+ </Card>
+ <Card title="SPARQL / Triplet Store" icon="database" href="triplet_store">
+ RDF backend for SPARQL reasoning.
+ </Card>
+ <Card title="Context" icon="brain" href="context">
+ Uses reasoning for agent intelligence.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/seed.md b/docs/reference/seed.md
index d43b36bc..899f5f45 100644
--- a/docs/reference/seed.md
+++ b/docs/reference/seed.md
@@ -1,239 +1,158 @@
-# Seed
-
-> **Seed data management system for initializing Knowledge Graphs from verified sources.**
-
---
-
-## 🎯 Overview
-
-The **Seed Module** provides a system for initializing Knowledge Graphs with verified, structured data from trusted sources. It enables bootstrapping knowledge graphs with reference data, taxonomies, and verified entities.
-
-### What is Seed Data?
-
-**Seed data** is verified, structured data used to bootstrap or enhance knowledge graphs. Examples include:
-
-- **Taxonomies**: Hierarchical classifications (product categories, organizational structures)
-- **Reference Data**: Immutable reference information (countries, codes, standards)
-- **Verified Entities**: Pre-validated entities from authoritative sources
-- **Foundation Graphs**: Initial graph structures to build upon
-
-### Why Use the Seed Module?
-
-- **Bootstrap KGs**: Start with verified data instead of empty graphs
-- **Quality Assurance**: Use trusted, validated data sources
-- **Faster Development**: Skip initial data extraction for known entities
-- **Data Integration**: Merge seed data with extracted data
-- **Versioning**: Manage different versions of seed data
-
-### How It Works
-
-1. **Load Seed Data**: Load from CSV, JSON, databases, or APIs
-2. **Validate**: Validate data quality and schema compliance
-3. **Transform**: Convert to knowledge graph format
-4. **Merge**: Integrate with extracted data using configurable strategies
-5. **Version**: Track versions of seed data sources
-
-<div class="grid cards" markdown>
-
-- :material-database-import:{ .lg .middle } **Multi-Source Loading**
-
- ---
-
- Load seed data from CSV, JSON, Databases, and APIs
-
-- :material-graph-outline:{ .lg .middle } **Foundation Graph**
-
- ---
-
- Create reliable foundation graphs to bootstrap your KG
-
-- :material-merge:{ .lg .middle } **Data Integration**
-
- ---
-
- Merge seed data with extracted data using configurable strategies
-
-- :material-check-all:{ .lg .middle } **Validation**
-
- ---
-
- Validate seed data quality and schema compliance
-
-- :material-git:{ .lg .middle } **Versioning**
-
- ---
-
- Manage versions of seed data sources
-
-- :material-export:{ .lg .middle } **Export**
-
- ---
-
- Export seed data to standard formats
-
-</div>
-
-!!! tip "When to Use"
- - **Bootstrapping**: When starting a new KG and you have existing structured data (taxonomies, user lists, product catalogs).
- - **Reference Data**: To load immutable reference data (countries, codes, constants).
- - **Testing**: To load consistent test datasets for development.
-
+title: "Seed Module"
+description: "Seed data management for initializing Knowledge Graphs from trusted, verified sources."
+icon: "database"
---
-## βš™οΈ Algorithms Used
-
-### Data Loading
+> Bootstrap Knowledge Graphs with verified taxonomies, reference data, and foundation graphs.
-**Purpose**: Load seed data from various formats efficiently.
+---
-**How it works**:
+## Overview
+
+The **Seed Module** provides a system for initializing Knowledge Graphs with verified, structured data from trusted sources β€” enabling you to start with a reliable foundation rather than an empty graph.
+
+<CardGroup cols={3}>
+ <Card title="Multi-Source Loading" icon="database">
+ Load seed data from CSV, JSON, databases, and APIs.
+ </Card>
+ <Card title="Foundation Graph" icon="diagram-project">
+ Build a reliable KG foundation to bootstrap extraction.
+ </Card>
+ <Card title="Data Integration" icon="code-merge">
+ Merge seed data with extracted data using configurable strategies.
+ </Card>
+ <Card title="Validation" icon="circle-check">
+ Validate seed data quality and schema compliance.
+ </Card>
+ <Card title="Versioning" icon="code-branch">
+ Manage and track versions of seed data sources.
+ </Card>
+ <Card title="Export" icon="file-export">
+ Export seed data to standard formats.
+ </Card>
+</CardGroup>
+
+<Tip>
+**When to use the Seed Module:**
+- **Bootstrapping** β€” you have existing structured data (taxonomies, user lists, product catalogs) and want to build on them.
+- **Reference data** β€” loading immutable reference information (countries, codes, constants).
+- **Testing** β€” loading consistent datasets for development and CI.
+</Tip>
-- **Format Detection**: Auto-detection of CSV delimiters, JSON structure
-- **Streaming**: Row-by-row processing for large files
-- **Normalization**: Type conversion and encoding handling
+---
-### Integration & Merging
+## SeedDataManager
-**Purpose**: Merge seed data with extracted data using configurable strategies.
+```python
+from semantica.seed import SeedDataManager
-**How it works**:
+manager = SeedDataManager()
+manager.register_source("countries", "csv", "data/countries.csv")
+foundation_kg = manager.create_foundation_graph()
+```
-- **Seed-First Strategy**: Seed data overrides extracted data (Trust Seed)
-- **Extracted-First Strategy**: Extracted data overrides seed (Trust Extraction)
-- **Smart Merge**: Property-level merging with conflict resolution
-- **ID Matching**: Entity resolution between seed and extracted entities
+| Method | Description |
+|--------|-------------|
+| `register_source(name, format, location)` | Add a data source |
+| `create_foundation_graph()` | Build KG from registered sources |
+| `validate_quality(seed_data)` | Check data quality |
+| `integrate_with_extracted(seed, extracted)` | Merge seed and extracted graphs |
+| `export_seed_data(path, format)` | Export seed data |
-### Validation
+---
-**Purpose**: Validate seed data quality and schema compliance.
+## SeedDataSource
-**How it works**:
+```python
+from semantica.seed import SeedDataSource
-- **Schema Validation**: Template-based structure checking
-- **Constraint Checking**: Required field and type validation
-- **Consistency Check**: Reference integrity (relationships point to existing entities)
+source = SeedDataSource(
+ name="taxonomy",
+ type="json", # "csv" | "json" | "api" | "sql"
+ path="taxonomy.json",
+ config={"encoding": "utf-8"}
+)
+```
---
-## Main Classes
-
-### SeedDataManager
+## Merge Strategies
-Coordinator for all seed data operations.
+```python
+final_kg = manager.integrate_seed_extracted(
+ seed_graph=foundation_kg,
+ extracted_data=new_data,
+ strategy="seed_first" # "seed_first" | "extracted_first" | "smart_merge"
+)
+```
-**Methods:**
+| Strategy | Behavior |
+|----------|----------|
+| `seed_first` | Seed data overrides extracted data |
+| `extracted_first` | Extracted data overrides seed data |
+| `smart_merge` | Property-level merging with conflict resolution |
-| Method | Description |
-|--------|-------------|
-| `register_source(name, format, location)` | Add data source |
-| `create_foundation_graph()` | Build KG from sources |
-| `validate_quality(seed_data)` | Check data quality |
-| `integrate_with_extracted(seed, extracted)` | Merge graphs |
-| `export_seed_data(path, format)` | Export data |
+---
-**Example:**
+## Bootstrapping a KG
```python
from semantica.seed import SeedDataManager
+from semantica.ingest import FileIngestor
+# Load foundation from verified data
manager = SeedDataManager()
-manager.register_source("countries", "csv", "data/countries.csv")
+manager.register_source("taxonomy", "json", "taxonomy.json")
foundation_kg = manager.create_foundation_graph()
-```
-
-### SeedDataSource
-Data class defining a source.
+# Ingest and merge new data
+ingestor = FileIngestor()
+new_data = ingestor.ingest("news_articles.pdf")
-**Attributes:**
-- `name`: Source identifier
-- `type`: `csv`, `json`, `api`, `sql`
-- `path`: File path or connection string
-- `config`: Parsing options
+final_kg = manager.integrate_seed_extracted(
+ seed_graph=foundation_kg,
+ extracted_data=new_data,
+ strategy="seed_first"
+)
+```
---
-
-
## Configuration
-### Environment Variables
-
-```bash
-export SEED_DATA_DIR=./data/seed
-export SEED_MERGE_STRATEGY=seed_first
-```
-
-### YAML Configuration
-
```yaml
seed:
sources:
- name: "employees"
type: "csv"
path: "./data/employees.csv"
-
merge:
strategy: "seed_first"
-
validation:
strict: true
```
----
-
-## Integration Examples
-
-### Bootstrapping a KG
-
-```python
-from semantica.seed import SeedDataManager
-from semantica.ingest import Ingestor
-
-# 1. Load Foundation (Seed)
-seed_manager = SeedDataManager()
-seed_manager.register_source("taxonomy", "json", "taxonomy.json")
-foundation_kg = seed_manager.create_foundation_graph()
-
-# 2. Ingest New Data
-ingestor = Ingestor()
-new_data = ingestor.ingest("news_articles.pdf")
-
-# 3. Merge
-final_kg = seed_manager.integrate_seed_extracted(
- seed_graph=foundation_kg,
- extracted_data=new_data,
- strategy="seed_first" # Keep taxonomy strict
-)
+```bash
+export SEED_DATA_DIR=./data/seed
+export SEED_MERGE_STRATEGY=seed_first
```
---
-## Best Practices
-
-1. **Trust Seed Data**: Usually, seed data is verified. Use `seed_first` merge strategy.
-2. **Version Control**: Keep seed data files in version control (git).
-3. **Validate Schema**: Ensure seed data matches your target ontology.
-4. **Clean IDs**: Use consistent ID schemes in seed data to facilitate merging.
-
----
-
-## Cookbook
-
-Interactive tutorials that use seed data:
-
-- **[Financial Data Integration MCP](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)**: Merging financial data with seed data integration
- - **Topics**: Finance, data fusion, MCP integration, seed data
- - **Difficulty**: Intermediate
- - **Use Cases**: Integrating structured seed data with extracted data
-
-- **[Energy Market Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)**: Analyzing trends with seed data integration
- - **Topics**: Energy, time series, temporal analysis, seed data
- - **Difficulty**: Intermediate
- - **Use Cases**: Bootstrapping knowledge graphs with verified data
-
## See Also
-- [Ingest Module](ingest.md) - Loading unstructured data
-- [Knowledge Graph Module](kg.md) - The target graph structure
-- [Deduplication Module](deduplication.md) - Handling duplicates during merge
+<CardGroup cols={2}>
+ <Card title="Ingest" icon="file-import" href="ingest">
+ Load unstructured data alongside seed data.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The target graph structure.
+ </Card>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Handle duplicates during merge.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Incorporate seed loading in a pipeline.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 1cea1d2d..e987f0c5 100644
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@ -1,602 +1,175 @@
-# Semantic Extract
-
-> **Advanced information extraction system for Entities, Relations, Events, and Triplets.**
-
---
-
-## 🎯 Overview
-
-The **Semantic Extract Module** extracts structured information from unstructured text. It identifies entities, relationships, events, and semantic structures that form the foundation of knowledge graphs.
-
-### What is Semantic Extraction?
-
-**Semantic extraction** is the process of identifying meaningful information from text:
-- **Named Entities**: People, organizations, locations, dates, etc.
-- **Relationships**: Connections between entities (e.g., "founded_by", "located_in")
-- **Events**: Actions with temporal information and participants
-- **Triplets**: Subject-Predicate-Object structures for knowledge graphs
-- **Semantic Networks**: Structured networks of nodes and edges
-
-### Why Use the Semantic Extract Module?
-
-- **Multiple Methods**: Support for ML models, LLMs, and rule-based extraction
-- **High Accuracy**: LLM-based extraction for complex schemas
-- **Flexible Configuration**: Customize extraction for your domain
-- **Confidence Scores**: Get confidence scores for all extractions
-- **Batch Processing**: Efficient parallel batch processing for large datasets
-- **Coreference Resolution**: Resolve pronouns to their entity references
-
-### How It Works
-
-1. **Text Input**: Receive parsed text from the parse module
-2. **Entity Extraction**: Identify named entities using NER
-3. **Coreference Resolution**: Resolve pronouns to entities (optional)
-4. **Relationship Extraction**: Identify relationships between entities
-5. **Event Detection**: Detect events with temporal information
-6. **Triplet Generation**: Generate RDF triplets for knowledge graphs
-7. **Output**: Return structured entities, relationships, and triplets
-
-<div class="grid cards" markdown>
-
-- :material-account-search:{ .lg .middle } **NER**
-
- ---
-
- Extract Named Entities (Person, Org, Loc) with confidence scores
-
-- :material-relation-one-to-one:{ .lg .middle } **Relation Extraction**
-
- ---
-
- Identify relationships between entities (e.g., `founded_by`, `located_in`)
-
-- :material-calendar-clock:{ .lg .middle } **Event Detection**
-
- ---
-
- Detect events with temporal information and participants
-
-- :material-format-quote-close:{ .lg .middle } **Coreference**
-
- ---
-
- Resolve pronouns ("he", "it") to their entity references
-
-- :material-share-variant:{ .lg .middle } **Triplet Extraction**
-
- ---
-
- Extract Subject-Predicate-Object triplets for Knowledge Graphs
-
-- :material-robot:{ .lg .middle } **LLM Extraction**
-
- ---
-
- Use LLMs to improve extraction quality and handle complex schemas
-
-- :material-graph:{ .lg .middle } **Semantic Networks**
-
- ---
-
- Build structured networks with nodes and edges from text
-
-</div>
-
-!!! tip "When to Use"
- - **KG Construction**: Converting unstructured text into structured graph data
- - **Text Analysis**: Identifying key actors and events in documents
- - **Search Indexing**: Extracting metadata for faceted search
- - **Data Enrichment**: Adding semantic tags to content
-
+title: "Semantic Extract Module"
+description: "Named entity recognition, relation extraction, event detection, and triplet generation."
+icon: "magnifying-glass-chart"
---
-## βš™οΈ Algorithms Used
-
-### Named Entity Recognition (NER)
-
-**Purpose**: Identify and classify named entities in text.
-
-**How it works**:
-
-- **Transformer Models**: BERT/RoBERTa for token classification
-- **Regex Patterns**: Pattern matching for specific formats (Emails, IDs)
-- **LLM Prompting**: Zero-shot extraction for custom entity types
-
-### Relation Extraction
-
-**Purpose**: Identify relationships between entities.
-
-**How it works**:
-
-- **Dependency Parsing**: Analyzing grammatical structure to find subject-verb-object paths
-- **Joint Extraction**: Extracting entities and relations simultaneously
-- **Semantic Role Labeling**: Identifying "Who did What to Whom"
-
-### Coreference Resolution
-
-**Purpose**: Resolve pronouns and references to their entity references.
-
-**How it works**:
-
-- **Mention Detection**: Finding all potential references (nouns, pronouns)
-- **Clustering**: Grouping mentions that refer to the same real-world entity
-- **Pronoun Resolution**: Mapping pronouns to the most likely antecedent
-
-### Triplet Extraction
-
-**Purpose**: Extract Subject-Predicate-Object triplets for Knowledge Graphs.
-
-**How it works**:
-
-- **OpenIE**: Open Information Extraction for arbitrary relation strings
-- **Schema-Based**: Mapping extracted relations to a predefined ontology
-- **Reification**: Handling complex relations (time, location) by creating event nodes.
+> Advanced information extraction system for Entities, Relations, Events, and Triplets.
---
-## Main Classes
-
-### NamedEntityRecognizer
-
-Coordinator for entity extraction.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `methods` | list | `["spacy"]` | Extraction methods to use |
-| `confidence_threshold` | float | `0.5` | Minimum confidence score |
-| `merge_overlapping` | bool | `True` | Merge overlapping entities |
-| `include_standard_types` | bool | `True` | Include Person, Org, Location |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `extract_entities(text)` | Get list of entities |
-| `add_custom_pattern(pattern)` | Add regex rule |
+## Overview
+
+The **Semantic Extract Module** extracts structured information from unstructured text β€” the foundation of every knowledge graph in Semantica.
+
+<CardGroup cols={2}>
+ <Card title="NER" icon="magnifying-glass">
+ Extract named entities (Person, Org, Location) with confidence scores.
+ </Card>
+ <Card title="Relation Extraction" icon="arrows-left-right">
+ Identify relationships between entities (e.g., `founded_by`, `located_in`).
+ </Card>
+ <Card title="Event Detection" icon="calendar">
+ Detect events with temporal information and participants.
+ </Card>
+ <Card title="Triplet Generation" icon="diagram-project">
+ Generate RDF triplets (Subject–Predicate–Object) for knowledge graphs.
+ </Card>
+</CardGroup>
-**Example:**
-
-```python
-from semantica.semantic_extract import NamedEntityRecognizer
-
-# Basic usage
-ner = NamedEntityRecognizer()
-entities = ner.extract_entities("Elon Musk leads SpaceX.")
-# [Entity(text="Elon Musk", label="PERSON"), Entity(text="SpaceX", label="ORG")]
-
-# With configuration
-ner = NamedEntityRecognizer(
- methods=["spacy", "rule-based"],
- confidence_threshold=0.7,
- merge_overlapping=True
-)
-entities = ner.extract_entities("Apple Inc. was founded in 1976.")
-```
-
-### NERExtractor
-
-Core entity extraction implementation used by notebooks and lower-level integrations.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `method` | str or list | `"ml"` | Method(s): "ml", "llm", "pattern", "regex", "huggingface" |
-| `entity_types` | list | `None` | Filter for specific entity types |
-| `**config` | dict | `{}` | Method-specific config (e.g., `model`, `aggregation_strategy`, `device`) |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `extract(text, pipeline_id=None, **kwargs)` | Alias for `extract_entities`. Supports `max_workers`. |
-| `extract_entities(text, pipeline_id=None, **kwargs)` | Get list of entities. Supports `max_workers`. |
+---
-**Example:**
+## NERExtractor
```python
from semantica.semantic_extract import NERExtractor
+from semantica.llms import Groq
+import os
-# 1. ML (spaCy) - Default
-extractor = NERExtractor(method="ml", model="en_core_web_trf")
-entities = extractor.extract("Elon Musk leads SpaceX.")
-
-# 2. LLM (OpenAI/Gemini/Groq/etc)
-extractor = NERExtractor(
- method="llm",
- provider="groq",
- model="llama-3.3-70b-versatile",
- max_tokens=2048, # Increased output limit
- temperature=0.0
-)
+# Pattern-based (fast, no API key needed)
+ner = NERExtractor(method="pattern")
+entities = ner.extract("Apple Inc. was founded by Steve Jobs in Cupertino.")
-# 3. Regex with custom patterns
-patterns = {"CODE": r"[A-Z]{3}-\d{3}"}
-extractor = NERExtractor(method="regex", patterns=patterns)
+# ML-based
+ner = NERExtractor(method="ml", model="dslim/bert-large-NER")
+entities = ner.extract(text)
-# 4. Ensemble (Multiple methods)
-extractor = NERExtractor(method=["ml", "llm"], ensemble_voting=True)
+# LLM-based (most accurate for complex schemas)
+llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))
+ner = NERExtractor(method="llm", llm_provider=llm, max_retries=3)
+entities = ner.extract(text)
```
-### RelationExtractor
-
-Extracts relationships between entities.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `method` | str | `"dependency"` | Method: "dependency", "pattern", "cooccurrence", "huggingface", "llm" |
-| `relation_types` | list | `None` | Specific relation types to extract |
-| `bidirectional` | bool | `False` | Extract bidirectional relations |
-| `confidence_threshold` | float | `0.6` | Minimum confidence score |
-| `max_distance` | int | `50` | Max token distance between entities |
-| `**config` | dict | `{}` | Method-specific config (e.g., `model`, `device` for HuggingFace) |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `extract(text, entities, pipeline_id=None, **kwargs)` | Alias for `extract_relations`. Supports `max_workers`. |
-| `extract_relations(text, entities, pipeline_id=None, **kwargs)` | Find links. Supports `max_workers`. |
-
-**Example:**
+Output format:
```python
-from semantica.semantic_extract import RelationExtractor, NamedEntityRecognizer
-
-# First extract entities
-ner = NamedEntityRecognizer()
-text = "Elon Musk founded SpaceX in 2002."
-entities = ner.extract_entities(text)
-
-# Basic relation extraction
-rel_extractor = RelationExtractor()
-relations = rel_extractor.extract(text, entities=entities)
-# [Relation(subject="Elon Musk", predicate="founded", object="SpaceX")]
-
-# With configuration
-rel_extractor = RelationExtractor(
- relation_types=["founded", "leads", "works_at"],
- confidence_threshold=0.7,
- bidirectional=False
-)
-relations = rel_extractor.extract(text, entities=entities)
+[
+ {"text": "Apple Inc.", "type": "ORGANIZATION", "confidence": 0.98, "start": 0, "end": 10},
+ {"text": "Steve Jobs", "type": "PERSON", "confidence": 0.99, "start": 27, "end": 37},
+ {"text": "Cupertino", "type": "LOCATION", "confidence": 0.97, "start": 41, "end": 50}
+]
```
-### CoreferenceResolver
-
-Resolves pronoun references and entity coreferences.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `method` | str or list | `None` | Underlying NER method(s) |
-| `**config` | dict | `{}` | Configuration for NER method |
+<Note>
+ **v0.5.0 fix:** `NERExtractor(method="llm")` no longer silently falls back to pattern extraction on custom gateways. The `response_format=json_object` parameter is now conditionally omitted for incompatible gateways, and a plain `generate()` + JSON parsing fallback is used.
+</Note>
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `resolve(text)` | Alias for `resolve_coreferences`. Get coreference chains. |
-| `resolve_coreferences(text)` | Get coreference chains |
-| `resolve_pronouns(text)` | Resolve pronouns to entities |
+---
-**Example:**
+## RelationExtractor
```python
-from semantica.semantic_extract import CoreferenceResolver
-
-resolver = CoreferenceResolver()
-text = "Steve Jobs founded Apple. He was the CEO."
+from semantica.semantic_extract import RelationExtractor
-# Resolve references
-chains = resolver.resolve(text)
-# [CoreferenceChain(mentions=["Steve Jobs", "He"], representative="Steve Jobs")]
+rel = RelationExtractor(method="llm", llm_provider=llm, max_retries=3)
+relationships = rel.extract(text, entities=entities)
```
-### EventDetector
-
-Identifies events with temporal information and participants.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `event_types` | list | `None` | Specific event types to detect |
-| `extract_participants` | bool | `True` | Extract event participants |
-| `extract_location` | bool | `True` | Extract event locations |
-| `extract_time` | bool | `True` | Extract temporal information |
-| `max_workers` | int | `1` | Threads for parallel batch processing |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `detect_events(text)` | Find events |
-
-**Example:**
+Output format:
```python
-from semantica.semantic_extract import EventDetector
-
-detector = EventDetector(
- event_types=["launch", "acquisition", "announcement"],
- extract_participants=True,
- extract_time=True
-)
-events = detector.detect_events("SpaceX launched Starship on March 14, 2024.")
+[
+ {"subject": "Steve Jobs", "predicate": "founded", "object": "Apple Inc.", "confidence": 0.92},
+ {"subject": "Apple Inc.", "predicate": "located_in", "object": "Cupertino", "confidence": 0.89}
+]
```
-### TripletExtractor
-
-Extracts RDF triplets (Subject-Predicate-Object).
-
-**Parameters:**
+Methods: `"rule"`, `"ml"` (REBEL model), `"llm"`.
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `method` | str | `"pattern"` | Extraction method ("pattern", "rules", "huggingface", "llm") |
-| `triplet_types` | list | `None` | Specific triplet types/predicates to extract |
-| `include_temporal` | bool | `False` | Include time information |
-| `include_provenance` | bool | `False` | Track source sentences |
-| `**kwargs` | dict | `{}` | Configuration options (e.g., `model`, `device`) |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `extract(text, entities=None, relations=None, pipeline_id=None, **kwargs)` | Alias for `extract_triplets`. Supports `max_workers`. |
-| `extract_triplets(text, entities=None, relations=None, pipeline_id=None, **kwargs)` | Get (S, P, O) tuples. Supports `max_workers`. |
+---
-**Example:**
+## TripletExtractor
```python
from semantica.semantic_extract import TripletExtractor
-extractor = TripletExtractor(
- include_temporal=True,
- include_provenance=True
-)
-triplets = extractor.extract_triplets("Steve Jobs founded Apple in 1976.")
-# [Triplet(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]
-```
-
-### SemanticNetworkExtractor
-
-Extracts structured semantic networks with nodes and edges.
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `ner_method` | str | `None` | Method for node extraction |
-| `relation_method` | str | `None` | Method for edge extraction |
-| `max_workers` | int | `1` | Threads for parallel batch processing |
-| `**config` | dict | `{}` | Configuration for underlying extractors |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `extract_network(text)` | Build network from text |
-| `extract(text)` | Alias for `extract_network` |
-| `export_to_yaml(network, path)` | Save network to YAML |
-
-**Example:**
-
-```python
-from semantica.semantic_extract import SemanticNetworkExtractor
-
-extractor = SemanticNetworkExtractor()
-network = extractor.extract("Apple Inc. is located in Cupertino.")
-
-# Analyze network
-print(f"Nodes: {len(network.nodes)}")
-print(f"Edges: {len(network.edges)}")
+trip = TripletExtractor(method="llm", llm_provider=llm)
+triplets = trip.extract(text)
```
-### LLMExtraction
-
-LLM-based extraction and enhancement. (Alias: `LLMEnhancer`)
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `provider` | str | `"openai"` | LLM provider ("openai", "gemini", "anthropic", etc.) |
-| `**config` | dict | `{}` | Model config (model name, api_key, etc.) |
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `enhance_extractions(extractions, text)` | Enhance generic extractions |
-| `enhance_entities(text, entities)` | Improve entity accuracy and details |
-| `enhance_relations(text, relations)` | Improve relation detection |
-
-**Example:**
-
-```python
-from semantica.semantic_extract import LLMExtraction
-
-extractor = LLMExtraction(provider="openai", model="gpt-4")
-enhanced_entities = extractor.enhance_entities(text, entities)
-```
+Generates RDF-ready `(subject, predicate, object)` triplets directly from text, suitable for loading into a triplet store.
---
-## Batch Processing & Provenance
-
-All extractors support batch processing for high-throughput extraction. You can pass a list of strings or a list of dictionaries (with `content` and `id` keys).
-
-**Features:**
-- **Progress Tracking**: Automatically shows a progress bar for large batches.
-- **Provenance Metadata**: Each extracted item includes `batch_index` and `document_id` in its `metadata`.
+## EventExtractor
```python
-from semantica.semantic_extract import NERExtractor
-
-documents = [
- {"id": "doc_1", "content": "Apple Inc. was founded by Steve Jobs."},
- {"id": "doc_2", "content": "Microsoft Corporation was founded by Bill Gates."}
-]
+from semantica.semantic_extract import EventExtractor
-extractor = NERExtractor()
-batch_results = extractor.extract(documents)
-
-for i, doc_entities in enumerate(batch_results):
- print(f"Document {i} entities:")
- for entity in doc_entities:
- print(f" - {entity.text} ({entity.label})")
- print(f" Provenance: Batch Index {entity.metadata['batch_index']}, Doc ID {entity.metadata.get('document_id')}")
+extractor = EventExtractor(method="llm", llm_provider=llm)
+events = extractor.extract(text)
```
-## Robust Extraction Fallbacks
-
-The framework implements robust fallback chains to prevent empty results when primary methods fail (e.g., due to model unavailability or obscure text).
-
-- **NER**: `ML/LLM` -> `Pattern` -> `Last Resort` (Capitalized Words)
-- **Relation**: `Primary` -> `Pattern` -> `Last Resort` (Adjacency)
-- **Triplet**: `Primary` -> `Relation-to-Triplet` -> `Pattern`
-
-This ensures that you almost always get *some* structured data, even if it requires falling back to simpler heuristics.
+Output includes event type, participants, temporal information, and confidence score.
---
-## Usage Examples
+## Custom Entity Types
```python
-from semantica.semantic_extract import (
- NamedEntityRecognizer,
- RelationExtractor,
- TripletExtractor,
- EventDetector,
- CoreferenceResolver,
- SemanticNetworkExtractor
+ner = NERExtractor(
+ method="pattern",
+ custom_entities={
+ "DRUG": ["aspirin", "ibuprofen", "metformin"],
+ "GENE": ["BRCA1", "TP53", "EGFR"]
+ }
)
-
-text = "Apple released the iPhone in 2007. Steve Jobs announced it at Macworld."
-
-# Extract entities with confidence filtering
-ner = NamedEntityRecognizer(confidence_threshold=0.7)
-entities = ner.extract_entities(text)
-
-# Resolve coreferences (recommended before relation extraction)
-coref = CoreferenceResolver()
-resolved = coref.resolve(text)
-
-# Extract relations
-rel_extractor = RelationExtractor(confidence_threshold=0.6)
-relations = rel_extractor.extract_relations(text, entities=entities)
-
-# Extract triplets for KG
-triplet_extractor = TripletExtractor(include_temporal=True)
-triplets = triplet_extractor.extract_triplets(text)
-
-# Detect events
-event_detector = EventDetector(extract_time=True)
-events = event_detector.detect_events(text)
-
-# Extract semantic network
-network_extractor = SemanticNetworkExtractor()
-network = network_extractor.extract(text)
-
-print(f"Entities: {len(entities)}")
-print(f"Relations: {len(relations)}")
-print(f"Triplets: {len(triplets)}")
-print(f"Events: {len(events)}")
-print(f"Network Nodes: {len(network.nodes)}")
```
---
-## Configuration
-
-### Environment Variables
+## Batch Processing
-```bash
-export NER_MODEL=dslim/bert-base-NER
-export RELATION_MODEL=semantica/rel-extract-v1
-export EXTRACT_CONFIDENCE_THRESHOLD=0.7
-```
+```python
+texts = ["Text 1...", "Text 2...", "Text 3..."]
-### YAML Configuration
-
-```yaml
-semantic_extract:
- ner:
- model: dslim/bert-base-NER
- min_confidence: 0.7
-
- relations:
- max_distance: 50 # tokens
-
- coreference:
- enabled: true
+ner = NERExtractor(method="llm", llm_provider=llm)
+batch_results = ner.extract_batch(texts, batch_size=10)
```
---
-## Integration Examples
-
-### KG Population Pipeline
+## Using All Extractors Together
```python
-from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripletExtractor
-from semantica.kg import GraphBuilder
-
-# 1. Extract
-text = "Google was founded by Larry Page and Sergey Brin."
-ner = NamedEntityRecognizer()
-entities = ner.extract_entities(text)
-triplet_extractor = TripletExtractor()
-triplets = triplet_extractor.extract_triplets(text)
-
-# 2. Populate KG using GraphBuilder
-builder = GraphBuilder()
-sources = [{
- "entities": entities,
- "relationships": [{"source": t.subject, "target": t.object, "type": t.predicate} for t in triplets]
-}]
-kg = builder.build(sources)
-```
+from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor
----
+llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))
-## Best Practices
+ner = NERExtractor(method="llm", llm_provider=llm, max_retries=3)
+rel = RelationExtractor(method="llm", llm_provider=llm, max_retries=3)
+trip = TripletExtractor(method="llm", llm_provider=llm, max_retries=3)
-1. **Resolve Coreferences**: Always run coreference resolution *before* relation extraction to link "He" to "John Doe".
-2. **Filter Low Confidence**: Set a confidence threshold (e.g., 0.7) to reduce noise.
-3. **Use Custom Patterns**: For domain-specific IDs (e.g., "Invoice #123"), regex is faster and more accurate than ML.
-4. **Batch Processing**: Use batch methods when processing large corpora.
+entities = ner.extract(text)
+relationships = rel.extract(text, entities=entities)
+triplets = trip.extract(text)
+```
---
## See Also
-- [Parse Module](parse.md) - Prepares text for extraction
-- [Ontology Module](ontology.md) - Defines the schema for extraction
-- [Knowledge Graph Module](kg.md) - Stores the extracted data
-
-## Cookbook
-
-Interactive tutorials to learn semantic extraction:
-
-- **[Entity Extraction](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/05_Entity_Extraction.ipynb)**: Extract named entities from text using NER
- - **Topics**: NER, Spacy, LLM extraction, entity types, confidence scores
- - **Difficulty**: Beginner
- - **Use Cases**: Identifying entities in text, building entity lists
-
-- **[Relation Extraction](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/06_Relation_Extraction.ipynb)**: Discover and classify relationships between entities
- - **Topics**: Relation classification, dependency parsing, relationship types
- - **Difficulty**: Beginner
- - **Use Cases**: Finding relationships, building knowledge graphs
-
-- **[Advanced Extraction](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/01_Advanced_Extraction.ipynb)**: Custom extractors, LLM-based extraction, and complex pattern matching
- - **Topics**: Custom models, regex, LLMs, ensemble methods, domain-specific extraction
- - **Difficulty**: Advanced
- - **Use Cases**: Custom extraction schemas, domain-specific entities
+<CardGroup cols={2}>
+ <Card title="LLM Providers" icon="microchip" href="llms">
+ Configure which LLM is used for extraction.
+ </Card>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ Build graphs from extracted entities and relationships.
+ </Card>
+ <Card title="Parse Module" icon="file-lines" href="parse">
+ Parse documents before extraction.
+ </Card>
+ <Card title="Deduplication" icon="copy" href="deduplication">
+ Resolve duplicate entities after extraction.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/split.md b/docs/reference/split.md
index bb97054d..a209e6e7 100644
--- a/docs/reference/split.md
+++ b/docs/reference/split.md
@@ -1,963 +1,127 @@
-# Split
-
-> **Comprehensive document chunking and splitting for optimal processing with 15+ methods including KG-aware, semantic, and structural chunking.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-content-cut:{ .lg .middle } **Multiple Methods**
-
- ---
-
- 15+ chunking methods: recursive, semantic, entity-aware, relation-aware, and more
-
-- :material-graph:{ .lg .middle } **KG-Aware Chunking**
-
- ---
-
- Preserve entities, relationships, and graph structure for GraphRAG workflows
-
-- :material-brain:{ .lg .middle } **Semantic Chunking**
-
- ---
-
- Intelligent boundary detection using embeddings and NLP
-
-- :material-file-tree:{ .lg .middle } **Structural Chunking**
-
- ---
-
- Respect document structure: headings, paragraphs, lists, tables
-
-- :material-check-circle:{ .lg .middle } **Quality Validation**
-
- ---
-
- Chunk quality assessment and validation
-
-- :material-source-branch:{ .lg .middle } **Provenance Tracking**
-
- ---
-
- Track chunk origins for data lineage
-
-</div>
-
-!!! tip "Choosing the Right Method"
- - **Standard Documents**: Use `recursive` or `sentence` for general text
- - **GraphRAG**: Use `entity_aware` or `relation_aware` to preserve knowledge
- - **Semantic Coherence**: Use `semantic_transformer` for topic-based chunks
- - **Structured Docs**: Use `structural` for documents with headings/sections
- - **Large Documents**: Use `hierarchical` for multi-level chunking
-
+title: "Split Module"
+description: "15+ text chunking methods including recursive, semantic, entity-aware, and relation-aware splitting."
+icon: "scissors"
---
-## βš™οΈ Algorithms Used
-
-### Standard Splitting Algorithms
-
-**Purpose**: Split documents into chunks using various strategies.
-
-**How it works**:
-
-- **Recursive Splitting**: Separator hierarchy (`` `\n\n` ``, `` `\n` ``, `` ` ` ``, ``) with greedy splitting
-- **Token Counting**: BPE tokenization using tiktoken or transformers
-- **Sentence Segmentation**: NLTK punkt, spaCy sentencizer, or regex-based
-- **Paragraph Detection**: Double newline detection with whitespace normalization
-- **Character Splitting**: Fixed-size character chunks with overlap
-- **Word Splitting**: Whitespace tokenization with word boundary preservation
-
-### Semantic Chunking Algorithms
-
-**Purpose**: Intelligent boundary detection using embeddings and NLP.
-
-**How it works**:
-
-- **Semantic Boundary Detection**:
- - Sentence transformer embeddings (384-1024 dim)
- - Cosine similarity between consecutive sentences
- - Threshold-based boundary detection (default: `` `0.7` ``)
-- **LLM-based Splitting**:
- - Prompt engineering for optimal split point detection
- - Context window management
- - Coherence scoring
-
-### KG/Ontology Chunking Algorithms
-
-**Purpose**: Preserve entities, relationships, and graph structure for GraphRAG workflows.
-
-**How it works**:
-
-- **Entity Boundary Detection**:
- - NER-based entity extraction (spaCy, LLM)
- - Entity span tracking
- - Boundary preservation (no entity splitting)
-- **Triplet Preservation**:
- - Graph-based triplet integrity checking
- - Subject-predicate-object span tracking
- - Relationship boundary preservation
-- **Graph Centrality Analysis**:
- - Degree centrality: `` `C_D(v) = deg(v) / (n-1)` ``
- - Betweenness centrality: `` `C_B(v) = Ξ£(Οƒ_st(v) / Οƒ_st)` ``
- - Closeness centrality: `` `C_C(v) = (n-1) / Ξ£d(v,u)` ``
- - Eigenvector centrality: Power iteration method
-- **Community Detection**:
- - Louvain algorithm: Modularity optimization O(n log n)
- - Leiden algorithm: Improved Louvain with refinement
- - Modularity calculation: `Q = (1/2m) Ξ£[A_ij - k_i*k_j/2m]Ξ΄(c_i,c_j)`
-
-### Structural Chunking Algorithms
-- **Heading Detection**: Markdown/HTML heading parsing
-- **List Detection**: Ordered/unordered list identification
-- **Table Detection**: Table boundary identification
-- **Section Hierarchy**: Tree-based section structure
-
-### Validation Algorithms
-- **Chunk Size Validation**: Min/max size checking
-- **Overlap Validation**: Overlap percentage calculation
-- **Completeness Check**: Coverage verification
-- **Quality Scoring**: Multi-factor quality assessment
+> Comprehensive document chunking for optimal RAG, embedding, and extraction pipelines.
---
-## Main Classes
-
-### TextSplitter
-
-Unified text splitter with method parameter for all chunking strategies.
+## Overview
-**Methods:**
+The **Split Module** breaks documents into chunks while preserving context and semantic meaning β€” critical for embedding quality in RAG systems.
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `split(text)` | Split text using configured method | Method-specific algorithm |
-| `split_documents(documents)` | Batch split documents | Parallel processing |
-| `split_with_metadata(text, metadata)` | Split with metadata preservation | Metadata propagation |
-| `validate_chunks(chunks)` | Validate chunk quality | Quality assessment |
-
-**Supported Methods:**
-
-| Category | Methods |
-|----------|---------|
-| **Standard** | recursive, token, sentence, paragraph, character, word |
-| **Semantic** | semantic_transformer, llm, huggingface, nltk |
-| **KG/Ontology** | entity_aware, relation_aware, graph_based, ontology_aware |
-| **Advanced** | hierarchical, community_detection, centrality_based, subgraph, topic_based |
-
-**Configuration Options:**
-
-```python
-TextSplitter(
- method="recursive", # Chunking method
- chunk_size=1000, # Target chunk size (characters/tokens)
- chunk_overlap=200, # Overlap between chunks
- length_function=len, # Function to measure chunk size
- separators=["\n\n", "\n", " ", ""], # For recursive method
- keep_separator=True, # Keep separators in chunks
- add_start_index=True, # Add start index to metadata
- strip_whitespace=True, # Strip whitespace from chunks
-
- # Semantic chunking options
- embedding_model="all-MiniLM-L6-v2", # For semantic_transformer
- similarity_threshold=0.7, # Semantic boundary threshold
-
- # Entity-aware options
- ner_method="ml", # NER method (ml/spacy, llm, pattern)
- preserve_entities=True, # Don't split entities
-
- # LLM options
- llm_provider="openai", # LLM provider
- llm_model="gpt-4", # LLM model
-
- # Graph-based options
- centrality_method="degree", # Centrality measure
- community_algorithm="louvain", # Community detection algorithm
-)
-```
+---
-**Example:**
+## TextSplitter
```python
from semantica.split import TextSplitter
-# Standard recursive splitting
-splitter = TextSplitter(
- method="recursive",
- chunk_size=1000,
- chunk_overlap=200
-)
-chunks = splitter.split(long_text)
-
-for i, chunk in enumerate(chunks):
- print(f"Chunk {i}: {len(chunk.text)} chars")
- print(f"Metadata: {chunk.metadata}")
-
-# Entity-aware for GraphRAG
splitter = TextSplitter(
- method="entity_aware",
- ner_method="ml",
+ method="semantic", # see methods below
chunk_size=1000,
- preserve_entities=True
-)
-chunks = splitter.split(text)
-
-# Semantic chunking
-splitter = TextSplitter(
- method="semantic_transformer",
- embedding_model="all-MiniLM-L6-v2",
- similarity_threshold=0.7
+ overlap=200
)
-chunks = splitter.split(text)
-# Hierarchical chunking
-splitter = TextSplitter(
- method="hierarchical",
- chunk_sizes=[2000, 1000, 500], # Multi-level
- chunk_overlaps=[400, 200, 100]
-)
chunks = splitter.split(text)
-```
-
----
-
-### SemanticChunker
-
-Semantic-based chunking using embeddings and similarity.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text)` | Chunk by semantic boundaries | Embedding similarity |
-| `find_boundaries(sentences)` | Find semantic boundaries | Threshold-based detection |
-| `calculate_similarity(sent1, sent2)` | Calculate similarity | Cosine similarity |
-
-**Example:**
-
-```python
-from semantica.split import SemanticChunker
-
-chunker = SemanticChunker(
- embedding_model="all-MiniLM-L6-v2",
- similarity_threshold=0.7,
- min_chunk_size=100,
- max_chunk_size=2000
-)
-
-chunks = chunker.chunk(long_text)
-
for chunk in chunks:
- print(f"Chunk: {chunk.text[:100]}...")
- print(f"Coherence score: {chunk.metadata.get('coherence_score')}")
+ print(f"Chunk: {chunk.text[:80]}... ({chunk.token_count} tokens)")
```
---
-### EntityAwareChunker
+## Splitting Methods
-Preserve entity boundaries during chunking for GraphRAG.
+| Method | Description | Best for |
+|--------|-------------|----------|
+| `recursive` | Split by paragraph β†’ sentence β†’ word | General purpose |
+| `semantic` | Split at semantic boundaries (topic shifts) | RAG systems |
+| `entity-aware` | Keep entity mentions intact across boundaries | NER pipelines |
+| `relation-aware` | Keep relation triplets intact | KG construction |
+| `sentence` | Split by sentence | Short content |
+| `token` | Split by token count (tiktoken) | LLM context windows |
+| `fixed` | Fixed character count with overlap | Batch processing |
+| `markdown` | Split by Markdown headers | Documentation |
+| `code` | Split by function/class boundaries | Code analysis |
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text, entities)` | Chunk preserving entities | Entity boundary detection |
+---
-**Example:**
+## Entity-Aware Chunking
```python
-from semantica.split import EntityAwareChunker
+from semantica.split import TextSplitter
from semantica.semantic_extract import NERExtractor
-# Extract entities first
-ner = NERExtractor(method="ml")
+ner = NERExtractor()
entities = ner.extract(text)
-# Chunk preserving entities
-chunker = EntityAwareChunker(
- chunk_size=1000,
- chunk_overlap=200,
- ner_method="ml"
-)
-
-chunks = chunker.chunk(text, entities=entities)
-
-for chunk in chunks:
- print(f"Entities in chunk: {chunk.metadata.get('entities')}")
-```
-
----
-
-### RelationAwareChunker
-
-Preserve relationship triplets during chunking.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text, relationships)` | Chunk preserving triplets | Triplet span tracking |
-| `extract_relationships(text)` | Extract relationships | Relation extraction |
-| `validate_triplet_integrity(chunk, relationships)` | Validate triplets | Integrity checking |
-
-**Example:**
-
-```python
-from semantica.split import RelationAwareChunker
-from semantica.semantic_extract import RelationExtractor
-
-# Extract relationships
-rel_extractor = RelationExtractor()
-relationships = rel_extractor.extract(text)
-
-# Chunk preserving relationships
-chunker = RelationAwareChunker(
- chunk_size=1000,
- preserve_triplets=True
-)
-
-chunks = chunker.chunk(text, relationships=relationships)
-
-for chunk in chunks:
- print(f"Relationships: {chunk.metadata.get('relationships')}")
-```
-
----
-
-### GraphBasedChunker
-
-Chunk based on graph structure and centrality.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text, graph)` | Chunk by graph structure | Centrality-based |
-| `calculate_centrality(graph)` | Calculate node centrality | Degree/betweenness/closeness |
-| `detect_communities(graph)` | Detect communities | Louvain/Leiden algorithm |
-
-**Example:**
-
-```python
-from semantica.split import GraphBasedChunker
-from semantica.kg import GraphBuilder
-
-# Build graph
-builder = GraphBuilder()
-kg = builder.build(entities, relationships)
-
-# Chunk by graph structure
-chunker = GraphBasedChunker(
- centrality_method="betweenness",
- community_algorithm="louvain"
-)
-
-chunks = chunker.chunk(text, graph=kg)
-
-for chunk in chunks:
- print(f"Community: {chunk.metadata.get('community_id')}")
- print(f"Centrality: {chunk.metadata.get('avg_centrality')}")
-```
-
----
-
-### StructuralChunker
-
-Structure-aware chunking respecting document hierarchy.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text)` | Chunk by structure | Heading/section detection |
-| `_extract_structure(text)` | Extract structural elements | Markdown/HTML parsing |
-
-**Example:**
-
-```python
-from semantica.split import StructuralChunker
-
-chunker = StructuralChunker(
- respect_headers=True,
- respect_sections=True,
- max_chunk_size=2000
-)
-
-chunks = chunker.chunk(markdown_text)
-
-for chunk in chunks:
- print(f"Structure preserved: {chunk.metadata.get('structure_preserved')}")
- print(f"Elements: {chunk.metadata.get('element_types')}")
-```
-
----
-
-### HierarchicalChunker
-
-Multi-level hierarchical chunking.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text)` | Multi-level chunking | Recursive hierarchical split |
-
-**Example:**
-
-```python
-from semantica.split import HierarchicalChunker
-
-chunker = HierarchicalChunker(
- chunk_sizes=[2000, 1000, 500],
- chunk_overlaps=[400, 200, 100],
- create_parent_chunks=True
-)
-
-chunks = chunker.chunk(long_text)
-
-for chunk in chunks:
- print(f"Level: {chunk.metadata.get('level')}")
- print(f"Parent: {chunk.metadata.get('parent_id')}")
- print(f"Children: {chunk.metadata.get('child_ids')}")
-```
-
----
-
-### OntologyAwareChunker
-
-Chunk based on ontology concepts and relationships.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text, ontology)` | Chunk by ontology concepts | Concept boundary detection |
-| `extract_concepts(text)` | Extract ontology concepts | Concept extraction |
-| `find_concept_boundaries(text, concepts)` | Find concept boundaries | Concept span checking |
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `chunk_size` | int | 1000 | Target chunk size |
-| `chunk_overlap` | int | 200 | Overlap between chunks |
-| `ontology_path` | str | None | Path to ontology file (.owl, .rdf) |
-| `preserve_concepts` | bool | True | Don't split ontology concepts |
-| `concept_extraction_method` | str | "llm" | Method for concept extraction |
-
-**Example:**
-
-```python
-from semantica.split import OntologyAwareChunker
-
-chunker = OntologyAwareChunker(
- chunk_size=1000,
- chunk_overlap=200,
- ontology_path="domain_ontology.owl",
- preserve_concepts=True,
- concept_extraction_method="llm"
-)
-
-chunks = chunker.chunk(text)
-
-for chunk in chunks:
- concepts = chunk.metadata.get('concepts', [])
- print(f"Concepts in chunk: {[c['label'] for c in concepts]}")
- print(f"Concept types: {[c['type'] for c in concepts]}")
+splitter = TextSplitter(method="entity-aware")
+chunks = splitter.split(text, entities=entities)
```
----
-
-### SlidingWindowChunker
-
-Fixed-size sliding window chunking with configurable step size.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk(text)` | Sliding window chunking | Fixed-size window with step |
-| `chunk_with_overlap(text)` | Chunk with specific overlap | Window position calculation |
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `chunk_size` | int | 1000 | Size of sliding window |
-| `overlap` | int | 0 | Overlap size |
-| `stride` | int | chunk_size - overlap | Step size |
-
-**Example:**
-
-```python
-from semantica.split import SlidingWindowChunker
-
-# Basic sliding window
-chunker = SlidingWindowChunker(
- chunk_size=1000,
- overlap=200
-)
-
-chunks = chunker.chunk(long_text)
-
-for i, chunk in enumerate(chunks):
- print(f"Window {i}: chars {chunk.start_index}-{chunk.end_index}")
- print(f"Has overlap: {chunk.metadata.get('has_overlap')}")
-
-# Boundary-preserving sliding window
-chunks = chunker.chunk(text, preserve_boundaries=True)
-```
+Entity mentions are never split across chunk boundaries, preserving context for downstream NER.
---
-### TableChunker
-
-Table-specific chunking preserving table structure.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `chunk_table(table_data)` | Chunk tables | Row/Column-based splitting |
-| `chunk_to_text_chunks(table_data)` | Convert table chunks to text | Table to text conversion |
-| `extract_table_schema(table_data)` | Extract schema | Type inference and schema extraction |
-
-**Parameters:**
-
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `max_rows` | int | 100 | Maximum rows per table chunk |
-| `preserve_headers` | bool | True | Keep headers in each chunk |
-| `chunk_by_columns` | bool | False | Chunk by columns instead of rows |
-
-**Example:**
+## Relation-Aware Chunking
```python
-from semantica.split import TableChunker
-
-chunker = TableChunker(
- max_rows=50,
- preserve_headers=True,
- chunk_by_columns=False
-)
-
-table_data = {
- "headers": ["Col1", "Col2", "Col3"],
- "rows": [["Val1", "Val2", "Val3"], ...]
-}
-
-# Get structured table chunks
-table_chunks = chunker.chunk_table(table_data)
-
-# Get text chunks for RAG
-text_chunks = chunker.chunk_to_text_chunks(table_data)
-
-for chunk in text_chunks:
- print(f"Table chunk {chunk.metadata.get('chunk_index')}")
- print(f"Rows: {chunk.metadata.get('row_count')}")
+splitter = TextSplitter(method="relation-aware")
+chunks = splitter.split(text, relationships=relationships)
```
----
-
-### ChunkValidator
-
-Validate chunk quality and completeness.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `validate(chunks)` | Validate chunks | Multi-factor validation |
-| `check_size(chunk)` | Check size constraints | Min/max checking |
-| `check_overlap(chunks)` | Check overlap | Overlap calculation |
-| `check_completeness(chunks, original)` | Check coverage | Coverage verification |
-| `calculate_quality_score(chunk)` | Quality score | Multi-factor scoring |
-
-**Example:**
-
-```python
-from semantica.split import ChunkValidator
-
-validator = ChunkValidator(
- min_chunk_size=100,
- max_chunk_size=2000,
- min_overlap=50,
- max_overlap=500
-)
-
-validation_result = validator.validate(chunks)
-
-print(f"Valid: {validation_result['valid']}")
-print(f"Issues: {validation_result['issues']}")
-print(f"Quality score: {validation_result['quality_score']}")
-```
-
----
-
-### ProvenanceTracker
-
-Track chunk provenance for data lineage.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `track(chunk, source)` | Track chunk origin | Provenance recording |
-| `get_lineage(chunk_id)` | Get chunk lineage | Lineage retrieval |
-| `visualize_lineage(chunk_id)` | Visualize lineage | Graph visualization |
-
-**Example:**
-
-```python
-from semantica.split import ProvenanceTracker
-
-tracker = ProvenanceTracker()
-
-for chunk in chunks:
- tracker.track(
- chunk=chunk,
- source={
- "document_id": "doc123",
- "file_path": "data/document.pdf",
- "page": 5,
- "timestamp": "2024-01-01T00:00:00Z"
- }
- )
-
-# Get lineage
-lineage = tracker.get_lineage(chunk.id)
-print(f"Source: {lineage['source']}")
-print(f"Transformations: {lineage['transformations']}")
-```
+Keeps subject–predicate–object triplets within the same chunk.
---
-## Convenience Functions
-
-Quick access to splitting operations:
-
-```python
-from semantica.split import (
- split_recursive,
- split_by_tokens,
- split_by_sentences,
- split_by_paragraphs,
- split_entity_aware,
- split_relation_aware,
- split_semantic_transformer,
- list_available_methods
-)
-
-# List available methods
-methods = list_available_methods()
-print(f"Available methods: {methods}")
-
-# Quick splitting
-chunks = split_recursive(text, chunk_size=1000, chunk_overlap=200)
-chunks = split_by_sentences(text, sentences_per_chunk=5)
-chunks = split_entity_aware(text, ner_method="ml")
-```
-
----
-
-## Configuration
-
-### Environment Variables
-
-```bash
-# Default settings
-export SPLIT_DEFAULT_METHOD=recursive
-export SPLIT_DEFAULT_CHUNK_SIZE=1000
-export SPLIT_DEFAULT_CHUNK_OVERLAP=200
-
-# Semantic chunking
-export SPLIT_EMBEDDING_MODEL=all-MiniLM-L6-v2
-export SPLIT_SIMILARITY_THRESHOLD=0.7
-
-# Entity-aware
-export SPLIT_NER_METHOD=ml # or spacy
-export SPLIT_PRESERVE_ENTITIES=true
-
-# LLM-based
-export SPLIT_LLM_PROVIDER=openai
-export SPLIT_LLM_MODEL=gpt-4
-```
-
-### YAML Configuration
-
-```yaml
-# config.yaml - Split Module Configuration
-
-split:
- default_method: recursive
- chunk_size: 1000
- chunk_overlap: 200
-
- recursive:
- separators: ["\n\n", "\n", " ", ""]
- keep_separator: true
-
- semantic:
- embedding_model: all-MiniLM-L6-v2
- similarity_threshold: 0.7
- min_chunk_size: 100
- max_chunk_size: 2000
-
- entity_aware:
- ner_method: ml # or spacy
- preserve_entities: true
- min_entity_gap: 50
-
- relation_aware:
- preserve_triplets: true
- relation_extraction_method: llm
-
- graph_based:
- centrality_method: betweenness
- community_algorithm: louvain
- min_community_size: 3
-
- hierarchical:
- levels: 3
- chunk_sizes: [2000, 1000, 500]
- chunk_overlaps: [400, 200, 100]
-
- validation:
- enabled: true
- min_chunk_size: 100
- max_chunk_size: 2000
- check_overlap: true
- check_completeness: true
-```
-
----
-
-## Method Comparison
-
-| Method | Best For | Pros | Cons |
-|--------|----------|------|------|
-| **recursive** | General text | Fast, simple | May split mid-sentence |
-| **sentence** | Coherent chunks | Respects sentences | Variable size |
-| **semantic_transformer** | Topic coherence | Semantic boundaries | Slower, needs embeddings |
-| **entity_aware** | GraphRAG | Preserves entities | Requires NER |
-| **relation_aware** | KG extraction | Preserves triplets | Requires relation extraction |
-| **graph_based** | Graph analysis | Graph-aware | Requires graph construction |
-| **hierarchical** | Large documents | Multi-level | More complex |
-| **structural** | Formatted docs | Respects structure | Needs structure |
-
----
-
-## Integration Examples
-
-### Complete GraphRAG Pipeline
+## Semantic Chunking
```python
from semantica.split import TextSplitter
-from semantica.semantic_extract import NERExtractor, RelationExtractor
-from semantica.kg import GraphBuilder
from semantica.embeddings import EmbeddingGenerator
-from semantica.vector_store import VectorStore
-
-# Parse document
-text = "Apple Inc. was founded by Steve Jobs in 1976..."
-
-# Entity-aware chunking
-splitter = TextSplitter(
- method="entity_aware",
- ner_method="llm",
- chunk_size=1000
-)
-chunks = splitter.split(text)
-
-# Extract from each chunk
-ner = NERExtractor(method="llm")
-rel_extractor = RelationExtractor()
-
-all_entities = []
-all_relationships = []
-
-for chunk in chunks:
- entities = ner.extract(chunk.text)
- relationships = rel_extractor.extract(chunk.text, entities)
-
- all_entities.extend(entities)
- all_relationships.extend(relationships)
-
-# Build knowledge graph
-builder = GraphBuilder()
-kg = builder.build(all_entities, all_relationships)
-
-# Generate embeddings
-embedder = EmbeddingGenerator()
-embeddings = embedder.generate([chunk.text for chunk in chunks])
-
-# Store in vector store
-vector_store = VectorStore()
-vector_store.store(embeddings, chunks)
-```
-
-### Multi-Level Hierarchical Chunking
-
-```python
-from semantica.split import HierarchicalChunker
-
-chunker = HierarchicalChunker(
- chunk_sizes=[4000, 2000, 1000],
- chunk_overlaps=[800, 400, 200],
- create_parent_chunks=True
-)
-
-chunks = chunker.chunk(very_long_document)
-
-# Access hierarchy
-for chunk in chunks:
- level = chunk.metadata['level']
- parent_id = chunk.metadata.get('parent_id')
- child_ids = chunk.metadata.get('child_ids', [])
-
- print(f"Level {level}: {len(chunk.text)} chars")
- if parent_id:
- print(f" Parent: {parent_id}")
- if child_ids:
- print(f" Children: {len(child_ids)}")
-```
-
----
-
-## Best Practices
-
-### 1. Choose Appropriate Chunk Size
-
-```python
-# For semantic search (embeddings)
-splitter = TextSplitter(method="recursive", chunk_size=512)
-
-# For LLM context (GPT-4)
-splitter = TextSplitter(method="recursive", chunk_size=4000)
-
-# For entity extraction
-splitter = TextSplitter(method="entity_aware", chunk_size=1000)
-```
-
-### 2. Use Overlap for Context
-
-```python
-# 20% overlap recommended
-splitter = TextSplitter(
- chunk_size=1000,
- chunk_overlap=200 # 20%
-)
-```
-### 3. Validate Chunks
-
-```python
-from semantica.split import ChunkValidator
-
-validator = ChunkValidator()
-validation = validator.validate(chunks)
-
-if not validation['valid']:
- print(f"Issues: {validation['issues']}")
-```
-
-### 4. Track Provenance
-
-```python
-from semantica.split import ProvenanceTracker
-
-tracker = ProvenanceTracker()
-for chunk in chunks:
- tracker.track(chunk, source={"doc_id": "123"})
-```
-
----
-
-## Troubleshooting
-
-### Issue: Chunks too small/large
-
-```python
-# Solution: Adjust chunk size and method
-splitter = TextSplitter(
- method="recursive",
- chunk_size=1500, # Increase
- chunk_overlap=300
-)
-
-# Or use validation
-validator = ChunkValidator(min_chunk_size=500, max_chunk_size=2000)
-```
-
-### Issue: Entities split across chunks
-
-```python
-# Solution: Use entity-aware chunking
+embedder = EmbeddingGenerator(model="sentence-transformers")
splitter = TextSplitter(
- method="entity_aware",
- ner_method="llm",
- preserve_entities=True
+ method="semantic",
+ embedder=embedder,
+ similarity_threshold=0.7 # split when topic similarity drops below this
)
-```
-### Issue: Slow semantic chunking
-
-```python
-# Solution: Use faster embedding model or batch processing
-splitter = TextSplitter(
- method="semantic_transformer",
- embedding_model="all-MiniLM-L6-v2", # Faster model
- batch_size=32 # Batch embeddings
-)
+chunks = splitter.split(text)
```
---
-## Performance Tips
-
-### Memory Optimization
-
-```python
-# Process in batches
-def chunk_large_corpus(documents, batch_size=100):
- splitter = TextSplitter(method="recursive")
-
- for i in range(0, len(documents), batch_size):
- batch = documents[i:i + batch_size]
- chunks = splitter.split_documents(batch)
- yield from chunks
-```
-
-### Speed Optimization
+## Chunk Object
```python
-# Use faster methods for large documents
-splitter = TextSplitter(
- method="recursive", # Fastest
- chunk_size=1000
-)
-
-# Avoid LLM-based for large corpora
-# Use semantic_transformer instead of llm
+@dataclass
+class Chunk:
+ text: str
+ start_char: int
+ end_char: int
+ token_count: int
+ metadata: Dict # source_id, chunk_index, section_title, etc.
+ entities: List[Dict] # if entity-aware splitting was used
```
---
## See Also
-- [Parse Module](parse.md) - Document parsing
-- [Semantic Extract Module](semantic_extract.md) - Entity extraction
-- [Knowledge Graph Module](kg.md) - Graph construction
-- [Embeddings Module](embeddings.md) - Vector generation
-- [Vector Store Module](vector_store.md) - Vector storage
-
-## Cookbook
-
-Interactive tutorials to learn text chunking and splitting:
-- **[Chunking and Splitting](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/11_Chunking_and_Splitting.ipynb)**: Split documents for RAG and processing
- - **Topics**: Recursive character splitting, semantic splitting, token-based splitting, chunking strategies
- - **Difficulty**: Beginner
- - **Use Cases**: Preparing text for RAG, document chunking
+<CardGroup cols={2}>
+ <Card title="Parse" icon="file-lines" href="parse">
+ Parse documents before chunking.
+ </Card>
+ <Card title="Embeddings" icon="vector-square" href="embeddings">
+ Embed chunks for vector search.
+ </Card>
+ <Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">
+ Extract entities from chunks.
+ </Card>
+ <Card title="Pipeline" icon="gear" href="pipeline">
+ Integrate splitting into a pipeline.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/triplet_store.md b/docs/reference/triplet_store.md
index c9275c78..9eb5605e 100644
--- a/docs/reference/triplet_store.md
+++ b/docs/reference/triplet_store.md
@@ -1,284 +1,124 @@
-# Triplet Store
-
-> **Store and query RDF triplets with SPARQL support and semantic reasoning using industry-standard triplet stores.**
-
---
-
-## 🎯 Overview
-
-The **Triplet Store Module** provides storage and querying for RDF (Resource Description Framework) triplets. It supports industry-standard triplet stores with SPARQL querying and semantic reasoning capabilities.
-
-### What is a Triplet Store?
-
-A **triplet store** (also called an RDF store) is a database designed to store and query RDF triplets. RDF triplets are statements in the form:
-
-- **Subject**: The entity being described
-- **Predicate**: The relationship or property
-- **Object**: The value or related entity
-
-**Example**: `` `(Apple Inc., foundedBy, Steve Jobs)` ``
-
-### Why Use the Triplet Store Module?
-
-- **W3C Standards**: Full support for RDF and SPARQL standards
-- **Semantic Reasoning**: RDFS and OWL reasoning for inference
-- **Multiple Backends**: Support for Blazegraph, Apache Jena, RDF4J
-- **SPARQL Queries**: Powerful SPARQL 1.1 query language
-- **Federation**: Query across multiple stores
-- **Bulk Loading**: High-performance data loading
-
-### How It Works
-
-1. **Store Selection**: Choose a backend (Blazegraph, Jena, RDF4J)
-2. **Triplet Storage**: Store subject-predicate-object triplets
-3. **SPARQL Queries**: Query using SPARQL 1.1
-4. **Reasoning**: Apply RDFS/OWL reasoning for inference
-5. **Federation**: Query across multiple stores if needed
-
-<div class="grid cards" markdown>
-
-- :material-graph-outline:{ .lg .middle } **RDF Storage**
-
- ---
-
- Store subject-predicate-object triplets in W3C-compliant RDF format
-
-- :material-code-braces:{ .lg .middle } **SPARQL Queries**
-
- ---
-
- Full W3C SPARQL 1.1 query language support for powerful semantic queries
-
-- :material-brain:{ .lg .middle } **Reasoning**
-
- ---
-
- RDFS and OWL reasoning for inference and knowledge discovery
-
-- :material-database-sync:{ .lg .middle } **Multiple Backends**
-
- ---
-
- Blazegraph, Apache Jena, and RDF4J support
-
-- :material-link-variant:{ .lg .middle } **Federation**
-
- ---
-
- Query across multiple triplet stores with SPARQL federation
-
-- :material-upload-multiple:{ .lg .middle } **Bulk Loading**
-
- ---
-
- High-performance bulk data loading with progress tracking
-
-</div>
-
-!!! tip "Choosing the Right Backend"
- - **Blazegraph**: High-performance, excellent for large datasets, GPU acceleration
- - **Apache Jena**: Full-featured, TDB2 storage, SHACL validation
- - **RDF4J**: Java-based, excellent tooling, multiple storage backends
-
+title: "Triplet Store Module"
+description: "RDF triple storage with SPARQL queries and bulk loading β€” Blazegraph, Apache Jena, and RDF4J."
+icon: "table"
---
-## βš™οΈ Algorithms Used
-
-### Query Algorithms
-- **SPARQL Query Optimization**: Join reordering with selectivity estimation
-- **Triplet Pattern Matching**: Index-based lookup with B+ trees
-- **Graph Pattern Matching**: Subgraph isomorphism with backtracking
-- **Query Planning**: Cost-based optimization with statistics
-- **Join Algorithms**: Hash join, merge join, nested loop join
-- **Filter Pushdown**: Early filter application for performance
-
-### Indexing
-- **SPO Index**: Subject-Predicate-Object index for subject lookups
-- **POS Index**: Predicate-Object-Subject index for predicate lookups
-- **OSP Index**: Object-Subject-Predicate index for object lookups
-- **Six-Index Scheme**: All permutations (SPO, SOP, PSO, POS, OSP, OPS) for optimal query performance
-- **B+ Tree Indexing**: Efficient range queries and sorted access
-- **Hash Indexing**: O(1) exact match lookups
-
-### Reasoning Algorithms
-- **RDFS Reasoning**: Subclass/subproperty inference, domain/range inference
-- **OWL Reasoning**: Class hierarchy, property characteristics, cardinality constraints
-- **Forward Chaining**: Materialization of inferred triplets
-- **Backward Chaining**: On-demand inference during query execution
-- **Rule-Based Inference**: Custom SWRL rules
-
-### Bulk Loading
-- **Batch Processing**: Chunked triplet insertion with configurable batch size
-- **Parallel Loading**: Multi-threaded data loading
-- **Index Building**: Deferred index construction for faster loading
-- **Transaction Management**: Atomic batch commits with rollback support
+> Store and query RDF triplets with SPARQL support.
---
-## Main Classes
-
-### TripletStore
-
-Main interface for triplet store operations.
+## Overview
-**Methods:**
+The **Triplet Store Module** provides W3C-standard RDF storage with full SPARQL query support. Use it when you need semantic web compatibility, OWL reasoning, or SPARQL-based queries.
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `__init__(backend, endpoint)` | Initialize triplet store | Factory pattern |
-| `add_triplet(triplet)` | Add single triplet | Single insert |
-| `add_triplets(triplets, batch_size)` | Add multiple triplets | Bulk load with batching |
-| `get_triplets(s, p, o)` | Retrieve triplets | Pattern matching |
-| `delete_triplet(triplet)` | Delete triplet | Pattern matching deletion |
-| `execute_query(query)` | Execute SPARQL | Query engine delegation |
-
-### BulkLoader
-
-High-volume data loading utility.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `load_triplets(triplets, store)` | Bulk load triplets | Batch processing with retries |
-
-### QueryEngine
-
-SPARQL query execution and optimization engine.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `execute(query)` | Execute SPARQL query | Query execution |
-| `optimize(query)` | Optimize SPARQL query | Query rewriting |
-| `expand_entity_uri(uri, store, ...)` | Expand aligned entity URIs | Bidirectional SPARQL lookup |
-| `build_values_clause(var, uris)` | Generate VALUES clause | String formatting |
+Backends: **Blazegraph**, **Apache Jena (Fuseki)**, **RDF4J**.
---
-## Cookbook
-
-Interactive tutorials that use triplet stores:
-
-- **[Reasoning and Inference](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb)**: Use logical reasoning with SPARQL and triplet stores
- - **Topics**: SPARQL reasoning, RDF stores, inference engines
- - **Difficulty**: Advanced
- - **Use Cases**: Semantic reasoning, SPARQL queries, RDF-based knowledge graphs
-
-## πŸš€ Usage
-
-### Initialization
+## Basic Usage
```python
from semantica.triplet_store import TripletStore
-# Initialize Blazegraph store
store = TripletStore(
backend="blazegraph",
- endpoint="http://localhost:9999/blazegraph"
+ endpoint="http://localhost:9999/blazegraph/sparql"
)
-```
-
-### Adding Data
-
-```python
-from semantica.semantic_extract.triplet_extractor import Triplet
-# Single triplet
-triplet = Triplet("http://s", "http://p", "http://o")
-store.add_triplet(triplet)
+# Add triplets
+store.add_triplet(
+ subject="http://example.org/apple_inc",
+ predicate="http://example.org/founded_by",
+ obj="http://example.org/steve_jobs"
+)
# Bulk load
-triplets = [Triplet(f"http://s{i}", "http://p", "http://o") for i in range(1000)]
-store.add_triplets(triplets)
+store.add_triplets_bulk(triplets)
```
-### Querying
+---
+
+## SPARQL Queries
```python
-query = """
-SELECT ?s ?p ?o
-WHERE {
- ?s ?p ?o
-}
-LIMIT 10
-"""
-results = store.execute_query(query)
+# SELECT query
+results = store.sparql("""
+ PREFIX ex: <http://example.org/>
+ SELECT ?person ?company WHERE {
+ ?person ex:founded ?company .
+ ?company ex:located_in ex:SiliconValley .
+ }
+""")
+
+# CONSTRUCT query (returns graph)
+graph = store.sparql_construct("""
+ PREFIX ex: <http://example.org/>
+ CONSTRUCT {
+ ?s ex:connected_to ?o
+ } WHERE {
+ ?s ex:founded ?company .
+ ?company ex:has_investor ?o .
+ }
+""")
```
-### Named Graph Partitions
+---
-Use named graphs to partition RDF data inside one store while keeping backward compatibility.
+## Backends
```python
-from semantica.semantic_extract.triplet_extractor import Triplet
-
-# Write into a specific graph partition
-store.add_triplet(
- Triplet("http://entity/1", "http://relation/type", "http://TypeA"),
- graph="http://example.org/graphs/partition-a",
+# Blazegraph
+store = TripletStore(
+ backend="blazegraph",
+ endpoint="http://localhost:9999/blazegraph/sparql",
+ namespace="semantica"
)
-# Query only one graph as default dataset
-result_a = store.execute_query(
- "SELECT ?s ?p ?o WHERE { ?s ?p ?o }",
- graph="http://example.org/graphs/partition-a",
+# Apache Jena Fuseki
+store = TripletStore(
+ backend="jena",
+ endpoint="http://localhost:3030/dataset/sparql",
+ update_endpoint="http://localhost:3030/dataset/update"
)
-# Query multiple named graphs (use GRAPH pattern in WHERE)
-result_multi = store.execute_query(
- """
- SELECT ?g ?s ?p ?o WHERE {
- GRAPH ?g { ?s ?p ?o }
- }
- """,
- graphs=[
- "http://example.org/graphs/partition-a",
- "http://example.org/graphs/partition-b",
- ],
+# RDF4J
+store = TripletStore(
+ backend="rdf4j",
+ server_url="http://localhost:8080/rdf4j-server",
+ repository_id="semantica"
)
```
-Notes:
-- `graph` injects `FROM <...>` before `WHERE`.
-- `graphs` injects `FROM NAMED <...>` before `WHERE`.
-- If not provided, existing behavior is unchanged.
-
-### Alignment-Aware Queries
-
-In complex enterprise environments with multiple data sources, you may want queries to seamlessly retrieve instances across aligned classes. For example, retrieving all http://schema.org/Person instances when querying for your internal http://internal.org/ontology/Employee class.
-
-The QueryEngine provides helper methods to expand entity URIs based on stored alignments (e.g., owl:equivalentClass, owl:sameAs, skos:exactMatch) and safely inject them into your queries using SPARQL VALUES clauses.
+---
-Expanding URIs in Queries
-You can expand a URI and build an alignment-aware query dynamically:
+## Import / Export
```python
-from semantica.triplet_store.query_engine import QueryEngine
-
-engine = QueryEngine()
+# Import from file
+store.import_file("ontology.ttl", format="turtle")
+store.import_file("data.jsonld", format="json-ld")
-# i) Expand the base URI to include all aligned equivalents
-expanded_uris = engine.expand_entity_uri(
- entity_uri="[http://internal.org/ontology/Employee](http://internal.org/ontology/Employee)",
- store_backend=store_backend,
- use_alignments=True
-)
-
-# ii) Build a SPARQL VALUES clause
-values_clause = engine.build_values_clause("entity_class", expanded_uris)
-# Result: VALUES ?entity_class { [http://internal.org/ontology/Employee](http://internal.org/ontology/Employee) [http://schema.org/Person](http://schema.org/Person) }
+# Export to file
+store.export("output.ttl", format="turtle")
+store.export("output.nt", format="nt")
+```
-# iii) Inject the clause into your query template
-query = f"""
-SELECT ?instance ?name WHERE {{
- {values_clause}
- ?instance a ?entity_class .
- ?instance [http://schema.org/name](http://schema.org/name) ?name .
-}}
-"""
+---
-# Execute the query to retrieve results across all aligned ontologies
-results = engine.execute_query(query, store_backend)
-```
+## See Also
+
+<CardGroup cols={2}>
+ <Card title="Export" icon="file-export" href="export">
+ Export to RDF formats.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Load OWL ontologies into a triplet store.
+ </Card>
+ <Card title="Reasoning" icon="microchip" href="reasoning">
+ SPARQL-based reasoning.
+ </Card>
+ <Card title="Graph Store" icon="server" href="graph_store">
+ Property graph alternative for Cypher queries.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/utils.md b/docs/reference/utils.md
index 5baa16e9..2f5b955e 100644
--- a/docs/reference/utils.md
+++ b/docs/reference/utils.md
@@ -1,128 +1,46 @@
-# Utils
-
-> **Shared utilities for logging, validation, error handling, and common operations.**
-
---
-
-## 🎯 Overview
-
-The **Utils Module** provides shared utilities used throughout all Semantica modules. It includes logging, error handling, validation, progress tracking, and common helper functions.
-
-### What is the Utils Module?
-
-The Utils module provides:
-
-- **Logging**: Structured logging with performance tracking
-- **Error Handling**: Custom exception hierarchy and error formatting
-- **Validation**: Data validation for entities, relationships, and configuration
-- **Progress Tracking**: Track long-running operations
-- **Helpers**: Common functions for text cleaning, hashing, file I/O
-- **Type Definitions**: Shared TypedDicts and Enums for type safety
-
-### Why Use the Utils Module?
-
-- **Consistency**: Shared utilities ensure consistent behavior across modules
-- **Error Handling**: Standardized error handling and reporting
-- **Logging**: Unified logging across all modules
-- **Validation**: Reusable validation functions
-- **Type Safety**: Shared type definitions for better IDE support
-
-### How It Works
-
-The Utils module is used internally by all Semantica modules. You typically don't use it directly, but it provides:
-
-- **Logging Functions**: `` `get_logger()` ``, `` `setup_logging()` ``
-- **Validation Functions**: `` `validate_entity()` ``, `` `validate_relationship()` ``
-- **Error Classes**: Custom exceptions for different error types
-- **Progress Tracking**: `` `ProgressTracker` `` for long operations
-- **Helper Functions**: Text cleaning, hashing, file operations
-
-<div class="grid cards" markdown>
-
-- :material-console-line:{ .lg .middle } **Logging**
-
- ---
-
- Structured logging with performance tracking and error reporting
-
-- :material-alert-circle-outline:{ .lg .middle } **Error Handling**
-
- ---
-
- Custom exception hierarchy and error formatting
-
-- :material-check-all:{ .lg .middle } **Validation**
-
- ---
-
- Data validation for entities, relationships, and configuration
-
-- :material-progress-clock:{ .lg .middle } **Progress Tracking**
-
- ---
-
- Track long-running operations with console or file output
-
-- :material-tools:{ .lg .middle } **Helpers**
-
- ---
-
- Common functions for text cleaning, hashing, and file I/O
-
-- :material-code-json:{ .lg .middle } **Type Definitions**
-
- ---
-
- Shared TypedDicts and Enums for type safety
-
-</div>
-
-!!! tip "When to Use"
- - **Development**: Use `setup_logging` to configure output.
- - **Data Cleaning**: Use `clean_text` and `normalize_entities`.
- - **Validation**: Use `validate_data` before processing external input.
- - **Debugging**: Use `log_performance` to find bottlenecks.
-
+title: "Utils Module"
+description: "Shared utilities for logging, validation, error handling, progress tracking, and common operations."
+icon: "wrench"
---
-## βš™οΈ Key Components
-
-### Logging
-- **Structured Output**: JSON or formatted text logs.
-- **Performance Metrics**: Decorators for timing functions.
-- **Quality Logging**: Specialized loggers for data quality issues.
-
-### Validation
-- **Schema Validation**: Check dictionary structure against requirements.
-- **Type Checking**: Runtime type validation.
-- **Constraint Checking**: Numeric ranges, string lengths, regex patterns.
-
-### Progress Tracking
-- **Multi-Environment**: Supports Console (tqdm), Jupyter, and File logging.
-- **Module Awareness**: Tracks progress per module.
+> Internal utilities used across all Semantica modules β€” logging, validation, error handling, and helpers.
---
-## Main Classes
-
-### Logger
+## Overview
+
+The Utils module provides shared infrastructure used throughout Semantica. You typically won't call it directly, but its APIs are available when you need fine-grained control.
+
+<CardGroup cols={3}>
+ <Card title="Logging" icon="terminal">
+ Structured logging with performance decorators and quality tracking.
+ </Card>
+ <Card title="Error Handling" icon="circle-exclamation">
+ Custom exception hierarchy and standardized error formatting.
+ </Card>
+ <Card title="Validation" icon="circle-check">
+ Data validation for entities, relationships, and configuration.
+ </Card>
+ <Card title="Progress Tracking" icon="clock">
+ Track long-running operations in console, Jupyter, or file output.
+ </Card>
+ <Card title="Helpers" icon="toolbox">
+ Text cleaning, hashing, and safe file operations.
+ </Card>
+ <Card title="Type Definitions" icon="code">
+ Shared TypedDicts and Enums for type safety across modules.
+ </Card>
+</CardGroup>
-Centralized logging configuration.
-
-**Functions:**
-
-| Function | Description |
-|----------|-------------|
-| `setup_logging(level)` | Configure global logging |
-| `get_logger(name)` | Get named logger instance |
-| `log_performance(func)` | Decorator for timing |
+---
-**Example:**
+## Logging
```python
from semantica.utils import setup_logging, get_logger, log_performance
-setup_logging(level="INFO")
+setup_logging(level="INFO") # "DEBUG" | "INFO" | "WARNING" | "ERROR"
logger = get_logger(__name__)
@log_performance
@@ -130,98 +48,84 @@ def process_data(data):
logger.info(f"Processing {len(data)} items")
```
-### Validators
-
-Data validation functions.
-
-**Functions:**
+```bash
+export SEMANTICA_LOG_LEVEL=DEBUG
+export SEMANTICA_LOG_FORMAT=json # "json" | "text"
+export SEMANTICA_PROGRESS_BAR=true
+```
-| Function | Description |
-|----------|-------------|
-| `validate_entity(data)` | Check entity structure |
-| `validate_config(cfg)` | Check configuration |
+---
-**Example:**
+## Validation
```python
-from semantica.utils import validate_entity, ValidationError
+from semantica.utils import validate_entity, validate_config, ValidationError
try:
- validate_entity({"id": "1", "type": "PERSON"})
+ validate_entity({"id": "1", "type": "PERSON", "text": "Alice"})
except ValidationError as e:
print(f"Invalid entity: {e}")
```
-### ProgressTracker
-
-Tracks execution progress.
-
-**Classes:**
+| Function | Description |
+|----------|-------------|
+| `validate_entity(data)` | Check entity structure |
+| `validate_config(cfg)` | Check configuration dict |
-| Class | Description |
-|-------|-------------|
-| `ProgressTracker` | Main tracker interface |
-| `ConsoleProgressDisplay` | CLI output |
+---
-**Example:**
+## Progress Tracking
```python
from semantica.utils import track_progress
-for item in track_progress(items, desc="Processing"):
+for item in track_progress(items, desc="Processing documents"):
process(item)
```
+Supports console (tqdm), Jupyter notebooks, and file logging automatically.
+
---
-## Convenience Functions
+## Helper Functions
```python
from semantica.utils import clean_text, hash_data, safe_filename
-# Text cleaning
-clean = clean_text(" Hello World ") # "Hello World"
-
-# Hashing
-id = hash_data({"key": "value"})
-
-# File safety
-fname = safe_filename("My File?.txt") # "My_File_.txt"
+clean = clean_text(" Hello World ") # "Hello World"
+uid = hash_data({"key": "value"}) # SHA-256 hex digest
+fname = safe_filename("My File?.txt") # "My_File_.txt"
```
---
-## Configuration
+## Exception Hierarchy
-### Environment Variables
+```python
+from semantica.utils import SemanticaError, ValidationError, ProcessingError
-```bash
-export SEMANTICA_LOG_LEVEL=DEBUG
-export SEMANTICA_LOG_FORMAT=json
-export SEMANTICA_PROGRESS_BAR=true
+try:
+ ...
+except ValidationError as e:
+ # Input data did not pass validation
+ ...
+except ProcessingError as e:
+ # Failure during extraction or graph construction
+ ...
+except SemanticaError as e:
+ # Catch-all for all framework errors
+ ...
```
---
-## Best Practices
-
-1. **Use `get_logger`**: Always use `get_logger(__name__)` instead of `print` for production code.
-2. **Validate Early**: Validate input data at the boundary (Ingest/Parse) using `validate_data`.
-3. **Handle Exceptions**: Catch `SemanticaError` for framework-specific errors.
-4. **Clean Text**: Use `clean_text` before embedding or extraction to improve quality.
-
----
-
-## Cookbook
-
-The Utils module is used throughout all Semantica modules. See any cookbook tutorial for examples of logging, validation, and error handling in practice.
-
-- **[Welcome to Semantica](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)**: See utils in action across all modules
- - **Topics**: Framework overview, all modules, utilities
- - **Difficulty**: Beginner
- - **Use Cases**: Understanding utility functions used throughout Semantica
-
## See Also
-- [Core Module](core.md) - Uses Utils for infrastructure
-- [Pipeline Module](pipeline.md) - Uses ProgressTracker
+<CardGroup cols={2}>
+ <Card title="Core" icon="gear" href="core">
+ Framework orchestration that uses Utils internally.
+ </Card>
+ <Card title="Pipeline" icon="arrows-turn-to-dots" href="pipeline">
+ Uses ProgressTracker for step-level tracking.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/vector_store.md b/docs/reference/vector_store.md
index a94b5d46..d5f76493 100644
--- a/docs/reference/vector_store.md
+++ b/docs/reference/vector_store.md
@@ -1,802 +1,191 @@
-# Vector Store
-
-> **Unified vector database interface supporting FAISS, Weaviate, Qdrant, Pinecone, and Milvus with Hybrid Search.**
-
---
-
-## 🎯 Overview
-
-The **Vector Store Module** provides a unified interface for storing and searching vector embeddings. It supports multiple backends (FAISS, Weaviate, Qdrant, Pinecone, Milvus) and enables semantic search, RAG, and similarity matching.
-
-### What is a Vector Store?
-
-A **vector store** is a database optimized for storing and searching high-dimensional vectors (embeddings). It enables:
-- **Semantic Search**: Find documents similar to a query based on meaning
-- **Similarity Matching**: Compare vectors to find similar items
-- **Hybrid Search**: Combine vector search with keyword/metadata filtering
-- **Scalable Storage**: Handle millions of vectors efficiently
-
-### Why Use the Vector Store Module?
-
-- **Multiple Backends**: Switch between FAISS (local), Weaviate, Qdrant, Pinecone, and Milvus
-- **Unified Interface**: Same API regardless of backend
-- **Hybrid Search**: Combine vector similarity with metadata filtering
-- **Performance**: Optimized for high-throughput search operations
-- **Namespace Support**: Multi-tenant isolation via namespaces
-- **Metadata Filtering**: Rich filtering capabilities for precise queries
-
-### How It Works
-
-1. **Index Creation**: Create an index optimized for your vector dimensions
-2. **Vector Storage**: Store embeddings with associated metadata
-3. **Query Processing**: Convert query text to embedding and search
-4. **Hybrid Search**: Combine vector similarity with metadata filters
-5. **Result Ranking**: Rank results by relevance and return top-k
-
-<div class="grid cards" markdown>
-
-- :material-database:{ .lg .middle } **Multi-Backend Support**
-
- ---
-
- Seamlessly switch between FAISS (Local), Weaviate, Qdrant, Pinecone, and Milvus
-
-- :material-magnify-plus:{ .lg .middle } **Hybrid Search**
-
- ---
-
- Combine dense vector similarity with sparse keyword/metadata filtering
-
-- :material-filter:{ .lg .middle } **Metadata Filtering**
-
- ---
-
- Rich filtering capabilities (eq, ne, gt, lt, in, contains)
-
-- :material-layers-triple:{ .lg .middle } **Namespace Isolation**
-
- ---
-
- Multi-tenant support via isolated namespaces
-
-- :material-flash:{ .lg .middle } **Performance**
-
- ---
-
- Batch operations, index optimization, and caching
-
-- :material-cloud-upload:{ .lg .middle } **Cloud & Local**
-
- ---
-
- Support for both embedded (local) and cloud-native deployments
-
-</div>
-
-!!! tip "When to Use"
- - **Semantic Search**: Finding documents similar to a query
- - **RAG**: Retrieving context for LLM generation
- - **Memory**: Storing agent memories as embeddings
- - **Recommendation**: Finding similar items based on vector proximity
-
+title: "Vector Store Module"
+description: "Unified interface for FAISS, Pinecone, Weaviate, Qdrant, Milvus, and PgVector with hybrid search."
+icon: "database"
---
-## βš™οΈ Algorithms Used
-
-### Similarity Metrics
-- **Cosine Similarity**: `A Β· B / ||A|| ||B||` (Default for semantic search)
-- **Euclidean Distance (L2)**: `||A - B||`
-- **Dot Product**: `A Β· B` (Faster, requires normalized vectors)
-
-### Indexing (FAISS)
-- **Flat**: Exact search (brute force). High accuracy, slow for large datasets.
-- **IVF (Inverted File)**: Partitions space into Voronoi cells. Faster search.
-- **HNSW**: Hierarchical Navigable Small World graphs. Best trade-off for speed/accuracy.
-- **PQ (Product Quantization)**: Compresses vectors for memory efficiency.
-
-### Hybrid Search
-- **Reciprocal Rank Fusion (RRF)**: Combines ranked lists from vector search and keyword search.
- `Score = 1 / (k + rank_vector) + 1 / (k + rank_keyword)`
-- **Pre-filtering**: Apply metadata filters *before* vector search (supported by most backends).
+> Unified vector database interface supporting multiple backends and hybrid search.
---
-## Main Classes
-
-### VectorStore
-
-The main facade for all vector operations.
+## Overview
+
+The **Vector Store Module** provides a unified API for storing and searching vector embeddings across all major backends.
+
+<CardGroup cols={2}>
+ <Card title="Multi-Backend" icon="server">
+ FAISS (local), Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory.
+ </Card>
+ <Card title="Hybrid Search" icon="magnifying-glass-plus">
+ Combine dense vector similarity with sparse keyword/metadata filtering.
+ </Card>
+ <Card title="Metadata Filtering" icon="filter">
+ Rich filtering (eq, ne, gt, lt, in, contains) on any field.
+ </Card>
+ <Card title="Namespace Isolation" icon="layer-group">
+ Multi-tenant support via isolated namespaces.
+ </Card>
+</CardGroup>
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `store_vectors(vectors, metadata)` | Store embeddings |
-| `add_documents(documents, metadata, batch_size, parallel)` | **(New)** Store documents with automatic embedding generation and parallelization |
-| `embed_batch(texts)` | **(New)** Generate embeddings for a batch of texts |
-| `search(query, k)` | Semantic search |
-| `delete(ids)` | Remove vectors |
+---
-**Example:**
+## Basic Usage
```python
from semantica.vector_store import VectorStore
-# Initialize (defaults to FAISS, parallel enabled by default with 6 workers)
-store = VectorStore(backend="faiss", dimension=1536)
+# In-memory (development)
+store = VectorStore(backend="inmemory", dimension=768)
-# 1. Store pre-computed vectors
-ids = store.store_vectors(
- vectors=[[0.1, 0.2, ...], ...],
- metadata=[{"text": "Hello"}, ...]
-)
+# FAISS (local, production)
+store = VectorStore(backend="faiss", dimension=768, index_path="store.faiss")
-# 2. Store raw documents (High Performance)
-# Automatically handles embedding generation in parallel batches (uses default 6 workers)
-ids = store.add_documents(
- documents=["Doc 1", "Doc 2", ...],
- metadata=[{"id": 1}, {"id": 2}, ...],
- batch_size=32,
- parallel=True
-)
+# Add vectors
+store.add_vectors(embeddings=embeddings, ids=["doc1", "doc2"], metadata=[{}, {}])
-# Search
-results = store.search(query_vector=[0.1, 0.2, ...], k=5)
+# Semantic search
+results = store.search(query_vector, top_k=10)
+for r in results:
+ print(f"{r['id']} β€” score: {r['score']:.3f}")
```
---
-### VectorIndexer
-
-Vector indexing engine for creating and managing vector indices.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `create_index(vectors, ids)` | Create vector index |
-| `train_index(index, vectors)` | Train index on vectors |
-| `add_to_index(index, vectors)` | Add vectors to index |
-| `optimize_index(index)` | Optimize index performance |
-
-**Example:**
-
-```python
-from semantica.vector_store import VectorIndexer
-import numpy as np
-
-indexer = VectorIndexer(backend="faiss", dimension=768)
-
-# Create index
-vectors = [np.random.rand(768) for _ in range(1000)]
-vector_ids = [f"vec_{i}" for i in range(1000)]
-index = indexer.create_index(vectors, vector_ids)
-
-# Optimize index
-indexer.optimize_index(index)
-```
+## Backends
+
+<Tabs>
+ <Tab title="FAISS">
+ ```python
+ store = VectorStore(
+ backend="faiss",
+ dimension=768,
+ index_type="IVF", # Flat, IVF, HNSW
+ index_path="store.faiss"
+ )
+ ```
+ Best for: local development, on-premise production with no external services.
+ </Tab>
+ <Tab title="Pinecone">
+ ```bash
+ pip install "semantica[pinecone]"
+ ```
+ ```python
+ store = VectorStore(
+ backend="pinecone",
+ dimension=768,
+ api_key=os.getenv("PINECONE_API_KEY"),
+ index_name="semantica-index",
+ environment="us-east-1-aws"
+ )
+ ```
+ </Tab>
+ <Tab title="Weaviate">
+ ```bash
+ pip install "semantica[weaviate]"
+ ```
+ ```python
+ store = VectorStore(
+ backend="weaviate",
+ dimension=768,
+ url="http://localhost:8080",
+ class_name="Document"
+ )
+ ```
+ </Tab>
+ <Tab title="Qdrant">
+ ```bash
+ pip install "semantica[qdrant]"
+ ```
+ ```python
+ store = VectorStore(
+ backend="qdrant",
+ dimension=768,
+ url="http://localhost:6333",
+ collection_name="semantica"
+ )
+ ```
+ </Tab>
+</Tabs>
---
-### VectorRetriever
-
-Vector retrieval and similarity search engine.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `search_similar(query, vectors, ids, k)` | Find k most similar vectors |
-| `batch_search(queries, vectors, ids, k)` | Batch similarity search |
-| `get_vector(vector_id)` | Retrieve vector by ID |
+## Hybrid Search
-**Example:**
+Combines vector similarity with keyword/metadata filters.
```python
-from semantica.vector_store import VectorRetriever
-import numpy as np
-
-retriever = VectorRetriever(backend="faiss")
-
-# Search similar vectors
-query_vector = np.random.rand(768)
-vectors = [np.random.rand(768) for _ in range(1000)]
-vector_ids = [f"vec_{i}" for i in range(1000)]
-
-results = retriever.search_similar(query_vector, vectors, vector_ids, k=10)
-print(f"Found {len(results)} similar vectors")
-```
-
----
-
-### VectorManager
-
-Vector store management and operations coordinator.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `create_store(backend, config)` | Create vector store |
-| `get_store(store_id)` | Get store by ID |
-| `list_stores()` | List all stores |
-| `delete_store(store_id)` | Delete store |
-
-**Example:**
-
-```python
-from semantica.vector_store import VectorManager
-
-manager = VectorManager()
-
-# Create store
-store = manager.create_store("faiss", {"dimension": 768})
-
-# List stores
-stores = manager.list_stores()
-print(f"Active stores: {stores}")
-```
-
----
-
-### HybridSearch
-
-Combines vector and metadata search.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `search(query_vec, filter)` | Execute hybrid query |
-
-**Example:**
-
-```python
-from semantica.vector_store import HybridSearch, MetadataFilter
-
-searcher = HybridSearch(store)
-filters = MetadataFilter().eq("category", "news").gt("date", "2023-01-01")
-
-results = searcher.search(
- query_vector=emb,
- filter=filters,
- k=10
-)
-```
-
-### Store Backends
-
-Backend-specific implementations:
-- `FAISSStore`: Local, in-memory/disk.
-- `WeaviateStore`: Schema-aware vector DB.
-- `QdrantStore`: Rust-based high-performance DB.
-- `MilvusStore`: Scalable cloud-native DB.
-
-#### FAISSStore
-
-Local vector storage with multiple index types.
-
-**Helper Classes:**
-- `FAISSIndex`: Index wrapper
-- `FAISSSearch`: Search operations
-- `FAISSIndexBuilder`: Index construction
-
-**Example:**
-
-```python
-from semantica.vector_store import FAISSStore, FAISSIndexBuilder
-import numpy as np
-
-store = FAISSStore(dimension=768)
-
-# Create HNSW index
-builder = FAISSIndexBuilder()
-index = builder.build(index_type="hnsw", dimension=768, m=16)
-
-# Add vectors
-vectors = np.random.rand(1000, 768).astype('float32')
-store.add_vectors(vectors, ids=[f"vec_{i}" for i in range(1000)])
-
-# Search
-query = np.random.rand(768).astype('float32')
-distances, indices = store.search(index, query, k=10)
-```
-
-#### WeaviateStore
-
-Schema-aware vector database with GraphQL.
-
-**Helper Classes:**
-- `WeaviateClient`: Client wrapper
-- `WeaviateSchema`: Schema management
-- `WeaviateQuery`: GraphQL queries
-
-**Example:**
-
-```python
-from semantica.vector_store import WeaviateStore
-
-store = WeaviateStore(url="http://localhost:8080")
-store.connect()
-
-# Create schema
-store.create_schema(
- "Document",
- properties=[{"name": "text", "dataType": "text"}]
-)
-
-# Add objects
-store.add_objects(
- objects=[{"text": "Hello world"}],
- vectors=[[0.1, 0.2, ...]]
-)
-```
-
-#### QdrantStore
-
-High-performance Rust-based vector database.
-
-**Helper Classes:**
-- `QdrantClient`: Client wrapper
-- `QdrantCollection`: Collection management
-- `QdrantSearch`: Search operations
-
-**Example:**
-
-```python
-from semantica.vector_store import QdrantStore
-
-store = QdrantStore(url="http://localhost:6333")
-store.connect()
-
-# Create collection
-collection = store.create_collection("my-collection", dimension=768)
-
-# Upsert with payload
-store.upsert_vectors(
- collection,
- vectors=[[0.1, 0.2, ...], ...],
- ids=["vec_1", "vec_2"],
- payloads=[{"category": "news"}, ...]
+results = store.hybrid_search(
+ query_vector=query_embedding,
+ query_text="machine learning", # keyword component
+ top_k=10,
+ alpha=0.7, # 0=keyword only, 1=vector only
+ filters={"category": "research", "year": {"$gte": 2022}}
)
```
-#### MilvusStore
-
-Scalable cloud-native vector database.
-
-**Helper Classes:**
-- `MilvusClient`: Client wrapper
-- `MilvusCollection`: Collection management
-- `MilvusSearch`: Search operations
-
-**Example:**
-
-```python
-from semantica.vector_store import MilvusStore
-
-store = MilvusStore(host="localhost", port="19530")
-store.connect()
-
-# Create collection
-collection = store.create_collection(
- "my-collection",
- dimension=768,
- metric_type="L2"
-)
-
-# Insert vectors
-store.insert_vectors(collection, vectors, ids)
-```
-
---
-## Metadata and Hybrid Search
-
-### MetadataFilter
-
-Metadata filtering for hybrid search.
-
-**Operators:**
-- `eq(field, value)`: Equality
-- `ne(field, value)`: Not equal
-- `gt(field, value)`: Greater than
-- `lt(field, value)`: Less than
-- `in_list(field, values)`: In list
-- `contains(field, value)`: Contains
-
-**Example:**
+## Metadata Filtering
```python
-from semantica.vector_store import MetadataFilter
-
-filter = MetadataFilter() \
- .eq("category", "science") \
- .gt("year", 2020) \
- .in_list("tags", ["AI", "ML"])
-
-# Test metadata
-metadata = {"category": "science", "year": 2023, "tags": ["AI"]}
-matches = filter.matches(metadata) # True
-```
+# Equality
+results = store.search(query_vector, filters={"author": "John Smith"})
-### SearchRanker
+# Range
+results = store.search(query_vector, filters={"date": {"$gte": "2023-01-01"}})
-Result ranking and fusion for multi-source search.
-
-**Strategies:**
-- `reciprocal_rank_fusion`: RRF algorithm
-- `weighted_average`: Weighted score fusion
-
-**Example:**
-
-```python
-from semantica.vector_store import SearchRanker
+# Set membership
+results = store.search(query_vector, filters={"tag": {"$in": ["ai", "ml"]}})
-ranker = SearchRanker(strategy="reciprocal_rank_fusion")
-
-# Fuse multiple result lists
-results1 = [{"id": "vec_1", "score": 0.9}, ...]
-results2 = [{"id": "vec_2", "score": 0.85}, ...]
-
-fused = ranker.rank([results1, results2], k=60)
-```
-
-### MetadataStore
-
-Metadata storage and querying.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `store_metadata(id, metadata)` | Store metadata |
-| `get_metadata(id)` | Retrieve metadata |
-| `query_metadata(conditions, operator)` | Query by metadata |
-
-**Example:**
-
-```python
-from semantica.vector_store import MetadataStore
-
-store = MetadataStore()
-store.store_metadata("vec_1", {"category": "science", "year": 2023})
-
-# Query
-matching_ids = store.query_metadata({"category": "science"}, operator="AND")
-```
-
-### MetadataIndex
-
-Metadata indexing for fast lookups.
-
-**Example:**
-
-```python
-from semantica.vector_store import MetadataIndex
-
-index = MetadataIndex()
-index.index_metadata("vec_1", {"category": "science"})
-
-# Query indexed metadata
-matching_ids = index.query({"category": "science"}, operator="AND")
-```
-
-### MetadataSchema
-
-Schema validation for metadata.
-
-**Example:**
-
-```python
-from semantica.vector_store import MetadataSchema
-
-schema = MetadataSchema({
- "category": {"type": str, "required": True},
- "year": {"type": int, "required": True}
+# Compound
+results = store.search(query_vector, filters={
+ "$and": [{"category": "research"}, {"year": {"$gte": 2022}}]
})
-
-# Validate
-is_valid = schema.validate({"category": "science", "year": 2023})
-```
-
----
-
-## Namespace Management
-
-### NamespaceManager
-
-Multi-tenant namespace isolation.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `create_namespace(name, description)` | Create namespace |
-| `add_vector_to_namespace(id, namespace)` | Add vector to namespace |
-| `get_namespace_vectors(namespace)` | Get namespace vectors |
-| `delete_namespace(name)` | Delete namespace |
-
-**Example:**
-
-```python
-from semantica.vector_store import NamespaceManager
-
-manager = NamespaceManager()
-
-# Create namespace
-namespace = manager.create_namespace("tenant1", "Tenant 1 vectors")
-
-# Add vectors
-for i in range(100):
- manager.add_vector_to_namespace(f"vec_{i}", "tenant1")
-
-# Get vectors
-vectors = manager.get_namespace_vectors("tenant1")
-```
-
-### Namespace
-
-Namespace dataclass with access control.
-
-**Attributes:**
-- `name`: Namespace name
-- `description`: Description
-- `metadata`: Additional metadata
-- `permissions`: Access control permissions
-
-**Example:**
-
-```python
-from semantica.vector_store import Namespace
-
-namespace = Namespace(
- name="docs",
- description="Document vectors",
- metadata={"owner": "user1"}
-)
-
-# Set permissions
-namespace.set_access_control("user1", ["read", "write"])
-namespace.set_access_control("user2", ["read"])
-
-# Check permissions
-has_write = namespace.has_permission("user1", "write") # True
```
---
-## Convenience Functions
-
-Quick access wrappers for common vector store operations.
-
-### store_vectors
-
-Store vectors with metadata.
-
-```python
-from semantica.vector_store import store_vectors
-
-ids = store_vectors(
- vectors=[[0.1, 0.2, ...], ...],
- metadata=[{"text": "Hello"}, ...],
- method="default"
-)
-```
-
-### search_vectors
-
-Search for similar vectors.
-
-```python
-from semantica.vector_store import search_vectors
-
-results = search_vectors(
- query_vector=[0.1, 0.2, ...],
- vectors=all_vectors,
- vector_ids=all_ids,
- k=10,
- method="default"
-)
-```
-
-### update_vectors
-
-Update existing vectors.
-
-```python
-from semantica.vector_store import update_vectors
-
-success = update_vectors(
- vector_ids=["vec_1", "vec_2"],
- new_vectors=[[0.2, 0.3, ...], ...],
- method="default"
-)
-```
-
-### delete_vectors
-
-Delete vectors by ID.
-
-```python
-from semantica.vector_store import delete_vectors
-
-success = delete_vectors(
- vector_ids=["vec_1", "vec_2"],
- method="default"
-)
-```
-
-### create_index
-
-Create vector index.
-
-```python
-from semantica.vector_store import create_index
-
-index = create_index(
- vectors=[[0.1, 0.2, ...], ...],
- index_type="hnsw",
- method="default"
-)
-```
-
-### hybrid_search
-
-Hybrid vector and metadata search.
-
-```python
-from semantica.vector_store import hybrid_search, MetadataFilter
-
-filter = MetadataFilter().eq("category", "news")
-results = hybrid_search(
- query_vector=[0.1, 0.2, ...],
- vectors=all_vectors,
- metadata=all_metadata,
- vector_ids=all_ids,
- filter=filter,
- k=10,
- method="default"
-)
-```
-
-### filter_metadata
-
-Filter vectors by metadata.
-
-```python
-from semantica.vector_store import filter_metadata
-
-matching_ids = filter_metadata(
- metadata=all_metadata,
- conditions={"category": "news"},
- operator="AND",
- method="default"
-)
-```
-
-### manage_namespace
-
-Manage vector namespaces.
+## Namespaces (Multi-Tenant)
```python
-from semantica.vector_store import manage_namespace
+store = VectorStore(backend="faiss", dimension=768)
-namespace = manage_namespace(
- action="create",
- namespace="tenant1",
- description="Tenant 1 vectors",
- method="default"
-)
-```
-
-### get_vector_store_method
-
-Get registered vector store method.
-
-```python
-from semantica.vector_store import get_vector_store_method
-
-method = get_vector_store_method(task="store", name="custom_store")
-```
-
-### list_available_methods
+store.add_vectors(embeddings, ids, namespace="tenant_a")
+store.add_vectors(embeddings, ids, namespace="tenant_b")
-List all registered methods.
-
-```python
-from semantica.vector_store import list_available_methods
-
-methods = list_available_methods()
-print(f"Available methods: {methods}")
+results = store.search(query_vector, namespace="tenant_a")
```
---
-## Configuration
-
-### Environment Variables
-
-```bash
-export VECTOR_STORE_BACKEND=weaviate
-export WEAVIATE_URL=http://localhost:8080
-```
-
-### YAML Configuration
-
-```yaml
-vector_store:
- backend: faiss # or weaviate, qdrant, milvus
- dimension: 1536
- metric: cosine
-
- faiss:
- index_type: HNSW
-
- weaviate:
- url: http://localhost:8080
-```
-
----
-
-## Integration Examples
-
-### RAG Retrieval
+## Batch Operations
```python
-from semantica.embeddings import EmbeddingGenerator
-from semantica.vector_store import VectorStore
-
-# 1. Embed Query
-embedder = EmbeddingGenerator()
-query_vec = embedder.generate("What is the capital of France?")
+# Batch add
+store.add_vectors_batch(embeddings_list, ids_list, batch_size=1000)
-# 2. Search
-store = VectorStore()
-results = store.search(query_vec, k=3)
+# Batch delete
+store.delete_vectors(ids=["doc1", "doc2", "doc3"])
-# 3. Use Context
-context = "\n".join([r.metadata['text'] for r in results])
-print(f"Context: {context}")
+# Update metadata
+store.update_metadata("doc1", {"status": "archived"})
```
---
-## Best Practices
-
-1. **Normalize Vectors**: Always normalize vectors if using Cosine Similarity or Dot Product.
-2. **Use HNSW**: For FAISS, `HNSW` is usually the best default index type for performance/recall balance.
-3. **Batch Operations**: Use `store_vectors` with batches (e.g., 100 items) rather than one by one.
-4. **Filter First**: In hybrid search, restrictive filters significantly improve performance.
-
----
-
-## Troubleshooting
-
-**Issue**: `DimensionMismatchError`
-**Solution**: Ensure your embedding model dimension (e.g., 1536 for OpenAI) matches the VectorStore dimension.
-
-**Issue**: FAISS index not saved.
-**Solution**: Call `store.save("index.faiss")` explicitly for local FAISS indices, or use a persistent backend like Weaviate/Qdrant.
-
----
-
## See Also
-- [High-Performance Usage Guide](../vector_store_usage.md) - **(New)** Parallel ingestion and batching guide
-- [Embeddings Module](embeddings.md) - Generates the vectors
-- [Context Module](context.md) - Uses vector store for memory
-- [Ingest Module](ingest.md) - Source of data
-
-## Cookbook
-
-Interactive tutorials to learn vector stores:
-
-- **[Vector Store](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/13_Vector_Store.ipynb)**: Set up and use vector stores for similarity search
- - **Topics**: FAISS, Weaviate, Qdrant, hybrid search, metadata filtering
- - **Difficulty**: Intermediate
- - **Use Cases**: Storing and searching embeddings, building RAG systems
-- **[Advanced Vector Store and Search](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/Advanced_Vector_Store_and_Search.ipynb)**: Advanced vector store operations and optimization
- - **Topics**: Index optimization, hybrid search, performance tuning, namespace management
- - **Difficulty**: Advanced
- - **Use Cases**: Production deployments, performance optimization
+<CardGroup cols={2}>
+ <Card title="Embeddings" icon="vector-square" href="embeddings">
+ Generate the vectors stored here.
+ </Card>
+ <Card title="Context" icon="brain" href="context">
+ AgentContext uses VectorStore for memory.
+ </Card>
+ <Card title="PgVector Guide" icon="database" href="../vector_stores/pgvector">
+ PostgreSQL vector storage with pgvector.
+ </Card>
+ <Card title="Ingest" icon="download" href="ingest">
+ Ingest documents before embedding and storing.
+ </Card>
+</CardGroup>
diff --git a/docs/reference/visualization.md b/docs/reference/visualization.md
index 3f472cd2..aba9737e 100644
--- a/docs/reference/visualization.md
+++ b/docs/reference/visualization.md
@@ -1,302 +1,146 @@
-# Visualization
-
-> **Comprehensive visualization suite for Knowledge Graphs, Ontologies, Embeddings, and Temporal data.**
-
---
-
-## 🎯 Overview
-
-<div class="grid cards" markdown>
-
-- :material-graph:{ .lg .middle } **KG Visualization**
-
- ---
-
- Interactive network graphs with Force-directed, Hierarchical, and Circular layouts
-
-- :material-file-tree:{ .lg .middle } **Ontology View**
-
- ---
-
- Visualize class hierarchies, property domains/ranges, and taxonomy trees
-
-- :material-chart-scatter-plot:{ .lg .middle } **Embedding Projector**
-
- ---
-
- 2D/3D visualization of vector embeddings using UMAP, t-SNE, and PCA
-
-- :material-clock-time-four-outline:{ .lg .middle } **Temporal Analysis**
-
- ---
-
- Timeline views and graph evolution visualization
-
-- :material-chart-bar:{ .lg .middle } **Analytics Dashboards**
-
- ---
-
- Visual dashboards for centrality, community structure, and connectivity
-
-- :material-export:{ .lg .middle } **Multi-Format Export**
-
- ---
-
- Export to HTML (interactive), PNG, SVG, PDF, and JSON
-
-</div>
-
-!!! tip "When to Use"
- - **Exploration**: Interactively explore graph connections and clusters
- - **Reporting**: Generate static charts for reports and presentations
- - **Debugging**: Visually inspect graph structure and disconnected components
- - **Analysis**: Identify patterns, outliers, and trends in data
-
+title: "Visualization Module"
+description: "Interactive and static knowledge graph, ontology, embedding, and temporal visualization."
+icon: "chart-bar"
---
-## βš™οΈ Algorithms Used
+> Comprehensive visualization suite for knowledge graphs, ontologies, embeddings, and temporal data.
-### Layout Algorithms
+---
-The visualization module uses various layout algorithms:
+## GraphVisualizer
-- **Force-Directed**: Simulates physical forces (repulsion between nodes, springs for edges) to find equilibrium
-- **Hierarchical**: Tree-based layout for taxonomies and directed acyclic graphs (DAGs)
-- **Circular**: Arranges nodes in a circle, useful for analyzing interconnectivity
-- **Community-Based**: Groups nodes by community (Louvain/Leiden) and separates clusters
+```python
+from semantica.visualization import GraphVisualizer
-### Dimensionality Reduction
+viz = GraphVisualizer()
-The module supports multiple dimensionality reduction techniques:
+# Interactive HTML (PyVis)
+viz.visualize(graph, output="graph.html")
-- **UMAP**: Uniform Manifold Approximation and Projection - Preserves global structure better than t-SNE
-- **t-SNE**: t-Distributed Stochastic Neighbor Embedding - Good for local clustering
-- **PCA**: Principal Component Analysis - Linear projection for variance maximization
+# Static image (Matplotlib)
+viz.visualize(graph, output="graph.png", backend="matplotlib")
-### Analytics Visualization
-- **Centrality Sizing**: Node size proportional to Degree/Betweenness/PageRank.
-- **Heatmaps**: Matrix visualization for adjacency or similarity.
-- **Sankey Diagrams**: Flow visualization for lineage or process steps.
+# Open directly in browser
+viz.show(graph)
+```
---
-## Main Classes
-
-### KGVisualizer
-
-Visualizes Knowledge Graph structure and communities.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `visualize_network(graph)` | Standard network plot |
-| `visualize_communities(graph)` | Color by community |
-| `visualize_centrality(graph, centrality, centrality_type)` | Size/color by centrality |
-| `visualize_entity_types(graph)` | Entity type distribution |
-| `visualize_relationship_matrix(graph)` | Relationship frequency heatmap |
-
-**Example:**
+## Layout Options
```python
-from semantica.visualization import KGVisualizer
-
-viz = KGVisualizer(layout="force", height=800)
-fig = viz.visualize_network(kg, output="interactive")
-fig.write_html("graph.html")
+viz.visualize(
+ graph,
+ output="graph.html",
+ layout="force_directed", # force_directed | hierarchical | circular | spring
+ node_color_by="type", # color nodes by attribute
+ edge_label="relation", # show edge labels
+ max_nodes=500 # limit for large graphs
+)
```
-### OntologyVisualizer
-
-Visualizes schema and taxonomy.
-
-**Methods:**
+---
-| Method | Description |
-|--------|-------------|
-| `visualize_hierarchy(ontology)` | Tree view of classes |
-| `visualize_properties(ontology)` | Property domain/range graph |
-| `visualize_structure(ontology)` | Class-property network |
-| `visualize_class_property_matrix(ontology)` | Class vs property heatmap |
-| `visualize_metrics(ontology)` | Metrics dashboard |
-| `visualize_semantic_model(model)` | Visualize semantic model/network |
+## Ontology Visualization
-### EmbeddingVisualizer
+```python
+from semantica.visualization import OntologyVisualizer
-Project high-dimensional vectors to 2D/3D.
+viz = OntologyVisualizer()
+viz.visualize(ontology, output="ontology.html")
-**Methods:**
+# Hierarchy view
+viz.visualize_hierarchy(ontology, output="hierarchy.html")
+```
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `visualize_2d_projection(embeddings, labels, method)` | 2D Scatter plot | UMAP/t-SNE/PCA |
-| `visualize_3d_projection(embeddings, labels, method)` | 3D Scatter plot | UMAP/t-SNE/PCA |
-| `visualize_similarity_heatmap(embeddings, labels)` | Pairwise similarity | Cosine |
-| `visualize_clustering(embeddings, cluster_labels, method)` | Colored by cluster | UMAP/t-SNE/PCA |
-| `visualize_multimodal_comparison(text_emb, image_emb, audio_emb)` | Compare modalities | UMAP/PCA |
+---
-**Example:**
+## Embedding Visualization
```python
from semantica.visualization import EmbeddingVisualizer
viz = EmbeddingVisualizer()
-viz.visualize_2d_projection(
- embeddings,
- labels=labels,
- method="umap",
- output="embeddings.html"
+
+# UMAP projection
+viz.visualize(
+ embeddings=embeddings,
+ labels=labels,
+ output="embeddings.html",
+ method="umap" # umap | tsne | pca
)
```
-### SemanticNetworkVisualizer
-
-Visualizes semantic network structure and distributions.
-
-**Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `visualize_network(semantic_network)` | Network visualization |
-| `visualize_node_types(semantic_network)` | Node type distribution |
-| `visualize_edge_types(semantic_network)` | Edge type distribution |
-
-### AnalyticsVisualizer
-
-Visualizes graph analytics results.
-
-**Methods:**
+---
-| Method | Description |
-|--------|-------------|
-| `visualize_centrality_rankings(centrality, centrality_type, top_n)` | Top-k bar chart |
-| `visualize_community_structure(graph, communities)` | Community network |
-| `visualize_connectivity(connectivity)` | Components and sizes |
-| `visualize_degree_distribution(graph)` | Degree histogram |
-| `visualize_metrics_dashboard(metrics)` | Metrics dashboard |
-| `visualize_centrality_comparison(centrality_results, top_n)` | Grouped comparison |
+## Temporal Visualization
-### TemporalVisualizer
+```python
+from semantica.visualization import TemporalVisualizer
-Visualizes time-series and graph evolution.
+viz = TemporalVisualizer()
-**Methods:**
+# Timeline of graph changes
+viz.visualize_timeline(temporal_kg, output="timeline.html")
-| Method | Description |
-|--------|-------------|
-| `visualize_timeline(events)` | Event timeline |
-| `visualize_temporal_patterns(patterns)` | Pattern durations |
-| `visualize_snapshot_comparison(snapshots)` | Compare snapshots |
-| `visualize_version_history(version_history)` | Version timeline |
-| `visualize_metrics_evolution(metrics_history, timestamps)` | Metrics over time |
+# Animated graph evolution
+viz.animate(temporal_kg, output="evolution.html", fps=2)
+```
---
-## Convenience Functions
+## Distance / Ego-Mode Visualization (v0.5.0)
```python
-from semantica.visualization import (
- visualize_kg,
- visualize_embeddings,
- visualize_ontology,
- visualize_semantic_network,
- visualize_analytics,
- visualize_temporal,
- list_available_methods,
-)
-
-# One-line visualization
-visualize_kg(kg, output="graph.html")
-visualize_embeddings(embeddings, method="umap")
-visualize_ontology(ontology, method="hierarchy")
-visualize_semantic_network(semantic_network)
-visualize_analytics({"centrality": centrality}, method="centrality")
-visualize_temporal(temporal_data, method="timeline")
-list_available_methods()
-```
-
----
+from semantica.visualization import DistanceVisualizer
-## Configuration
+viz = DistanceVisualizer()
-### Environment Variables
-
-```bash
-export VISUALIZATION_DEFAULT_LAYOUT=force
-export VISUALIZATION_COLOR_SCHEME=vibrant
-export VISUALIZATION_OUTPUT_FORMAT=interactive
-```
+# Ego-mode: neighborhood of a node colored by distance band
+viz.visualize_ego(
+ graph,
+ center_node="Apple Inc.",
+ output="ego.html",
+ radius=0.5
+)
-### YAML Configuration
-
-```yaml
-visualization:
- layout:
- algorithm: force
- iterations: 50
-
- style:
- node_size: 10
- edge_width: 1
- color_scheme: "vibrant" # vibrant, pastel, dark
-
- export:
- width: 1200
- height: 800
- scale: 2.0
+# Distance matrix heatmap
+viz.visualize_distance_matrix(
+ matrix=distance_matrix,
+ labels=node_labels,
+ output="distance_heatmap.html"
+)
```
---
-## Integration Examples
+## Graph Explorer (v0.4.0/v0.5.0)
-### Exploratory Data Analysis (EDA)
+The full-featured browser UI β€” bidirectional path finding, indexed search (0.004ms on 118k nodes), workspace management.
```python
-from semantica.kg import GraphBuilder
-from semantica.visualization import KGVisualizer, AnalyticsVisualizer
-
-# 1. Build Knowledge Graph
-builder = GraphBuilder()
-kg = builder.build(sources=sample_data)
-
-# 2. Visualize Structure
-kg_viz = KGVisualizer()
-kg_viz.visualize_network(kg, output="structure.html")
-
-# 3. Visualize Analytics
-analytics_viz = AnalyticsVisualizer()
-centrality = {"rankings": [{"node": "A", "score": 0.9}, {"node": "B", "score": 0.7}]}
-analytics_viz.visualize_centrality_rankings(centrality, centrality_type="degree", top_n=10, output="centrality.png")
-analytics_viz.visualize_degree_distribution(kg, output="degree_dist.png")
-```
-
----
-
-## Best Practices
+from semantica.explorer import start_explorer
-1. **Filter First**: Don't try to visualize 1M nodes. Filter to a subgraph of <5000 nodes for readability.
-2. **Use Interactive**: Interactive HTML plots (Plotly) allow zooming and hovering, which is essential for dense graphs.
-3. **Color Meaningfully**: Use color to represent node types or communities, not just random assignment.
-4. **Size by Importance**: Map node size to centrality (e.g., PageRank) to highlight important entities.
+start_explorer(graph=kg, port=8080)
+# Opens at http://localhost:8080
+```
---
## See Also
-- [Knowledge Graph Module](kg.md) - The data source
-- [Embeddings Module](embeddings.md) - Source for vector visualizations
-- [Ontology Module](ontology.md) - Source for hierarchy visualizations
-
-## Cookbook
-
-Interactive tutorials to learn graph visualization:
-
-- **[Visualization](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/16_Visualization.ipynb)**: Basic graph visualization techniques
- - **Topics**: Graph visualization, network diagrams, basic plotting
- - **Difficulty**: Beginner
- - **Use Cases**: Visualizing knowledge graphs, understanding graph structure
-- **[Complete Visualization Suite](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)**: Creating interactive, publication-ready visualizations
- - **Topics**: PyVis, NetworkX, D3.js, interactive visualizations, publication-ready graphics
- - **Difficulty**: Intermediate
- - **Use Cases**: Advanced visualizations, presentations, publications
+<CardGroup cols={2}>
+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">
+ The graph being visualized.
+ </Card>
+ <Card title="Ontology" icon="sitemap" href="ontology">
+ Visualize ontology structure.
+ </Card>
+ <Card title="Embeddings" icon="vector-square" href="embeddings">
+ Visualize embedding space.
+ </Card>
+ <Card title="Explorer" icon="globe" href="evals">
+ Full Knowledge Explorer UI.
+ </Card>
+</CardGroup>
diff --git a/docs/use-cases.md b/docs/use-cases.md
index 2d9c4ba2..35df306c 100644
--- a/docs/use-cases.md
+++ b/docs/use-cases.md
@@ -1,7 +1,7 @@
-# Use Cases
-
-Real-world applications of Semantica across domains, with linked cookbook notebooks for each.
-
+---
+title: "Use Cases"
+description: "Real-world applications of Semantica across domains, with linked cookbook notebooks for each."
+icon: "briefcase"
---
## Overview
@@ -19,7 +19,7 @@ Real-world applications of Semantica across domains, with linked cookbook notebo
| Renewable Energy Management | Energy | Intermediate | 1–2 hours |
| GraphRAG | AI | Advanced | 1–2 hours |
-**Difficulty levels**:
+**Difficulty levels:**
- **Beginner** β€” basic Semantica knowledge only
- **Intermediate** β€” some domain knowledge helpful
@@ -33,7 +33,7 @@ Real-world applications of Semantica across domains, with linked cookbook notebo
Connect genes, proteins, drugs, and diseases from scientific literature and databases to accelerate drug discovery and understand disease pathways.
-**Cookbooks**:
+**Cookbooks:**
- [Drug Discovery Pipeline](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb) β€” PubMed RSS ingestion, entity-aware chunking, GraphRAG, vector similarity search
- [Genomic Variant Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb) β€” bioRxiv RSS, temporal KGs, deduplication, pathway analysis
@@ -45,19 +45,19 @@ Connect genes, proteins, drugs, and diseases from scientific literature and data
Unify financial data from APIs, MCP servers, and real-time streams into a single queryable knowledge graph.
-**Cookbook**: [Financial Data Integration (MCP)](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb) β€” Alpha Vantage API, MCP servers, seed data, real-time ingestion
+**Cookbook:** [Financial Data Integration (MCP)](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb) β€” Alpha Vantage API, MCP servers, seed data, real-time ingestion
### Fraud Detection
Detect complex fraud rings using temporal graphs and pattern detection over transaction, device, and user data.
-**Cookbook**: [Fraud Detection](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb) β€” temporal KGs, cycle detection, fraud pattern analysis
+**Cookbook:** [Fraud Detection](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb) β€” temporal KGs, cycle detection, fraud pattern analysis
### Blockchain Analytics
Map transaction flows, analyze DeFi protocols, and detect illicit activity across wallet and exchange networks.
-**Cookbooks**:
+**Cookbooks:**
- [DeFi Protocol Intelligence](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb)
- [Transaction Network Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb)
@@ -69,7 +69,7 @@ Map transaction flows, analyze DeFi protocols, and detect illicit activity acros
Ingest threat feeds (CVE databases, security RSS), detect anomalies in streaming data, and build threat intelligence knowledge graphs for proactive defense.
-**Cookbooks**:
+**Cookbooks:**
- [Real-Time Anomaly Detection](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
- [Threat Intelligence Hybrid RAG](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)
@@ -77,13 +77,13 @@ Ingest threat feeds (CVE databases, security RSS), detect anomalies in streaming
Build knowledge graphs from police reports, court records, and OSINT feeds to identify key players, communities, and suspicious patterns using network centrality analysis.
-**Cookbook**: [Criminal Network Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
+**Cookbook:** [Criminal Network Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
### Intelligence Analysis Orchestrator
Process multiple intelligence sources in parallel using an orchestrator-worker pipeline pattern with multi-source conflict detection and integration.
-**Cookbook**: [Intelligence Analysis Orchestrator-Worker](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
+**Cookbook:** [Intelligence Analysis Orchestrator-Worker](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
---
@@ -93,13 +93,13 @@ Process multiple intelligence sources in parallel using an orchestrator-worker p
Map suppliers, logistics routes, and inventory levels to identify bottlenecks and optimize global supply chains.
-**Cookbook**: [Supply Chain Data Integration](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb)
+**Cookbook:** [Supply Chain Data Integration](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb)
### Renewable Energy Management
Connect sensor data, weather forecasts, and maintenance logs to predict equipment failures and optimize grid operations.
-**Cookbook**: [Energy Market Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)
+**Cookbook:** [Energy Market Analysis](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)
---
@@ -109,7 +109,7 @@ Connect sensor data, weather forecasts, and maintenance logs to predict equipmen
Use knowledge graphs to retrieve precise, structured context for LLM responses β€” with hybrid retrieval, logical inference, and source attribution.
-**Cookbooks**:
+**Cookbooks:**
- [GraphRAG Complete](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) β€” production-ready implementation
- [RAG vs. GraphRAG Comparison](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) β€” side-by-side comparison
@@ -117,9 +117,18 @@ Use knowledge graphs to retrieve precise, structured context for LLM responses
## Next Steps
-- [Cookbook](cookbook.md) β€” full notebook catalog organized by topic and difficulty
-- [Modules Guide](modules.md) β€” every module with examples
-- [API Reference](reference/core.md) β€” complete technical documentation
-
-!!! info "Have a use case to add?"
- [Open a PR](https://github.com/Hawksight-AI/semantica) or start a discussion on GitHub.
+<CardGroup cols={3}>
+ <Card title="Cookbook" icon="flask" href="cookbook">
+ Full notebook catalog organized by topic and difficulty.
+ </Card>
+ <Card title="Modules Guide" icon="puzzle-piece" href="modules">
+ Every module with examples.
+ </Card>
+ <Card title="API Reference" icon="code" href="reference/context">
+ Complete technical documentation.
+ </Card>
+</CardGroup>
+
+<Info>
+ Have a use case to add? [Open a PR](https://github.com/Hawksight-AI/semantica) or start a discussion on GitHub.
+</Info>
diff --git a/docs/vector_store_usage.md b/docs/vector_store_usage.md
index c11a75f9..bd2124fe 100644
--- a/docs/vector_store_usage.md
+++ b/docs/vector_store_usage.md
@@ -1,47 +1,47 @@
-# High-Performance Vector Store Usage
+---
+title: "Vector Store: High-Performance Usage"
+description: "Parallel ingestion, batch processing, and performance tuning for the Semantica Vector Store."
+icon: "bolt"
+---
-This guide demonstrates how to leverage the new high-performance features of the Semantica Vector Store, specifically designed for efficient batch processing and parallel ingestion of large document sets.
+> High-performance batch ingestion with parallel embedding generation β€” 3–10Γ— faster than sequential processing.
-## πŸš€ Key Features
+---
-- **Parallel Ingestion**: Utilize multi-threading to embed and store documents concurrently.
-- **Batch Processing**: Automatically group documents into batches to minimize overhead.
-- **Unified API**: A single `add_documents` method handles embedding generation and storage.
+## Key Features
----
+- **Parallel ingestion** β€” multi-threaded embedding generation and storage
+- **Batch processing** β€” minimizes overhead by grouping documents into chunks
+- **Unified API** β€” `add_documents` handles embedding generation and storage in one call
-## ⚑ Quick Start: Parallel Ingestion
+---
-The fastest way to ingest documents is using the `add_documents` method. Parallelization is enabled by default with optimized settings (6 workers).
+## Quick Start: Parallel Ingestion
```python
from semantica.vector_store import VectorStore
import time
-store = VectorStore(
- backend="faiss",
- dimension=768,
-)
+store = VectorStore(backend="faiss", dimension=768)
documents = [f"This is document number {i} with some content." for i in range(1000)]
-metadata = [{"source": "generated", "id": i} for i in range(1000)]
+metadata = [{"source": "generated", "id": i} for i in range(1000)]
-start_time = time.time()
-ids = store.add_documents(
+start = time.time()
+ids = store.add_documents(
documents=documents,
metadata=metadata,
batch_size=64,
- parallel=True,
+ parallel=True, # default: True
)
-print(f"Ingested {len(ids)} documents in {time.time() - start_time:.2f}s")
+print(f"Ingested {len(ids)} documents in {time.time() - start:.2f}s")
```
---
-## πŸ“Š Performance Comparison
+## Performance Comparison
-### Old Method (Sequential Loop)
-*Slower due to sequential processing and overhead per single item.*
+**Old method (sequential loop)** β€” slower due to per-item overhead:
```python
for doc in documents:
@@ -49,8 +49,7 @@ for doc in documents:
store.store_vectors([emb], [{"text": doc}])
```
-### New Method (Parallel Batching)
-*Significantly faster (3x-10x) by utilizing thread pools and batch operations.*
+**New method (parallel batching)** β€” 3–10Γ— faster:
```python
store.add_documents(documents, parallel=True)
@@ -58,23 +57,26 @@ store.add_documents(documents, parallel=True)
---
-## πŸ›  Configuration & Tuning
+## Configuration and Tuning
### `max_workers`
-Controls the number of concurrent threads used for embedding generation.
-- **Default**: 6 (Optimized for most systems)
-- **Recommendation**: You generally don't need to change this. If you have very high core counts or specific throughput needs, you can override it.
+
+Number of concurrent threads for embedding generation.
+
+- **Default**: 6 (optimized for most systems)
+- Override only if you have very high core counts or specific throughput needs
```python
store = VectorStore(max_workers=16)
```
### `batch_size`
-Controls how many documents are processed in a single chunk.
+
+Number of documents processed in a single chunk.
+
- **Default**: 32
-- **Recommendation**:
- - **Local Models**: 32-64 usually works well.
- - **API Models (OpenAI, etc.)**: Larger batches (e.g., 100-200) can reduce network latency overhead.
+- **Local models**: 32–64 works well
+- **API models (OpenAI, etc.)**: 100–200 reduces network latency overhead
```python
store.add_documents(documents, batch_size=100)
@@ -82,20 +84,34 @@ store.add_documents(documents, batch_size=100)
---
-## 🧩 Advanced: Manual Batch Embedding
+## Manual Batch Embedding
-If you need the embeddings without storing them immediately, use `embed_batch`.
+If you need embeddings without immediately storing them:
```python
-vectors = store.embed_batch(
- texts=documents[:100],
-)
-
+vectors = store.embed_batch(texts=documents[:100])
print(f"Generated {len(vectors)} vectors")
```
-## ⚠️ Best Practices
+---
+
+## Best Practices
+
+<Tip>
+- **Metadata consistency** β€” ensure your `metadata` list is the same length as `documents`.
+- **Error handling** β€” `add_documents` propagates exceptions if embedding fails; validate your data first.
+- **Memory usage** β€” very large `batch_size` combined with high `max_workers` increases RAM usage. Monitor system resources for large corpora.
+</Tip>
+
+---
+
+## See Also
-1. **Metadata Consistency**: Ensure your `metadata` list has the same length as your `documents` list.
-2. **Error Handling**: The `add_documents` method will propagate exceptions if embedding fails. Ensure your data is clean.
-3. **Memory Usage**: Very large `batch_size` combined with high `max_workers` can increase memory usage. Monitor your system resources.
+<CardGroup cols={2}>
+ <Card title="Vector Store Reference" icon="vector-square" href="reference/vector_store">
+ Full VectorStore API with all backends.
+ </Card>
+ <Card title="Embeddings" icon="brain" href="reference/embeddings">
+ Embedding providers and GPU acceleration.
+ </Card>
+</CardGroup>
diff --git a/docs/vector_stores/pgvector.md b/docs/vector_stores/pgvector.md
index a5480644..22ea25c0 100644
--- a/docs/vector_stores/pgvector.md
+++ b/docs/vector_stores/pgvector.md
@@ -1,4 +1,8 @@
-# PgVector Store
+---
+title: "pgvector Store"
+description: "PostgreSQL with pgvector extension β€” cosine, L2, and inner product similarity search with IVFFlat and HNSW indexing."
+icon: "database"
+---
PostgreSQL with pgvector extension support for Semantica vector storage and similarity search.
@@ -372,4 +376,4 @@ TEST_PGVECTOR_URL="postgresql://postgres:postgres@localhost:5432/test" \
- [pgvector Documentation](https://github.com/pgvector/pgvector)
- [PgVector Python Client](https://github.com/pgvector/pgvector-python)
- [psycopg Documentation](https://www.psycopg.org/)
-- [Vector Store Usage Guide](../vector_store_usage.md)
+- [Vector Store Usage Guide](../vector_store_usage)