Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
docs: premium overhaul of all reference pages and core docs
KaifAhmad19113ef342809
diff --git a/docs/architecture.md b/docs/architecture.mdindex 48c5c711..d2ab458d 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -1,12 +1,10 @@---title: "Architecture"-description: "Three-layer, modular architecture designed for independent component use, clean separation of concerns, and extensibility."+description: "Three-layer, modular architecture designed for independent component use, clean separation of concerns, and full extensibility."icon: "building"----Semantica is built around a three-layer modular architecture. Import only what you need — nothing forces a full stack.-----+Semantica is built around a three-layer modular architecture. Import only what you need — the framework never forces a full stack. Every component is independently swappable, and every layer communicates through clean interfaces with no hidden coupling.## Three-Layer Architecture@@ -27,33 +25,35 @@ Semantica is built around a three-layer modular architecture. Import only what y<Tab title="Layer 1 — Ingestion">-Loads data from any source into the pipeline.+Loads data from any source into the pipeline as a unified `SourceDocument`.| Source | Module | Notes |-|--------|--------|-------|-| PDF, DOCX, PPTX, HTML, JSON, CSV | `ingest.FileIngestor` | Supports archives, recursive scan |+| ------ | ------ | ----- |+| PDF, DOCX, PPTX, HTML, JSON, CSV | `ingest.FileIngestor` | Supports archives, recursive directory 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 |+| Email | `ingest.EmailIngestor` | IMAP/SMTP with attachment extraction |+| Repositories | `ingest.RepoIngestor` | Git repos, code structure || MCP | `ingest.MCPIngestor` | Model Context Protocol sources |</Tab><Tab title="Layer 2 — Semantic Processing">-The core intelligence engine — transforms raw data into structured knowledge.+The core intelligence engine — transforms raw text into structured, queryable knowledge.| 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 |+| Extract | `semantic_extract` | NER, relation extraction, event detection, 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) |+| Temporal | `kg.TemporalKnowledgeGraph` | `valid_from` / `valid_until`, Allen interval algebra (v0.4.0) |</Tab>@@ -62,52 +62,51 @@ The core intelligence engine — transforms raw data into structured knowledge.Consumes the knowledge graph for downstream use cases.| 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 |+| Export | `export` | RDF, Parquet, ArangoDB AQL, OWL, CSV, Arrow || Reasoning | `reasoning` | Forward chaining, Rete, Datalog, SPARQL, abductive |</Tab></Tabs>-----## Data Flow+Every pipeline follows the same linear path from raw source to delivered output:+```text-Ingest → raw data from sources-Parse → structured text extraction-Normalize → canonical forms, date/name standardization-Extract → entities, relationships, events-Build → entity resolution, graph construction+Ingest → raw data from files, web, databases, streams+Parse → structured text and layout extraction+Normalize → canonical forms, date and name standardization+Extract → entities, relationships, events, triplets+Build → entity resolution and graph constructionQA → deduplication, conflict resolution, validationStore → vector store, graph store, triplet storeDeliver → GraphRAG, agents, export, visualization```-----## Module Map| 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` |-----+| Output | `export`, `visualization`, `pipeline`, `explorer` |+| Utilities | `llms`, `mcp_server`, `seed`, `evals`, `core`, `utils` |## Extension Points+Every layer exposes a registry-based extension point. Register custom implementations and they participate in the full pipeline with zero changes to core code.+<CodeGroup>```python Custom Ingestor@@ -120,7 +119,6 @@ def custom_file_ingestor(source):# Register under the "file" task category with a unique namemethod_registry.register("file", "my_custom_format", custom_file_ingestor)-# Verify registrationavailable = method_registry.list_all("file")```@@ -140,7 +138,7 @@ from semantica.core import PluginRegistryclass MyPlugin:def process(self, graph, config):- # Modify the graph in place+ # Modify the graph in place and return itreturn graphregistry = PluginRegistry()@@ -149,52 +147,53 @@ registry.register_plugin("my_plugin", MyPlugin, version="1.0.0")</CodeGroup>-----## Design Decisions<AccordionGroup><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.++Every component works standalone. `NERExtractor` runs without a graph store. `VectorStore` runs without decision tracking. The framework never forces a full stack instantiation — you pay only for what you import.+</Accordion><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.++Custom ingestors, extractors, validators, and exporters follow the same base class pattern. Register them via `PluginRegistry` and they participate in the full pipeline — provenance tracking, retry policies, and parallel execution included — with no changes to core code.+</Accordion><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.++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's no opt-in required — provenance is always on.+</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.++Centralized `ConfigManager` with environment variable overrides. No magic defaults — all behavior is explicit and overridable. Suitable for multi-environment deployments where dev, staging, and production need different backends.+</Accordion></AccordionGroup>-----## Performance Characteristics| 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 |+| **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+| **Indexed search** | Explorer search at 0.004ms on 118k nodes (v0.5.0) |<CardGroup cols={2}><Card title="Modules" icon="cubes" href="modules">Full module documentation with code examples.</Card>- <Card title="Learning More" icon="microscope" href="learning-more">- Internals, algorithms, and advanced extension patterns.+ <Card title="Learning More" icon="graduation-cap" href="learning-more">+ Configuration reference, performance guide, and troubleshooting.</Card><Card title="Pipeline Reference" icon="gear" href="reference/pipeline">Pipeline orchestration, workers, and retry policies.diff --git a/docs/assets/img/semantica-logo.png b/docs/assets/img/semantica-logo.pngnew file mode 100644index 00000000..a89e5b67Binary files /dev/null and b/docs/assets/img/semantica-logo.png differdiff --git a/docs/community-projects.md b/docs/community-projects.mdindex c09e46f6..afd99467 100644--- a/docs/community-projects.md+++ b/docs/community-projects.md@@ -1,64 +1,118 @@---title: "Community Projects"-description: "Projects and integrations built by the Semantica community."+description: "Projects, extensions, and integrations built by the Semantica community."icon: "people-group"----> Projects and integrations from the Semantica community.-<Tip>-Have a project using Semantica? [Submit it on GitHub](https://github.com/semantica-agi/semantica/issues/new) — we'd love to feature it here.+ Building something with Semantica? [Submit it on GitHub](https://github.com/semantica-agi/semantica/issues/new?template=community_project.md) — we'd love to feature it here.</Tip>----+Semantica is used across academia, enterprise, and independent research. Below is a snapshot of the ecosystem being built by the community.## Projects Using Semantica-### Research and Academia+### Research & Academia-- Academic literature analysis and citation graph construction-- Biomedical analysis and drug discovery knowledge graphs-- Social network analysis and community detection+Teams in academia are using Semantica to build structured, auditable knowledge from unstructured scientific literature.-### Enterprise and Industry+- **Academic literature mapping** — citation graph construction across multi-year corpora with temporal provenance+- **Biomedical knowledge graphs** — connecting genes, proteins, drugs, and diseases from PubMed and preprint feeds+- **Social network analysis** — community detection and influence analysis over entity-linked interaction graphs+- **Computational linguistics** — coreference resolution pipelines with entity-linked output for downstream NLP tasks-- Business intelligence and corporate knowledge bases-- Cybersecurity and threat intelligence-- Healthcare and medical record processing-- Finance, trading, and fraud detection+### Enterprise & Industry----+Production deployments span regulated and high-stakes industries where AI accountability is not optional.-## Integrations+- **Business intelligence** — corporate knowledge bases built from filings, reports, and internal documentation+- **Cybersecurity & threat intelligence** — adversary attribution graphs, CVE-linked threat feeds, incident timelines+- **Healthcare & clinical AI** — patient safety graphs, drug interaction knowledge bases, HIPAA-compliant audit trails+- **Financial services** — fraud detection graphs, regulatory compliance pipelines (SOX/GDPR/MiFID II), risk lineage+- **Legal & compliance** — contract analysis pipelines, regulatory change tracking, evidence-backed research graphs+- **Critical infrastructure** — supply chain risk graphs, energy grid event graphs, logistics provenance-**Vector Databases** — Weaviate, Qdrant, FAISS, Milvus, Pinecone, pgvector+### Independent & Open Source-**Graph Databases** — Neo4j, FalkorDB, Apache AGE+- **GraphRAG toolkits** — custom retrieval layers built on top of Semantica's `context` + `vector_store` modules+- **Domain-specific extractors** — NER and relation extractors for clinical, legal, and scientific text+- **Temporal graph dashboards** — visual timelines built with Semantica's `TemporalKnowledgeGraph` + custom visualization adapters-**LLM Providers** — OpenAI, Anthropic, Groq, Google Gemini, Ollama, HuggingFace, DeepSeek, Novita AI+## Supported Integrations-**NLP Libraries** — spaCy, NLTK, Sentence Transformers+### Vector Databases----+- FAISS — in-process, CPU/GPU+- Pinecone — managed vector cloud+- Weaviate — schema-first hybrid search+- Qdrant — high-performance Rust-native+- Milvus — enterprise-scale distributed+- PgVector — Postgres-native for SQL stacks++### Graph Databases++- Neo4j — industry standard, Cypher query+- FalkorDB — Redis-protocol, low-latency+- Apache AGE — PostgreSQL extension, OpenCypher+- Amazon Neptune — managed AWS, SPARQL + Gremlin++### LLM Providers++- OpenAI (GPT-4o, GPT-4, GPT-3.5)+- Anthropic (Claude Opus, Sonnet, Haiku)+- Google Gemini+- Groq (LLaMA, Mixtral — fast inference)+- Ollama (fully local, air-gapped)+- HuggingFace+- DeepSeek+- Novita AI+- LiteLLM (100+ model gateway)++### NLP Libraries++- spaCy — production NER and dependency parsing+- NLTK — tokenization and feature extraction+- Sentence Transformers — semantic embeddings+- FastEmbed — lightweight, fast inference## Community Extensions-- Custom entity extractors for domain-specific use cases-- Specialized export formats for various industries-- Integration adapters for popular data sources-- Enhanced visualization tools and dashboards+The plugin system (`PluginRegistry`) makes it easy to add new capabilities without touching core code. The community has built:----+- **Custom entity extractors** — domain-specific NER for clinical entities, legal clause types, and financial instruments+- **Export adapters** — specialized serialization formats for proprietary industry systems+- **Ingestor plugins** — adapters for SharePoint, Notion, Confluence, and custom databases+- **Visualization plugins** — enhanced dashboards with Plotly, D3.js, and custom graph renderers+- **Evaluation harnesses** — domain-specific precision/recall benchmarks using `semantica.evals`-## How to Contribute+## Build Your Own Extension++Any Semantica component can be extended via the registry pattern:++```python+from semantica.ingest.registry import method_registry++def my_ingestor(source):+ return [{"text": "...", "metadata": {}, "source": source}]-See the [Contributing Guide](contributing) for full details.+method_registry.register("file", "my_format", my_ingestor)+```++See [Architecture](architecture#extension-points) for the full extension guide.++## How to Contribute<CardGroup cols={2}>- <Card title="Contributing" icon="code-pull-request" href="contributing-guide">- Submit code, docs, or tests.+ <Card title="Contributing Guide" icon="code-pull-request" href="contributing-guide">+ Submit code, documentation, tests, or cookbook notebooks.</Card><Card title="GitHub Issues" icon="circle-dot" href="https://github.com/semantica-agi/semantica/issues">- Report bugs or request features.+ Report bugs, request features, or propose integrations.+ </Card>+ <Card title="Discord" icon="discord" href="https://discord.gg/sV34vps5hH">+ Share what you're building with the community.+ </Card>+ <Card title="GitHub Discussions" icon="comments" href="https://github.com/semantica-agi/semantica/discussions">+ Long-form questions, design discussions, and ideas.</Card></CardGroup>diff --git a/docs/community.md b/docs/community.mdindex 17614a34..e49caa48 100644--- a/docs/community.md+++ b/docs/community.md@@ -4,73 +4,86 @@ description: "Get help, connect with contributors, and share what you build withicon: "users"----> Connect with the Semantica community for support, collaboration, and learning.-----+Semantica is built in the open, with contributions from researchers, engineers, and practitioners across many domains. Whether you're filing a bug, sharing a project, or reviewing a PR — you're part of the ecosystem.## Get Help<CardGroup cols={2}><Card title="GitHub Issues" icon="circle-dot" href="https://github.com/semantica-agi/semantica/issues">- Bug reports and feature requests.+ File bug reports and feature requests with full context.</Card><Card title="GitHub Discussions" icon="comments" href="https://github.com/semantica-agi/semantica/discussions">- Questions, ideas, and community conversation.+ Ask questions, share ideas, and discuss design decisions.</Card><Card title="Pull Requests" icon="code-pull-request" href="https://github.com/semantica-agi/semantica/pulls">- Code contributions and reviews.+ Browse open contributions and submit your own.</Card><Card title="Security Issues" icon="shield" href="https://github.com/semantica-agi/semantica/security/advisories/new">- Report vulnerabilities privately.+ Report vulnerabilities privately — never in public issues.</Card></CardGroup>-----## Community Guidelines-We follow the [Contributor Covenant Code of Conduct](https://github.com/semantica-agi/semantica/blob/main/CODE_OF_CONDUCT.md). Our community values:+We follow the [Contributor Covenant Code of Conduct](https://github.com/semantica-agi/semantica/blob/main/CODE_OF_CONDUCT.md). The community is built on four principles:-- **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+- **Respect** — treat everyone with kindness and patience, regardless of experience level+- **Inclusion** — welcome all backgrounds, domains, and approaches+- **Collaboration** — work toward better solutions together rather than competing on approaches+- **Learning** — share knowledge openly, ask questions without hesitation, and help others grow-If you experience unacceptable behavior, open an issue with a `[CoC]` prefix. We investigate every report.-----+To report unacceptable behavior, open a GitHub issue with the `[CoC]` prefix. Every report is investigated.## Ways to Contribute-- **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+There's no single right way to contribute. Pick the path that fits your skills and time:-See the [Contributing Guide](contributing) for full details.+### Code----+- Fix open bugs tagged [`good-first-issue`](https://github.com/semantica-agi/semantica/labels/good-first-issue)+- Add new features or integrations+- Improve performance or refactor existing modules-## Stay Connected+### Documentation-- **[GitHub](https://github.com/semantica-agi/semantica)** — Source code, releases, roadmap-- **[PyPI](https://pypi.org/project/semantica/)** — Package downloads+- Fix typos and improve clarity in guides+- Add examples to the API reference+- Write domain-specific cookbook notebooks----+### Testing++- Add coverage for untested modules+- Reproduce and confirm reported bugs+- Improve test reliability across platforms++### Community++- Answer questions in issues and discussions+- Review open pull requests+- Share your Semantica projects in GitHub Discussions++See the [Contributing Guide](contributing-guide) for the full development workflow.++## Stay Connected++- **[GitHub](https://github.com/semantica-agi/semantica)** — source code, releases, and the public roadmap+- **[PyPI](https://pypi.org/project/semantica/)** — package releases and download stats+- **[Discord](https://discord.gg/sV34vps5hH)** — real-time community chat+- **[X / Twitter](https://x.com/BuildSemantica)** — announcements and release highlights## See Also<CardGroup cols={2}>- <Card title="Contributing" icon="code-pull-request" href="contributing-guide">- Step-by-step guide for submitting PRs.+ <Card title="Contributing Guide" icon="code-pull-request" href="contributing-guide">+ Step-by-step guide for submitting PRs and setting up your dev environment.+ </Card>+ <Card title="Community Projects" icon="people-group" href="community-projects">+ Projects and integrations built by the community.</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.+ How the project is run and decisions are made.</Card></CardGroup>diff --git a/docs/concepts.md b/docs/concepts.mdindex 58dc0ec6..88eaa595 100644--- a/docs/concepts.md+++ b/docs/concepts.md@@ -5,24 +5,16 @@ icon: "book-open"---<Tip>- New here? Start with [Getting Started](getting-started) for hands-on examples, then come back here for deeper understanding.+ New here? Start with [Getting Started](getting-started) for hands-on examples, then return here for deeper understanding.</Tip>------## What is Semantica?--Semantica transforms unstructured data (documents, web pages, reports, databases) into **knowledge graphs** — structured representations that AI systems can query, reason about, and trace back to sources.--At its core, Semantica adds a **context and intelligence layer** on top of your existing AI stack: it doesn't replace LangChain, LlamaIndex, or your LLM provider — it makes their outputs accountable.+Semantica transforms unstructured data — documents, web pages, reports, databases — into **knowledge graphs**: structured representations that AI systems can query, reason about, and trace back to sources.----+At its core, Semantica adds a **context and intelligence layer** on top of your existing AI stack. It doesn't replace LangChain, LlamaIndex, or your LLM provider — it makes their outputs accountable.## Knowledge Graphs-The foundation of everything in Semantica.--A knowledge graph stores information as:+The foundation of everything in Semantica. A knowledge graph stores information as three building blocks:- **Nodes (entities)** — people, companies, locations, events, concepts- **Edges (relationships)** — `works_for`, `located_in`, `founded_by`@@ -30,8 +22,6 @@ A knowledge graph stores information as:This structure makes knowledge **searchable**, **connectable**, **queryable**, and — critically — **explainable**: every answer can be traced back to the facts and relationships that produced it.-----## Entity Extraction (NER)Scanning text to find and classify real-world entities.@@ -48,9 +38,11 @@ Scanning text to find and classify real-world entities.}```-Each entity gets a type, confidence score, and a link to its source document.+Each entity gets a type, confidence score, and a link to its source document. Three extraction methods are available:----+- **`"pattern"`** — fast, regex-based, no API key required+- **`"ml"`** — local ML model, higher accuracy+- **`"llm"`** — LLM-powered, highest accuracy, supports all 8 providers## Relationship Extraction@@ -65,13 +57,11 @@ Finding how entities connect to each other.}```-Relationships can be extracted via rule-based methods, ML models, or LLMs (with `"llm_typed"` metadata).-----+Relationships can be extracted via rule-based methods, ML models, or LLMs — each producing typed triplets with confidence scores and source attribution.## Embeddings-Embeddings convert text into numerical vectors so that AI systems can measure semantic similarity — finding related concepts even when the exact words differ.+Embeddings convert text into numerical vectors so AI systems can measure semantic similarity — finding related concepts even when the exact words differ.Semantica uses embeddings for:@@ -80,23 +70,21 @@ Semantica uses embeddings for:- **Precedent search** — find similar past decisions- **GraphRAG retrieval** — hybrid vector + graph traversal----+**Supported models:** Sentence-Transformers, FastEmbed, OpenAI, BGE## GraphRAGGraphRAG (Graph-Augmented Retrieval Augmented Generation) enhances LLM responses by grounding them in a structured knowledge graph rather than raw text chunks alone.-How it works:+**How it works:**1. User submits a query-2. Semantica retrieves relevant graph context (entities, relationships, reasoning paths)+2. Semantica retrieves relevant graph context — entities, relationships, reasoning paths3. The LLM generates a response grounded in that context4. Every claim in the response links back to a source node in the graphThis eliminates the hallucination and traceability problems of standard RAG.-----## OntologyAn ontology defines the schema and rules for your knowledge — what entity types exist, which relationships are valid, and what constraints apply.@@ -112,24 +100,20 @@ ontology = {}```-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.-----+Semantica can auto-generate ontologies from your knowledge graph or import existing OWL/RDF/Turtle ontologies. The **Ontology Hub** (v0.5.0) adds a visual editor, SHACL Studio, alignment authoring, and a live health dashboard.## Reasoning & InferenceSemantica includes multiple reasoning engines to derive new knowledge from existing facts.-```+```textKnown: Steve Jobs founded Apple Inc.Known: Apple Inc. is headquartered in CupertinoInferred: Steve Jobs has a connection to Cupertino```-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 |@@ -139,9 +123,7 @@ Supported engines:All engines produce **explainable inference paths**, not black-box conclusions.------## Temporal Intelligence (v0.4.0)+## Temporal IntelligenceKnowledge changes over time. Temporal graphs attach `valid_from` / `valid_until` windows to nodes and edges, enabling point-in-time queries and historical analysis.@@ -156,35 +138,34 @@ tkg.add_node("ceo_role", valid_from=datetime(2020, 1, 1), valid_until=datetime(2snapshot = 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.+**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)+## Distance Intelligence-Explore the semantic neighborhood of any entity in your graph.+Explore the semantic neighborhood of any entity in your graph. Useful for understanding what's conceptually close, detecting clusters, and visualizing knowledge topology.```pythonfrom semantica.kg import DistanceCalculator-calc = DistanceCalculator(graph)+calc = DistanceCalculator(graph)neighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)-matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])+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.-----+**Features:** N×N distance matrices, ego-mode visualization, distance band classification (`near` / `mid` / `far`), embedding cache optimization.## Deduplication & Entity ResolutionReal-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.-Strategies: Jaro-Winkler similarity (v1), `blocking_v2`, `hybrid_v2`, `semantic_v2` (v2 — up to 7x faster).+**Strategies:**----+- **v1** — Jaro-Winkler similarity, suitable for small datasets+- **`blocking_v2`** — candidate blocking for large corpora+- **`hybrid_v2`** — combines blocking with semantic matching+- **`semantic_v2`** — pure embedding-based resolution, up to 7x faster than v1## Provenance & Auditability@@ -197,8 +178,6 @@ Every fact in Semantica links back to:This is W3C PROV-O compliant lineage — suitable for regulated industries that require audit trails (HIPAA, SOX, GDPR, FDA 21 CFR Part 11).-----## Decision IntelligenceEvery agent decision is a first-class object in Semantica — recorded, causally linked, and searchable by precedent.@@ -216,24 +195,25 @@ precedents = context.find_precedents("model selection reasoning", limit=5)influence = context.analyze_decision_influence(decision_id)```----+This prevents inconsistent decisions, enables audits, and lets agents learn from their own history.## Conflict DetectionWhen multiple sources disagree on the same fact, Semantica flags and resolves the conflict rather than silently picking one value.-Resolution strategies: prefer most recent, prefer most reliable source, majority vote, or flag for manual review.-----+**Resolution strategies:**-## Next Steps+- Prefer the most recent source+- Prefer the most reliable source+- Majority vote across sources+- Flag for manual review<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.+ Every module explained with examples.</Card><Card title="Use Cases" icon="briefcase" href="use-cases">Real-world domain examples.diff --git a/docs/contributing-guide.md b/docs/contributing-guide.mdindex 1602c6b1..d7421d7a 100644--- a/docs/contributing-guide.md+++ b/docs/contributing-guide.md@@ -4,9 +4,7 @@ description: "How to contribute code, documentation, tests, and community supporicon: "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. Every contribution is recognized in release notes and the GitHub contributors list.## Quick Start@@ -18,57 +16,34 @@ pip install -e ".[dev]"pytest```-New to the project? Look for [`good-first-issue`](https://github.com/semantica-agi/semantica/labels/good-first-issue) labels.-----+New to the project? Start with [`good-first-issue`](https://github.com/semantica-agi/semantica/labels/good-first-issue) labeled tickets — they're scoped to be completable in a few hours without deep codebase knowledge.## Ways to Contribute-**Code**+### Code+- Fix bugs and resolve open issues- Implement new features or integrations-- Optimize performance or refactor existing code--**Documentation**-- Fix typos, improve clarity, add examples-- Write tutorials or domain-specific cookbook notebooks-- Keep the API reference up to date--**Testing**-- 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 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** — include: your use case, what you'd like Semantica to do, and how it benefits others.-------## Pull Request Checklist--Before submitting:+- Optimize performance or refactor existing modules+- Add new ingestors, parsers, or exporters using the plugin registry-- [ ] Tests pass locally (`pytest`)+### Documentation-- [ ] New features have documentation with examples+- Fix typos, improve clarity, and add missing examples+- Write tutorials or domain-specific cookbook notebooks+- Keep the API reference accurate as modules evolve-- [ ] Code follows project style (Black, isort, flake8)+### Testing-- [ ] Commit messages are clear and descriptive+- Add test coverage for untested modules or edge cases+- Reproduce and confirm reported bugs with a minimal repro+- Improve test reliability across Python versions and platforms-- [ ] No unresolved merge conflicts+### Community----+- Answer questions in GitHub Issues and Discussions+- Review open pull requests with constructive feedback+- Share Semantica in blog posts, talks, or conference demos## Development Setup@@ -78,22 +53,44 @@ cd semanticapip install -e ".[dev]"```-Code style: **Black** (formatting), **isort** (imports), **flake8** (linting).+**Code style tools:**```bash-pytest # full test suite-black semantica/ tests/ # format-isort semantica/ tests/ # sort imports-flake8 semantica/ # lint+pytest # full test suite+black semantica/ tests/ # auto-format+isort semantica/ tests/ # sort imports+flake8 semantica/ # lint```----+Style conventions: **Black** for formatting, **isort** for imports, **flake8** for linting. All three run in CI.-## Code of Conduct+## Reporting Issues-Please follow the [Code of Conduct](https://github.com/semantica-agi/semantica/blob/main/CODE_OF_CONDUCT.md). Be respectful, patient, and constructive. All contributors are recognized in release notes and the GitHub contributors list.+**Bug reports** should include:----+- What happened vs. what you expected+- Minimal steps to reproduce+- Your environment: Python version, OS, Semantica version (`python -c "import semantica; print(semantica.__version__)"`)++**Feature requests** should include:++- Your concrete use case+- What you'd like Semantica to do+- Why it benefits a broad set of users, not just your specific workflow++## Pull Request Checklist++Before submitting a PR, confirm:++- [ ] Tests pass locally — `pytest`+- [ ] New features include documentation with working code examples+- [ ] Code follows project style — Black, isort, flake8+- [ ] Commit messages are clear and describe the *why*, not just the *what*+- [ ] No unresolved merge conflicts++## Code of Conduct++All contributors are expected to follow the [Contributor Covenant Code of Conduct](https://github.com/semantica-agi/semantica/blob/main/CODE_OF_CONDUCT.md). Be respectful, patient, and constructive — especially toward newcomers. Report violations by opening an issue with the `[CoC]` prefix.## Help@@ -101,15 +98,11 @@ Please follow the [Code of Conduct](https://github.com/semantica-agi/semantica/b- [GitHub Discussions](https://github.com/semantica-agi/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.+ How decisions are made and the project is run.</Card></CardGroup>diff --git a/docs/docs.json b/docs/docs.jsonindex 2be3d248..c2ffe747 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -8,17 +8,19 @@"light": "#10B981","dark": "#047857"},- "favicon": "/assets/img/Semantica Logo.png",+ "favicon": "/assets/img/semantica-logo.png","logo": {- "light": "/assets/img/Semantica Logo.png",- "dark": "/assets/img/Semantica Logo.png"+ "light": "/assets/img/semantica-logo.png",+ "dark": "/assets/img/semantica-logo.png"},"font": {"headings": {- "family": "Lexend"+ "family": "Space Grotesk",+ "weight": 700},"body": {- "family": "Inter"+ "family": "Inter",+ "weight": 400}},"appearance": {@@ -41,7 +43,7 @@"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",+ "og:image": "/assets/img/semantica-logo.png","twitter:card": "summary_large_image","twitter:site": "@BuildSemantica"},@@ -108,10 +110,10 @@]},{- "tab": "API Reference",+ "tab": "Modules","groups": [{- "group": "Context & Knowledge",+ "group": "Context & Intelligence","pages": ["reference/context","reference/kg",diff --git a/docs/faq.md b/docs/faq.mdindex 88af3cac..3f1fa7b6 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -4,34 +4,48 @@ description: "Common questions about Semantica — installation, features, integicon: "circle-question"----<AccordionGroup>-## General+<AccordionGroup>+<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.++It's not a replacement for LangChain or LlamaIndex. It's the **accountability layer** that goes on top — recording decisions, tracing facts to sources, and making reasoning transparent.+</Accordion><Accordion title="What can I build with Semantica?" icon="hammer">- Knowledge graphs from documents and multi-source data-- GraphRAG systems with graph-grounded retrieval+- GraphRAG systems with graph-grounded retrieval and source attribution- AI agents with structured decision history and semantic memory-- Compliance-ready pipelines with W3C PROV-O lineage+- Compliance-ready pipelines with W3C PROV-O lineage (HIPAA, SOX, GDPR, FDA 21 CFR Part 11)+- Temporal graphs that track how facts change over time+- Ontology-driven knowledge bases with SHACL validation</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.++Semantica works alongside these frameworks, not against them.+</Accordion><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.++Yes — MIT licensed, no vendor lock-in, no paywalled features. Some capabilities require third-party API keys (e.g., OpenAI embeddings, Groq inference), but Semantica itself is always free and open source.+</Accordion><Accordion title="What's the latest version?" icon="star">-**v0.5.0** — released May 2026. Highlights: Ontology Hub, Distance Intelligence, Parquet/XML ingestion, 12 security fixes, Graph Explorer redesign.+**v0.5.0** — released May 2026.++Highlights: Ontology Hub, Distance Intelligence, Parquet/XML ingestion, 12 security fixes, Graph Explorer redesign, NER gateway fix.```bashpip install --upgrade semantica@@ -41,86 +55,104 @@ pip install --upgrade semantica</AccordionGroup>----+## Installation<AccordionGroup>-## Installation-<Accordion title="How do I install Semantica?" icon="download">```bashpip install semantica```-See [Installation](installation) for virtual environment setup, optional extras (`[gpu]`, `[all]`, provider-specific), and troubleshooting.+See [Installation](installation) for virtual environment setup, optional extras (`[gpu]`, `[all]`, provider-specific), and platform-specific troubleshooting.+</Accordion><Accordion title="What Python version do I need?" icon="python">-Python **3.8 or higher**. Python 3.11+ is recommended for best performance.++Python **3.8 or higher**. Python 3.11+ is recommended for best performance and compatibility.+</Accordion><Accordion title="The [all] extra fails on Windows" icon="windows">+This was a known bug — fixed in **v0.5.0**. Upgrade:```bashpip install --upgrade semantica```++If you're on an older version, install extras individually: `pip install "semantica[core]"`, then add `[llm-openai]`, `[gpu]`, etc.+</Accordion><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 |+| Storage | 2 GB | 20 GB+ |+| GPU | Optional | CUDA for embeddings and ML models |</Accordion></AccordionGroup>----+## Data & Features<AccordionGroup>-## Data & Features-<Accordion title="What data sources does Semantica support?" icon="database">| Category | Sources |-|----------|---------|+| -------- | ------- || **Files** | PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, Parquet (v0.5.0), XML (v0.5.0), archives |-| **Web** | `WebIngestor` crawl, RSS feeds |+| **Web** | `WebIngestor` crawl, RSS feeds, sitemaps || **Databases** | PostgreSQL, MySQL, Snowflake via `DBIngestor` / `SnowflakeIngestor` |-| **Streams** | Kafka, real-time ingestion |-| **Protocols** | MCP (Model Context Protocol) |+| **NoSQL** | MongoDB via `MongoIngestor`, DuckDB via `DuckDBIngestor` |+| **Streams** | Kafka, real-time ingestion via `StreamIngestor` |+| **Protocols** | MCP (Model Context Protocol) via `MCPIngestor` |+| **Cloud** | Google Drive via `GDriveIngestor`, HuggingFace datasets |</Accordion><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`.++Yes. Semantica supports:++- **Custom NER and extraction models** — register via `method_registry`+- **Custom embedding models** — any model with a `.encode()` interface+- **Custom LLM providers** — via LiteLLM (100+ models) or direct provider integration+- **Custom pipeline processors** — register via `PluginRegistry`+</Accordion><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 GPU support:```bashpip install "semantica[gpu]"```++This includes PyTorch with CUDA, FAISS GPU, and CuPy.+</Accordion><Accordion title="How does Semantica handle large datasets?" icon="layer-group">-- **Batching** — process documents in configurable chunks-- **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+- **Batching** — process documents in configurable chunks to control memory usage+- **Parallel processing** — `Pipeline(workers=N)` runs extraction steps concurrently+- **Delta processing** — update graphs incrementally without full recompute on new data+- **Persistent backends** — swap in-memory NetworkX for Neo4j, FalkorDB, or Apache AGE for large-scale production graphs</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.+<Accordion title="What is Temporal Intelligence?" icon="clock">++`TemporalKnowledgeGraph` attaches `valid_from` / `valid_until` windows to nodes and edges, enabling point-in-time queries and historical analysis. Supports all 13 Allen interval algebra relations and OWL-Time export.```pythonfrom semantica.kg import TemporalKnowledgeGraph@@ -129,69 +161,109 @@ tkg = TemporalKnowledgeGraph()tkg.add_temporal_triple("A", "caused", "B", valid_from="2024-01", valid_until="2024-06")snapshot = tkg.query_at_time("2024-03")```++Available since v0.4.0.+</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 title="What is the Ontology Hub?" icon="sitemap">++A visual browser UI for the full ontology lifecycle — launched via `semantica.explorer`. Includes:++- **Visual editor** — create and edit classes, properties, and relationships+- **SHACL Studio** — author, validate, and export SHACL shapes+- **Alignment authoring** — map concepts across ontologies+- **Health dashboard** — coverage, consistency, and constraint violation metrics+- **Version control** — diff and history for ontology changes++Available since v0.5.0.+</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 title="What is Distance Intelligence?" icon="compass">++Semantic neighborhood exploration for any entity in the graph. Returns structured proximity data with distance band classification.++- N×N distance matrices across a set of entities+- Ego-mode visualization centered on a single node+- Distance bands: `near` / `mid` / `far` based on embedding thresholds+- Embedding cache optimization for repeated queries++Available since v0.5.0.+</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.++Fixed in **v0.5.0**. The `response_format=json_object` parameter is now conditionally omitted for incompatible gateways, with a plain `generate()` plus JSON parsing fallback applied automatically. Upgrade to fix:++```bash+pip install --upgrade semantica+```+</Accordion></AccordionGroup>----+## Technical<AccordionGroup>-## Technical-<Accordion title="What graph databases are supported?" icon="diagram-project">-Neo4j, FalkorDB, Apache AGE (PostgreSQL), Amazon Neptune, and in-memory NetworkX for development.++- **Neo4j** — industry standard, Cypher query language+- **FalkorDB** — Redis-protocol, ultra-low latency+- **Apache AGE** — PostgreSQL extension, OpenCypher+- **Amazon Neptune** — managed AWS, SPARQL and Gremlin+- **NetworkX** — in-memory, for development and small graphs+</Accordion><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.++RDF (Turtle, JSON-LD, N-Triples, XML), Apache Parquet, ArangoDB AQL, Apache Arrow, LPG, CSV, YAML, OWL ontologies, and distance matrices.+</Accordion><Accordion title="What vector stores are supported?" icon="server">-FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, and in-memory.++FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, and in-memory. All backends share the same `VectorStore` API — swap with one line change.+</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.++Groq, OpenAI, Anthropic, Google Gemini, Ollama (fully local), DeepSeek, Novita AI, LiteLLM (100+ models via a single interface), and any OpenAI-compatible gateway.+</Accordion><Accordion title="Is Semantica production-ready?" icon="shield-check">+Yes. v0.5.0 ships with:-- 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)+- 1,000+ passing tests across Python 3.8–3.12+- `PipelineValidator` and `FailureHandler` with exponential backoff and configurable retry policies+- W3C PROV-O provenance tracking across all modules+- Change management with SHA-256 checksums and full audit trails+- 12 security vulnerability fixes: eval injection, pickle deserialization, SQL injection, XXE, SSRF, ReDoS, path traversal, and more+</Accordion></AccordionGroup>----+## Troubleshooting<AccordionGroup>-## Troubleshooting-<Accordion title="ModuleNotFoundError: No module named 'semantica'" icon="xmark-circle">-Ensure you have the correct Python environment active:++Ensure the correct Python environment is active:```bashpip list | grep semanticapip install --upgrade semantica```+</Accordion><Accordion title="Installation fails with dependency errors" icon="xmark-circle">@@ -200,32 +272,48 @@ pip install --upgrade semanticapip install --upgrade pip wheelpip install semantica```++If `[all]` fails on Windows, install extras individually instead.+</Accordion><Accordion title="Memory errors during processing" icon="memory">-Reduce batch sizes, enable streaming ingestion, or switch to a persistent graph backend (Neo4j, FalkorDB).++Reduce batch sizes, enable streaming ingestion, or switch to a persistent graph 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="Slow embedding or inference" icon="gauge-high">-Install GPU support and ensure CUDA is available:++Install GPU support and confirm CUDA is available:```bashpip install "semantica[gpu]"+nvidia-smi # confirm GPU is visible```+</Accordion><Accordion title="Unicode / cp1252 crash on Windows" icon="windows">-Fixed in **v0.5.0**. Upgrade:++Fixed in **v0.5.0**. Upgrade, or set the encoding environment variable for older versions:```bashpip install --upgrade semantica+# or for older versions:+set PYTHONIOENCODING=utf-8```+</Accordion></AccordionGroup>-----## Support<CardGroup cols={3}>diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 64575b12..5b51fd73 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -5,16 +5,14 @@ icon: "rocket"---<Tip>- Already installed? Jump to [Quickstart](quickstart). Need setup help first? Start with [Installation](installation).+ Already installed? Jump straight to [Quickstart](quickstart). Need setup help first? See [Installation](installation).</Tip>-----## What You Can Build<CardGroup cols={2}><Card title="GraphRAG Systems" icon="diagram-project">- Enhanced retrieval with semantic graph reasoning — ground LLM responses in traceable, structured knowledge.+ Ground LLM responses in traceable, structured knowledge. Every claim links back to a source node.</Card><Card title="Accountable AI Agents" icon="robot">Agents with structured decision history, causal chains, and precedent search. Every choice is recorded and auditable.@@ -27,8 +25,6 @@ icon: "rocket"</Card></CardGroup>-----## Installation```bash@@ -41,17 +37,15 @@ With all optional dependencies:pip install semantica[all]```-For virtual environments and platform-specific setup, see the full [Installation](installation).+For virtual environments and platform-specific setup, see the full [Installation](installation) guide.-Verify:+**Verify:**```pythonimport semantica-print(semantica.__version__)+print(semantica.__version__) # 0.5.0```-----## Quick Start<CodeGroup>@@ -62,17 +56,16 @@ from semantica.parse import DocumentParserfrom semantica.semantic_extract import NERExtractor, RelationExtractorfrom semantica.kg import GraphBuilder-# Ingest → Parse → Extract → Build-ingestor = FileIngestor()-sources = ingestor.ingest("data/sample.pdf")+ingestor = FileIngestor()+sources = ingestor.ingest("data/sample.pdf")parser = DocumentParser()parsed = parser.parse(sources[0])-ner = NERExtractor()-entities = ner.extract(parsed)+ner = NERExtractor()+entities = ner.extract(parsed)-rel = RelationExtractor()+rel = RelationExtractor()relationships = rel.extract(parsed, entities=entities)graph = GraphBuilder(merge_entities=True).build(@@ -91,7 +84,7 @@ context = AgentContext(decision_tracking=True,)-# Store a memory with provenance+# Store a fact with provenancecontext.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%")# Record a decision with causal chain@@ -117,7 +110,6 @@ context = AgentContext(knowledge_graph=ContextGraph(advanced_analytics=True),)-# Load your knowledge graphcontext.load_graph("company_kg.json")# Multi-hop GraphRAG query@@ -134,22 +126,18 @@ for claim in result.claims:</CodeGroup>-----## Core ArchitectureSemantica uses a modular, layered architecture — import only what you need.| Layer | Modules | Purpose |-|-------|---------|---------|+| ----- | ------- | ------- || **Input** | `ingest`, `parse`, `split`, `normalize` | Load and prepare data || **Semantic** | `semantic_extract`, `kg`, `ontology`, `reasoning` | Extract meaning |-| **Storage** | `embeddings`, `vector_store`, `graph_store` | Persist knowledge |+| **Storage** | `embeddings`, `vector_store`, `graph_store`, `triplet_store` | Persist knowledge || **Quality** | `deduplication`, `conflicts` | Validate and clean || **Context** | `context`, `provenance`, `change_management` | Track decisions and lineage |-| **Output** | `export`, `visualization`, `pipeline` | Deliver results |-----+| **Output** | `export`, `visualization`, `pipeline`, `explorer` | Deliver results |## Next Steps@@ -158,18 +146,16 @@ Semantica uses a modular, layered architecture — import only what you need.Knowledge graphs, ontologies, and reasoning explained in depth.</Card><Card title="Quickstart Tutorial" icon="play" href="quickstart">- Full 6-step pipeline with `<Steps>` walkthrough.+ Full 6-step pipeline walkthrough with working code.</Card>- <Card title="Cookbook" icon="flask" href="cookbook">- 40+ domain-specific Jupyter notebook tutorials.+ <Card title="Module Reference" icon="puzzle-piece" href="modules">+ Every module, class, and common chain explained.</Card><Card title="API Reference" icon="code" href="reference/context">Complete module documentation for every class and method.</Card></CardGroup>-----## Help<CardGroup cols={3}>diff --git a/docs/glossary.md b/docs/glossary.mdindex 3908f369..3240d29c 100644--- a/docs/glossary.md+++ b/docs/glossary.md@@ -1,174 +1,208 @@---title: "Glossary"-description: "Reference of terms and concepts used throughout Semantica."+description: "Reference definitions for terms and concepts used throughout Semantica."icon: "book"---<Tip>- Use Ctrl+F to search this page.+ Use Ctrl+F / Cmd+F to search this page for a specific term.</Tip>----+A quick-reference dictionary of every concept, data structure, algorithm, and standard referenced in Semantica's documentation and codebase.## 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 perceives its environment, reasons about information, and takes actions to achieve goals. In Semantica, agents use knowledge graphs for structured memory and context, with every decision recorded as a first-class object.-**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.+**Context Graph**+A persistent, queryable graph of everything an agent knows, decides, and reasons about — entities, relationships, decisions, and their causal links. The core data structure of `semantica.context`.-**Knowledge Graph (KG)** — A structured representation of knowledge using entities (nodes) and relationships (edges). KGs enable reasoning, querying, and semantic analysis of data.+**Decision**+A first-class object in Semantica: a recorded agent choice with category, scenario, reasoning, outcome, confidence score, causal chain, and source provenance. Stored and searchable via `context.record_decision()`.-**Relationship** — A connection between two entities that describes how they relate to each other (e.g., `works_for`, `located_in`, `founded_by`).+**Entity**+A distinct object or concept in the real world — a person, organization, location, event, or abstract concept. Entities are nodes in a knowledge graph, each with typed properties and a source provenance record.-**Semantic** — Relating to meaning in language or logic. Semantic understanding goes beyond keywords to comprehend context and intent.+**Knowledge Graph (KG)**+A structured representation of knowledge using entities (nodes) and relationships (edges). Knowledge graphs enable reasoning, querying, semantic search, and traceable inference — unlike flat vector stores.----+**Relationship**+A directed, typed connection between two entities: e.g., `works_for`, `located_in`, `founded_by`. Relationships carry confidence scores and provenance back to the source document.++**Semantic**+Relating to meaning in language or logic. Semantic understanding captures context and intent — going beyond keyword matching to understand what text *means*.## Data Processing-**Ingestion** — The process of loading data from various sources (files, databases, APIs, streams) into a system for processing.+**Chunking**+Splitting large documents into smaller pieces while preserving semantic context. Semantica supports recursive, semantic boundary, entity-aware, relation-aware, sliding window, structural, and table-aware chunking strategies.-**Normalization** — The process of standardizing data into a consistent format (e.g., converting dates to ISO format, standardizing entity names).+**Ingestion**+Loading data from external sources — files, databases, APIs, streams — into the pipeline as a unified `SourceDocument`. The first stage in every Semantica pipeline.-**Parsing** — Extracting structured information from unstructured or semi-structured documents like PDFs, Word documents, or web pages.+**Normalization**+Standardizing data into a consistent canonical form: converting dates to ISO format, canonicalizing entity names, fixing encoding issues, stripping noise. Ensures downstream extraction works on clean, consistent text.-**Chunking** — Breaking down large documents into smaller, manageable pieces while preserving context and meaning.-----+**Parsing**+Extracting structured text, layout, and metadata from unstructured or semi-structured documents — PDFs, Word files, HTML, PPTX. `DoclingParser` additionally handles multi-column layouts, merged-cell tables, and OCR.## 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.+**Abductive Reasoning**+Inference to the most plausible explanation for observed facts. One of six reasoning engines in `semantica.reasoning` — returns the most likely hypothesis given available evidence.-**RAG (Retrieval Augmented Generation)** — A technique that enhances LLM responses by retrieving relevant information from a knowledge base before generating an answer.+**Datalog**+A declarative logic programming language for knowledge base queries. Semantica's `DatalogEngine` supports recursive Horn clause rules with bottom-up semi-naive fixpoint semantics. Added in v0.4.0.-**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 similarity search with knowledge graph traversal. Every LLM response is grounded in structured graph context, with each claim traceable to a source node. Eliminates hallucination without source attribution.-**Inference** — The process of deriving new facts or conclusions from existing knowledge using logical rules.+**Inference**+Deriving new facts or conclusions from existing knowledge using logical rules — without the derived facts being explicitly present in the source data.----+**LLM (Large Language Model)**+An AI model trained on large text corpora, capable of understanding and generating natural language. Semantica integrates with 8+ LLM providers for entity extraction, relation extraction, and reasoning.-## Knowledge Graph Components+**RAG (Retrieval Augmented Generation)**+A technique that enhances LLM outputs by retrieving relevant context from a knowledge base before generating a response. GraphRAG extends this with graph traversal for more precise, structured retrieval.-**Node** — A vertex in a graph representing an entity or concept.+## Knowledge Graph Components-**Edge** — A connection between two nodes representing a relationship.+**Allen Interval Algebra**+A system of 13 relations for describing how two time intervals relate — before, after, meets, overlaps, during, starts, finishes, equals, and their inverses. Supported in `TemporalKnowledgeGraph` since v0.4.0.-**Property** — An attribute or characteristic of an entity or relationship (e.g., name, date, confidence score).+**BiTemporalFact**+A fact with two independent time dimensions: *valid time* (when it was true in the world) and *transaction time* (when it was recorded in the system). Enables full audit trails for slowly changing data.-**Triplet** — A basic unit of knowledge in RDF, consisting of a subject, predicate, and object (e.g., `<Apple_Inc> <founded_by> <Steve_Jobs>`).+**Edge**+A directed connection between two nodes in a graph, representing a typed relationship. Edges carry type, confidence score, and provenance metadata.-**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.+**Node**+A vertex in a knowledge graph representing an entity or concept. Nodes carry typed properties, a confidence score, and provenance linking back to the source document.-**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).+**Property**+An attribute or characteristic of an entity or relationship — name, date, URI, confidence score, source URL.-**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.+**Temporal Graph**+A knowledge graph where nodes and edges carry `valid_from` / `valid_until` time windows, enabling point-in-time queries and historical state reconstruction.----+**Triplet**+The atomic unit of knowledge: a `(subject, predicate, object)` triple — e.g., `(Apple_Inc, founded_by, Steve_Jobs)`. The building block of RDF and SPARQL-based storage.## 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.+**Coreference Resolution**+Determining when multiple expressions in text refer to the same entity — e.g., "Apple" and "the company" both referring to Apple Inc. Handled by `CoreferenceResolver` in `semantica.semantic_extract`.-**Relationship Extraction** — The task of identifying and extracting semantic relationships between entities in text.+**Entity Resolution**+Determining when two entity mentions across different documents refer to the same real-world entity. Also called entity linking or deduplication. Uses similarity scoring, blocking, and semantic embeddings.-**Entity Resolution** — The process of determining when two entity mentions refer to the same real-world entity, also known as entity linking or deduplication.+**Event Detection**+Identifying and classifying events in text — acquisitions, partnerships, product launches, regulatory decisions. Handled by `EventDetector` in `semantica.semantic_extract`.-**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.).+**Named Entity Recognition (NER)**+Identifying and classifying named entities in text into predefined categories: persons, organizations, locations, dates, products, and custom types. Three modes: pattern-based, ML-based, and LLM-based.-**Event Detection** — The task of identifying and classifying events (e.g., acquisitions, partnerships, announcements) in text.-----+**Relationship Extraction**+Identifying and extracting typed semantic relationships between entities — e.g., `(Google, acquired, DeepMind)` — from raw text.## Ontology & Schema-**Ontology** — A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).+**Axiom**+A statement accepted as true in an ontology, used to define logical constraints — e.g., "every Person must have a name", "Organization can have at most one CEO at a time".-**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.+**Class**+A category or type of entity in an ontology — `Person`, `Organization`, `Location`. Classes form a hierarchy and carry constraints validated by SHACL.-**Class** — In ontologies, a category or type of entity (e.g., `Person`, `Organization`, `Location`).+**Ontology**+A formal specification of domain concepts, relationships, and constraints — typically expressed in OWL. Semantica can auto-generate ontologies from knowledge graphs or import existing OWL/RDF/Turtle files.-**Axiom** — A statement or rule that is accepted as true without proof, used in ontologies to define logical constraints and relationships.+**Ontology Hub**+Semantica's v0.5.0 visual browser UI for the full ontology lifecycle: visual class editor, SHACL Studio, alignment authoring, health dashboard, and version-controlled diffs.-**OWL (Web Ontology Language)** — A W3C standard language for defining and instantiating ontologies on the web.+**OWL (Web Ontology Language)**+The W3C standard language for defining and instantiating ontologies. Semantica can generate, import, and export OWL ontologies.-**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.+**SHACL (Shapes Constraint Language)**+The W3C standard for validating RDF graphs against a set of shape constraints. Semantica auto-generates SHACL shapes from ontologies and validates graphs against them.-**SKOS (Simple Knowledge Organization System)** — A W3C standard for representing controlled vocabularies, taxonomies, and thesauri.+**SKOS (Simple Knowledge Organization System)**+A W3C standard for representing controlled vocabularies, taxonomies, and thesauri. Used in Semantica for domain vocabulary management.------## Data Storage & Retrieval+## 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 numerical vector that represents text, images, or other data in a continuous semantic space. Entities with similar meaning produce vectors that are close together — enabling similarity search and semantic matching.-**Vector Store** — A database optimized for storing and searching high-dimensional vectors, used for semantic similarity search.+**Graph Database**+A database optimized for storing and querying graph-structured data using node and edge primitives. Semantica supports Neo4j, FalkorDB, Apache AGE, and Amazon Neptune.-**Triplet Store** — A database designed specifically for storing and querying RDF triplets.+**Hybrid Search**+A retrieval strategy combining vector similarity search with keyword or metadata filtering — higher accuracy than either approach alone.-**Graph Database** — A database designed specifically for storing and querying graph-structured data.+**Triplet Store**+A database designed specifically for storing and querying RDF `(subject, predicate, object)` triples. Semantica supports Blazegraph, Apache Jena, and RDF4J.-**Hybrid Search** — A search strategy that combines multiple retrieval methods, typically vector search and keyword search, to improve accuracy.-----+**Vector Store**+A database optimized for storing and searching high-dimensional embedding vectors by similarity. Semantica supports FAISS, Pinecone, Weaviate, Qdrant, Milvus, and PgVector.## Graph Analytics-**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.+**Centrality**+A measure of a node's importance in the graph. Common metrics: PageRank (link-based importance), betweenness centrality (bridge nodes), closeness centrality (average distance to all others).-**Community Detection** — The process of identifying groups or clusters of densely connected nodes in a graph.+**Community Detection**+Identifying groups of densely connected nodes — clusters that share more internal links than external ones. Used for finding subject communities, fraud rings, and organizational clusters.-**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 semantic proximity to a target: `near`, `mid`, or `far`, based on embedding distance thresholds. Part of Distance Intelligence (v0.5.0).-**Distance Band** — A classification of a node's proximity to a target: `near`, `mid`, or `far`, based on semantic embedding distance thresholds.+**Distance Intelligence**+Semantica's v0.5.0 feature for semantic neighborhood exploration: N×N distance matrices, ego-mode visualization centered on a single entity, and distance band classification across the graph.----+**PageRank**+An algorithm measuring node importance based on the structure of incoming relationships — originally designed for web pages, applicable to any directed graph.-## Query Languages+## Query Languages & Standards-**Cypher** — A declarative query language for graph databases, particularly Neo4j.+**Cypher**+The declarative graph query language used by Neo4j and FalkorDB. Analogous to SQL for relational databases.-**SPARQL** — A query language for RDF data, similar to SQL for relational databases.+**Datalog**+A subset of Prolog used for deductive database queries. Semantica's `DatalogEngine` supports recursive Horn clause rules with guaranteed termination via bottom-up semi-naive fixpoint evaluation.-**RDF (Resource Description Framework)** — A W3C standard for representing information about resources in the form of subject-predicate-object triplets.+**RDF (Resource Description Framework)**+The W3C standard for representing information as subject-predicate-object triples. The basis of the semantic web and Semantica's triplet store.-**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).-----+**SPARQL**+The W3C query language for RDF data. Semantica's `SparqlReasoner` uses SPARQL for query-based inference over RDF graphs.## Data Quality-**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.+**Conflict Resolution**+Handling contradictory facts from multiple sources in the same knowledge graph. Semantica's `ConflictDetector` surfaces conflicts; resolution strategies include prefer-most-recent, prefer-most-reliable, majority-vote, and flag-for-review.-**Data Provenance** — Information about the origin, history, and lineage of data, including sources, timestamps, and transformations.+**Data Provenance**+Complete information about the origin, history, and lineage of every fact — source document, extraction method, timestamp, confidence score. W3C PROV-O compliant in Semantica.-**W3C PROV-O** — The W3C standard ontology for provenance. Semantica tracks lineage across all 17 modules in a PROV-O compliant format.+**Deduplication**+Identifying and merging duplicate entity records. Semantica v2 strategies (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to 7x faster than v1.----+**W3C PROV-O**+The W3C provenance ontology standard. Semantica tracks lineage across all modules in PROV-O compliant format — suitable for HIPAA, SOX, GDPR, and FDA 21 CFR Part 11 compliance.-## Technical Terms+## Security Terms-**API (Application Programming Interface)** — A set of functions and protocols that allow different software applications to communicate with each other.+**SSRF (Server-Side Request Forgery)**+A vulnerability where a server is induced to make requests to unintended destinations. Semantica validates `base_url` at construction time to prevent SSRF in LLM gateway configurations.-**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.--**XXE (XML External Entity)** — A security vulnerability in XML parsers. Semantica's `XMLIngestor` (v0.5.0) uses an XXE-safe lxml backend.--**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.-----+**XXE (XML External Entity)**+A vulnerability in XML parsers that allows attackers to read arbitrary files or trigger SSRF. Semantica's `XMLIngestor` (v0.5.0) uses an XXE-safe lxml backend.## See Also-- [Core Concepts](concepts) — deeper explanation of key ideas-- [Getting Started](getting-started) — first steps+- [Core Concepts](concepts) — deeper explanation of key ideas with code examples+- [Getting Started](getting-started) — first working examples- [Modules Guide](modules) — every module explained-- [API Reference](reference/context) — technical reference+- [API Reference](reference/context) — complete technical referencediff --git a/docs/index.md b/docs/index.mdindex b80b7807..d4845ac2 100644--- a/docs/index.md+++ b/docs/index.md@@ -7,27 +7,23 @@ description: "The Accountability and Context Layer for AI — Context Graphs ·**v0.5.0 is live** — Ontology Hub, Distance Intelligence, SHACL Studio, Parquet & XML ingestion, 12 security fixes. [What's new →](#whats-new)</Info>-> 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.-----+> 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 ProblemAI 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. 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 why AI cannot be deployed in healthcare, finance, legal, and government without custom guardrails built from scratch.+- **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're why AI cannot be deployed in healthcare, finance, legal, and government without custom guardrails built from scratch.## The Solution-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.+Semantica is the **accountability and context layer** you add on top of your existing AI stack. Not a replacement for LangChain or LlamaIndex — the infrastructure that makes their outputs trustworthy.- **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.@@ -36,9 +32,7 @@ Semantica is the **accountability and context layer** you add on top of your exi- **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 any LLM provider and any agent framework — Semantica is not a replacement, it's the accountability layer on top.-----+Works alongside any LLM provider and any agent framework.## Quick Start@@ -137,8 +131,6 @@ decision_id = context.record_decision(</Card></CardGroup>-----## What's New<AccordionGroup>@@ -177,11 +169,9 @@ pip install semantica==0.5.0</AccordionGroup>-----## Start Here-If you're new to Semantica, install first and then open [Quickstart](quickstart). Use [Core Concepts](concepts) or [API Reference](reference/context) when you need more context or exact details.+If you're new to Semantica, install first and then open [Quickstart](quickstart). Use [Core Concepts](concepts) for the mental model, or jump to [API Reference](reference/context) when you need exact details.<CardGroup cols={2}><Card title="Installation" icon="download" href="installation">@@ -191,18 +181,16 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)Build a complete knowledge graph pipeline in 5 minutes.</Card><Card title="Core Concepts" icon="book-open" href="concepts">- Use this for the mental model behind the API.+ The mental model behind the API.</Card><Card title="API Reference" icon="rectangle-terminal" href="reference/context">- Jump here when you need exact module, class, or method details.+ Jump here for exact module, class, and method details.</Card><Card title="Cookbook" icon="flask" href="cookbook">Explore domain notebooks once you have the basics working.</Card></CardGroup>-----## Capabilities<AccordionGroup>@@ -210,10 +198,10 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)<Accordion title="Context & Decision Intelligence" icon="brain">- **Context Graphs** — structured, persistent graph of entities, relationships, and decisions-- **Decision tracking** — `record_decision()` for full lifecycle management with causal chains+- **Decision tracking** — `record_decision()` with full lifecycle management and 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+- **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</Accordion>@@ -231,7 +219,7 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)<Accordion title="Provenance & Auditability" icon="shield-check">-- **W3C PROV-O** — lineage tracking across all 17 modules+- **W3C PROV-O** — lineage tracking across all 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@@ -244,16 +232,14 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)**Vector Stores:** FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory-**Export:** RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, OWL ontologies-**Graph Stores:** Neo4j, FalkorDB, Apache AGE, Amazon Neptune+**Export:** RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, OWL ontologies+</Accordion></AccordionGroup>-----## Module Reference| Module | What it provides |@@ -269,7 +255,7 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)| `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.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 |@@ -283,10 +269,8 @@ If you're new to Semantica, install first and then open [Quickstart](quickstart)| `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 |-----+| `semantica.utils` | Shared utilities — ID generation, date parsing, schema helpers |## Built for High-Stakes Domains@@ -304,8 +288,6 @@ Where every decision must be accountable and mistakes have real consequences:**Critical Infrastructure** — power grids, transportation safety, emergency response coordination.-----## Why Semantica?**Open source, MIT licensed.** No vendor lock-in, no paywalled features. Every line of code is available and forkable.diff --git a/docs/installation.md b/docs/installation.mdindex b1cf5cb4..ae12904e 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -9,14 +9,17 @@ icon: "download"</Check><Note>- Python 3.8 or higher required. Python 3.11+ recommended.+ Python 3.8 or higher is required. Python 3.11+ is recommended.</Note>-<Tip>- Once you're set up, read [Getting Started](getting-started) for the overview and [Quickstart](quickstart) for the end-to-end pipeline.-</Tip>+## System Requirements----+| Component | Minimum | Recommended |+| --------- | ------- | ----------- |+| Python | 3.8 | 3.11+ |+| OS | Windows / Linux / Mac | Linux / Mac |+| RAM | 4 GB | 16 GB+ |+| Storage | 2 GB | 20 GB+ (models and data) |## Basic Installation@@ -36,16 +39,14 @@ pip install semantica[all]python -c "import semantica; print(semantica.__version__)"```-----## Virtual Environment (Recommended)<Tabs><Tab title="venv">```bashpython -m venv venv- source venv/bin/activate # Linux / Mac- venv\Scripts\activate # Windows+ source venv/bin/activate # Linux / Mac+ venv\Scripts\activate # Windowspip install semantica```</Tab>@@ -58,8 +59,6 @@ python -c "import semantica; print(semantica.__version__)"</Tab></Tabs>-----## Optional DependenciesInstall only what you need:@@ -69,35 +68,32 @@ Install only what you need:```bashpip install semantica[gpu]```- Includes PyTorch with CUDA, FAISS GPU, CuPy.+ Includes PyTorch with CUDA, FAISS GPU, and CuPy.</Tab><Tab title="Visualization">```bashpip install semantica[viz]```- Includes PyVis, Graphviz, UMAP.+ Includes PyVis, Graphviz, and UMAP.</Tab><Tab title="LLM Providers">```bash- pip install semantica[llm-all] # all providers-- pip install semantica[llm-openai] # OpenAI- pip install semantica[llm-anthropic] # Anthropic- pip install semantica[llm-gemini] # Google Gemini- pip install semantica[llm-groq] # Groq- pip install semantica[llm-ollama] # Ollama (local)+ pip install semantica[llm-all] # all providers+ pip install semantica[llm-openai] # OpenAI+ pip install semantica[llm-anthropic] # Anthropic+ pip install semantica[llm-gemini] # Google Gemini+ pip install semantica[llm-groq] # Groq+ pip install semantica[llm-ollama] # Ollama (local)```</Tab><Tab title="Cloud">```bashpip install semantica[cloud]```- Includes AWS S3, Azure Blob, Google Cloud Storage.+ Includes AWS S3, Azure Blob, and Google Cloud Storage.</Tab></Tabs>-----## Install from SourceFor the latest development version or to contribute:@@ -106,24 +102,22 @@ For the latest development version or to contribute:git clone https://github.com/semantica-agi/semantica.gitcd semantica-pip install -e . # core only-pip install -e ".[all]" # all extras-pip install -e ".[dev]" # dev tools (pytest, black, etc.)+pip install -e . # core only+pip install -e ".[all]" # all extras+pip install -e ".[dev]" # dev tools (pytest, black, etc.)```-If you encounter issues with the PyPI release, install directly from the main branch:+Install directly from the main branch if the PyPI release has issues:```bashpip install git+https://github.com/semantica-agi/semantica.git@main```-----## Troubleshooting### ModuleNotFoundError-Check you have the right environment active:+Make sure you're in the right environment:```bashpip list | grep semantica@@ -135,7 +129,7 @@ pip install --upgrade semantica```bashpip install --upgrade pippip install build wheel-pip install semantica --no-deps # install without optional deps first+pip install semantica --no-deps # install without optional deps first```### GPU dependencies fail@@ -150,7 +144,7 @@ pip install semantica[gpu]### Permission denied```bash-pip install --user semantica # or use a virtual environment+pip install --user semantica # or use a virtual environment```### Windows `[all]` install fails@@ -165,19 +159,6 @@ pip install --upgrade semanticaInstall 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.------## System Requirements--| Component | Minimum | Recommended |-|-----------|---------|-------------|-| Python | 3.8 | 3.11+ |-| OS | Windows / Linux / Mac | Linux / Mac |-| RAM | 4 GB | 16 GB+ |-| Storage | 2 GB | 20 GB+ (for models and data) |------## Next Steps<CardGroup cols={3}>diff --git a/docs/learning-more.md b/docs/learning-more.mdindex b54b0443..b884bbb3 100644--- a/docs/learning-more.md+++ b/docs/learning-more.md@@ -4,38 +4,32 @@ description: "Structured learning paths, configuration reference, troubleshootinicon: "graduation-cap"----> Structured paths for going from beginner to production with Semantica.-----+Whether you're running your first pipeline or deploying Semantica in production, this page gives you a structured path forward — from beginner to enterprise-grade usage.## Learning Paths<CardGroup cols={3}><Card title="Beginner (1–2 hrs)" icon="seedling">New to Semantica and knowledge graphs.- [Start with Installation](installation)+ [Start with Installation →](installation)</Card><Card title="Intermediate (4–6 hrs)" icon="compass">- Comfortable with basics, building production apps.- [Start with Modules](modules)+ Comfortable with basics, building real applications.+ [Start with Modules →](modules)</Card><Card title="Advanced (8+ hrs)" icon="rocket">- Enterprise applications and customization.- [Start with Architecture](architecture)+ Enterprise deployments, customization, and extension.+ [Start with Architecture →](architecture)</Card></CardGroup>-----### Beginner Path1. [Installation Guide](installation) — set up your environment2. [Core Concepts](concepts) — understand KGs, embeddings, and extraction3. [Getting Started](getting-started) — first working example-4. [Quickstart Tutorial](quickstart) — build your first KG-5. [Welcome to Semantica notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb) — interactive introduction-----+4. [Quickstart Tutorial](quickstart) — build your first knowledge graph+5. [Welcome to Semantica notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb) — interactive introduction to all modules### Intermediate Path@@ -44,91 +38,140 @@ icon: "graduation-cap"3. [Embeddings notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/09_Embeddings.ipynb)4. [GraphRAG Complete notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)5. [Multi-Source Data Integration notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)-6. [Use Cases](use-cases) — domain-specific examples-----+6. [Use Cases](use-cases) — domain-specific examples with notebooks### Advanced Path-1. [Architecture Guide](architecture) — three-layer system overview+1. [Architecture Guide](architecture) — three-layer system, extension points, design decisions2. [Temporal Graphs notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/04_Temporal_Graphs.ipynb) — v0.4.0 temporal intelligence3. [Ontology notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb) — v0.5.0 Ontology Hub4. [Complete Visualization Suite notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)5. [Multi-Format Export notebook](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)-6. [Deep Dive](deep-dive) — internals and extension points-----## Configuration Reference+All settings can be overridden with environment variables — no code changes needed.+| Setting | Environment Variable | Default |-|---------|---------------------|---------|+| ------- | -------------------- | ------- || OpenAI API Key | `OPENAI_API_KEY` | `None` || Groq API Key | `GROQ_API_KEY` | `None` |+| Anthropic API Key | `ANTHROPIC_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-**`ModuleNotFoundError`**+### `ModuleNotFoundError: No module named 'semantica'`-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 and that the correct Python environment is active:-**`AuthenticationError`**+```bash+pip list | grep semantica+pip install --upgrade semantica+```-Set the relevant API key as an environment variable (`OPENAI_API_KEY`, `GROQ_API_KEY`, etc.). Never hardcode keys in source files.+For optional features, install the relevant extra:-**`MemoryError` or OOM crashes**+```bash+pip install "semantica[llm-openai]" # OpenAI provider+pip install "semantica[gpu]" # GPU acceleration+```-Reduce batch sizes or switch to a persistent graph backend (Neo4j, FalkorDB) instead of the default in-memory NetworkX backend.+### `AuthenticationError`-Slow processing on large datasets — enable parallel processing via `Pipeline(workers=N)` and use GPU acceleration for embedding models.+Set your API key as an environment variable — never hardcode keys in source files:-**Windows `[all]` installation fails (v0.5.0 fix)**+```bash+export OPENAI_API_KEY="sk-..."+export GROQ_API_KEY="gsk_..."+```-Use `pip install "semantica[core]"` instead of `pip install "semantica[all]"` on Windows. See the [Installation guide](installation) for the full list of extras.+### `MemoryError` or OOM crashes-cp1252 encoding crash on Windows (v0.5.0 fix) — pass `encoding="utf-8"` explicitly to `FileIngestor` or set `PYTHONIOENCODING=utf-8` in your environment.+Switch from the default in-memory NetworkX backend to a persistent graph database:----+```python+from semantica.graph_store import FalkorDBStore+from semantica.kg import GraphBuilder-## Performance Optimization+store = FalkorDBStore(host="localhost", port=6379)+builder = GraphBuilder(merge_entities=True, graph_store=store)+```++Also reduce batch sizes and enable streaming ingestion for large corpora.-**Batch processing** — process documents in batches rather than one at a time; configure chunk sizes based on available RAM.+### Slow processing on large datasets-**Parallel execution** — `Pipeline(workers=N)` runs extraction steps in parallel across documents.+Enable parallel execution and GPU acceleration:-**Backend selection:**+```python+from semantica.pipeline import Pipeline-| Operation | NetworkX | Neo4j / FalkorDB |-|-----------|----------|-----------------|+pipeline = Pipeline(workers=8, batch_size=32)+pipeline.run(sources)+```++```bash+pip install "semantica[gpu]" # CUDA-backed embeddings+```++### Windows `[all]` installation fails++Fixed in **v0.5.0**. Upgrade:++```bash+pip install --upgrade semantica+```++Or install extras individually: `pip install "semantica[core]"`, then add `[llm-openai]`, `[gpu]`, etc. as needed.++### cp1252 encoding crash on Windows++Fixed in **v0.5.0**. For earlier versions, pass encoding explicitly or set the environment variable:++```bash+set PYTHONIOENCODING=utf-8+```++## Performance Optimization++### Backend Selection++| Operation | NetworkX (default) | Neo4j / FalkorDB |+| --------- | ------------------ | ---------------- || Graph construction | Fast | Moderate || Query performance | Moderate | Fast |-| Scalability | Low (in-memory) | High (persistent) |+| Scalability | Low — in-memory only | High — persistent |+| Recommended for | Development, small graphs | Production, large corpora |-Use NetworkX for development and small graphs; switch to a persistent backend for production.+Use NetworkX for local development and prototyping. Switch to a persistent backend before deploying to production.----+### Batch Processing-## Security Best Practices+Process documents in batches rather than one at a time. Configure `chunk_size` based on available RAM — a good starting point is 1,000 documents per batch on a 16 GB machine.-**API keys** — store in environment variables or a secrets manager; never commit them to version control; rotate regularly.+### Deduplication v2-**Data privacy** — use local embedding models (Ollama, HuggingFace) for sensitive data; avoid sending PII to external APIs without appropriate data handling agreements.+If deduplication is a bottleneck, switch from v1 strategies to v2:-**Exports** — encrypt sensitive graph exports at rest; use the v0.5.0 SSRF-safe `base_url` validation when configuring custom LLM gateways.+```python+resolver = EntityResolver()+merged = resolver.resolve(entities, strategy="semantic_v2") # up to 7x faster+```----+## Security Best Practices-## See Also+- **API keys** — store in environment variables or a secrets manager; never commit them to version control; rotate on a schedule+- **Sensitive data** — use local embedding models (Ollama, HuggingFace) for PII or classified content; avoid sending sensitive data to external APIs without data handling agreements+- **Graph exports** — encrypt sensitive exports at rest; use the v0.5.0 SSRF-safe `base_url` validation when configuring custom LLM gateways+- **XML ingestion** — always use `XMLIngestor` (v0.5.0), which uses the XXE-safe lxml backend; never parse untrusted XML with the standard library parser<CardGroup cols={2}>- <Card title="Cookbook" icon="book-open" href="cookbook">- Interactive Jupyter notebook tutorials.+ <Card title="Cookbook" icon="flask" href="cookbook">+ Interactive Jupyter notebooks from beginner to advanced.</Card><Card title="FAQ" icon="circle-question" href="faq">Common questions answered.@@ -137,6 +180,6 @@ Use NetworkX for development and small graphs; switch to a persistent backend foComplete technical documentation.</Card><Card title="Use Cases" icon="briefcase" href="use-cases">- Real-world domain examples.+ Domain-specific examples with notebooks.</Card></CardGroup>diff --git a/docs/modules.md b/docs/modules.mdindex 4190eb1b..1f6aa0c3 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -5,15 +5,13 @@ icon: "puzzle-piece"---<Tip>- Just need a quick reference? Jump to the [Module Index](#module-index) at the bottom of this page.+ Looking for a quick reference? Jump to the [Module Index](#module-index) at the bottom.</Tip>----+Semantica is organized into **27 modules** across six logical layers. Each module is independently importable — you never pay for what you don't use.## Architecture Overview-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@@ -31,26 +29,24 @@ Semantica is organized into **six logical layers**, each with specific responsibAgent 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+ Export, visualization, and workflows. **Modules:** Export, Visualization, Pipeline, Explorer</Card></CardGroup>-----## Input Layer### Ingest-Data ingestion from files, web, databases, and streams.+Loads data from files, web, databases, and streams into a unified `SourceDocument` format.```pythonfrom semantica.ingest import FileIngestor, WebIngestor, ParquetIngestor, XMLIngestor-# Files (PDF, DOCX, CSV, Excel, PPTX, JSON, HTML, archives)+# Files: PDF, DOCX, CSV, Excel, PPTX, JSON, HTML, archivesingestor = FileIngestor()documents = ingestor.ingest_directory("data/")-# Web+# Web crawlweb_ingestor = WebIngestor()pages = web_ingestor.ingest_urls(["https://example.com"])@@ -63,14 +59,16 @@ xml = XMLIngestor(validate_xsd="schema.xsd")sources = xml.ingest("data/records/")```+**Available ingestors:** `FileIngestor`, `WebIngestor`, `ParquetIngestor`, `XMLIngestor`, `APIIngestor`, `DBIngestor`, `DuckDBIngestor`, `ElasticIngestor`, `EmailIngestor`, `FeedIngestor`, `GDriveIngestor`, `HuggingFaceIngestor`, `MCPIngestor`, `MongoIngestor`, `OntologyIngestor`, `PandasIngestor`, `RepoIngestor`, `SnowflakeIngestor`, `StreamIngestor`+### Parse-Document parsing and text extraction.+Extracts structured text and layout metadata from raw documents.```pythonfrom semantica.parse import DocumentParser, DoclingParser-# Standard parser+# Standard parser — all common formatsparser = DocumentParser()parsed = parser.parse_document("document.pdf")@@ -79,9 +77,11 @@ parser = DoclingParser(extract_tables=True, extract_images=True, output_format="parsed = parser.parse("data/annual_report.pdf")```+**Available parsers:** `DocumentParser`, `DoclingParser`, `CodeParser`, `CSVParser`, `DocxParser`, `EmailParser`, `ExcelParser`, `HTMLParser`, `ImageParser`, `JSONParser`, `MCPParser`, `MediaParser`, `PDFParser`, `PPTXParser`, `StructuredDataParser`, `WebParser`, `XMLParser`+### Split-Text chunking and segmentation for embedding and RAG pipelines.+Chunks text for embedding and RAG pipelines with awareness of semantic boundaries.```pythonfrom semantica.split import TextSplitter@@ -90,21 +90,21 @@ splitter = TextSplitter(method="semantic")chunks = splitter.split(text, chunk_size=1000, overlap=200)```-Methods: `recursive`, `semantic`, `entity-aware`, `relation-aware`.+**Chunking strategies:** `recursive`, `semantic`, `entity-aware`, `relation-aware`, `sliding_window`, `structural`, `table`### Normalize-Data cleaning and standardization.+Cleans and standardizes text before semantic processing.```pythonfrom semantica.normalize import DataNormalizernormalizer = DataNormalizer()-clean_text = normalizer.normalize_text(text)+clean_text = normalizer.normalize_text(text)standardized_date = normalizer.normalize_date("Jan 1st, 2020")```----+**Normalizers available:** text cleaning, entity canonicalization, date normalization, number normalization, encoding handling, language detection## Core Processing@@ -125,11 +125,13 @@ trip = TripletExtractor(method="llm", llm_provider=llm)triplets = trip.extract(text)```-Methods: `"pattern"`, `"ml"`, `"llm"`. LLM method supports all 8 providers.+**Extraction methods:** `"pattern"` (no API key), `"ml"` (local model), `"llm"` (any of the 8 supported providers)++**Additional extractors:** `CoreferenceResolver`, `EventDetector`, `SemanticAnalyzer`, `SemanticNetworkExtractor`### Knowledge Graph-Graph construction, algorithms, temporal model, and distance intelligence.+Graph construction, graph algorithms, temporal model, and distance intelligence.```pythonfrom semantica.kg import GraphBuilder, GraphAnalyzer, TemporalKnowledgeGraph, DistanceCalculator@@ -146,12 +148,14 @@ snapshot = tkg.at(datetime(2021, 6, 15))# 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"])+matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])```+**Graph algorithms available:** centrality calculation, community detection, connectivity analysis, entity resolution, link prediction, path finding, similarity calculation+### Ontology-SHACL, SKOS, alignments, diff/migration, auto-generation, and OWL/RDF — plus the visual Ontology Hub (v0.5.0).+Schema management including SHACL, SKOS, alignments, diff/migration, auto-generation, and the visual Ontology Hub (v0.5.0).```pythonfrom semantica.ontology import OntologyManager, SHACLGenerator@@ -161,19 +165,21 @@ ontology.add_class("Person", ["name", "birth_date"])ontology.add_relationship("works_for", "Person", "Organization")is_valid = ontology.validate_graph(kg)-shacl = SHACLGenerator()+shacl = SHACLGenerator()shapes = shacl.generate(ontology)```+**Components:** `OntologyManager`, `SHACLGenerator`, `OntologyGenerator`, `OntologyValidator`, `OntologyEvaluator`, `LLMGenerator`, `OWLGenerator`, `PropertyGenerator`, `DomainOntologies`, `NamespaceManager`+### Reasoning-Forward chaining, Rete, deductive, abductive, SPARQL, and Datalog reasoning.+Derives new facts from existing knowledge using multiple inference strategies.```pythonfrom semantica.reasoning import ReasoningEngine, DatalogEngine# Rule-based reasoning-engine = ReasoningEngine()+engine = ReasoningEngine()inferences = engine.infer(kg, rules=["transitivity", "symmetry"])# Datalog — recursive Horn clause rules (v0.4.0)@@ -182,42 +188,45 @@ datalog.add_rule("ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).")results = datalog.query("ancestor(alice, ?)")```----+**Engines:** forward chaining, Rete network, deductive, abductive, SPARQL, Datalog — all produce explainable inference paths## Storage### Embeddings-Vector embeddings and similarity computation.+Generates and manages vector embeddings for semantic similarity.```pythonfrom semantica.embeddings import EmbeddingGenerator-generator = EmbeddingGenerator(model="sentence-transformers")+generator = EmbeddingGenerator(model="sentence-transformers")embeddings = generator.generate(["text1", "text2"])similarity = generator.similarity(embeddings[0], embeddings[1])```-Supported: Sentence-Transformers, FastEmbed, OpenAI, BGE.+**Supported models:** Sentence-Transformers, FastEmbed, OpenAI, BGE++**Components:** `EmbeddingGenerator`, `TextEmbedder`, `VectorEmbeddingManager`, `GraphEmbeddingManager`, `PoolingStrategies`### Vector Store-Multi-backend vector database management.+Multi-backend vector database with hybrid search support.```pythonfrom semantica.vector_store import VectorStore-store = VectorStore(backend="faiss", dimension=768)+store = VectorStore(backend="faiss", dimension=768)store.add_vectors(embeddings, ids)results = store.search(query_vector, top_k=10)```-Backends: FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory.-Search modes: semantic top-k, hybrid (vector + keyword), metadata-filtered.+**Backends:** FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory++**Search modes:** semantic top-k, hybrid (vector + keyword), metadata-filtered### Graph Store-Graph database integration.+Connects to graph databases for persistent, query-able storage.```pythonfrom semantica.graph_store import GraphStore@@ -228,11 +237,11 @@ store.add_edges(relationships)results = store.query("MATCH (n)-[r]->(m) RETURN n, r, m")```-Backends: Neo4j, FalkorDB, Apache AGE, Amazon Neptune.+**Backends:** Neo4j, FalkorDB, Apache AGE, Amazon Neptune### Triplet Store-RDF triple-based storage with SPARQL.+RDF triple-based storage with SPARQL query support.```pythonfrom semantica.triplet_store import TripletStore@@ -242,40 +251,42 @@ store.add_triplets(subject, predicate, obj)results = store.sparql("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")```-Backends: Blazegraph, Apache Jena, RDF4J.-----+**Backends:** Blazegraph, Apache Jena, RDF4J## Quality Assurance### Deduplication-Entity deduplication v1/v2, similarity scoring, and merging.+Detects, scores, and merges duplicate entities across sources.```pythonfrom semantica.deduplication import EntityResolverresolver = EntityResolver()-merged = resolver.resolve(entities, strategy="semantic_v2")+merged = resolver.resolve(entities, strategy="semantic_v2")```-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.+**v2 strategies** (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to 7x faster than v1.++**Components:** `EntityResolver`, `DuplicateDetector`, `EntityMerger`, `SimilarityCalculator`, `ClusterBuilder`++**`DuplicateDetector` options:** `max_results`, `top_k_per_entity`, `min_similarity`, `sort_by`### Conflicts-Multi-source conflict detection and resolution.+Detects and resolves fact conflicts across overlapping knowledge sources.```pythonfrom semantica.conflicts import ConflictDetector-detector = ConflictDetector()+detector = ConflictDetector()conflicts = detector.detect_conflicts(kg)-resolved = detector.resolve(conflicts, strategy="most_recent")+resolved = detector.resolve(conflicts, strategy="most_recent")```-Detection types: value, type, temporal, and logical conflicts.+**Detection types:** value conflicts, type conflicts, temporal conflicts, logical conflicts----+**Resolution strategies:** prefer most recent, prefer most reliable source, majority vote, flag for manual review## Context & Memory@@ -293,15 +304,23 @@ context = AgentContext()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+ category="model_selection",+ scenario="...",+ reasoning="...",+ outcome="...",+ confidence=0.9,)+precedents = context.find_precedents("model selection", limit=5)```+**Components:** `AgentContext`, `ContextGraph`, `AgentMemory`, `DecisionRecorder`, `CausalAnalyzer`, `EntityLinker`, `PolicyEngine`+### Provenance-W3C PROV-O compliant lineage tracking across all 17 modules.+W3C PROV-O compliant lineage tracking across all modules.```pythonfrom semantica.provenance import ProvenanceManager@@ -311,36 +330,46 @@ manager.track_entity("entity_1", "document.pdf", "person")lineage = manager.get_lineage("entity_1")```+**Components:** `ProvenanceManager`, `IntegrityChecker`, `BridgeAxiom`, `ProvenanceStorage`+### Change Management-Version storage, change tracking, SHA-256 checksums, and audit trails.+Version control with SHA-256 checksums, diffs, and rollback.```pythonfrom semantica.change_management import TemporalVersionManager-manager = TemporalVersionManager(storage_path="versions.db")+manager = TemporalVersionManager(storage_path="versions.db")snapshot = manager.create_snapshot(kg, "v1.0", "[email protected]", "Initial version")-diff = manager.diff("v1.0", "v1.1")+diff = manager.diff("v1.0", "v1.1")```----+**Components:** `TemporalVersionManager`, `ChangeLog`, `OntologyVersionManager`, `VersionStorage`## Output & Orchestration### Export-RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, CSV, OWL ontologies.+Serializes graphs to downstream formats for analytics, semantic web, or graph databases.```python-from semantica.export import RDFExporter+from semantica.export import RDFExporter, ParquetExporter, ArangoDBExporter++# RDF formats+RDFExporter().export_to_rdf(graph, format="turtle", output="graph.ttl")-exporter = RDFExporter()-rdf = exporter.export_to_rdf(graph, format="turtle")+# Analytics+ParquetExporter().export(graph, output_dir="output/")++# ArangoDB+aql = ArangoDBExporter().export(graph)```+**Export formats:** RDF (Turtle, JSON-LD, N-Triples, XML), Parquet, ArangoDB AQL, CSV, OWL, Arrow, LPG, YAML, distance matrices+### Visualization-Interactive and static KG, ontology, embedding, and temporal visualization.+Renders interactive and static knowledge graph visualizations.```pythonfrom semantica.visualization import GraphVisualizer@@ -349,6 +378,10 @@ viz = GraphVisualizer()viz.visualize(graph, output="graph.html")```+**Visualizers:** `GraphVisualizer`, `OntologyVisualizer`, `EmbeddingVisualizer`, `SemanticNetworkVisualizer`, `TemporalVisualizer`, `AnalyticsVisualizer`++**Layout algorithms:** force-directed, hierarchical, circular+### PipelinePipeline DSL with parallel workers, retry policies, and failure handling.@@ -357,15 +390,17 @@ Pipeline DSL with parallel workers, retry policies, and failure handling.from semantica.pipeline import Pipelinepipeline = Pipeline()-pipeline.add_step("ingest", FileIngestor())-pipeline.add_step("extract", NERExtractor())-pipeline.add_step("build", GraphBuilder())+pipeline.add_step("ingest", FileIngestor())+pipeline.add_step("extract", NERExtractor())+pipeline.add_step("build", GraphBuilder())result = pipeline.run("data/")```-### Explorer (v0.4.0/v0.5.0)+**Components:** `Pipeline`, `PipelineBuilder`, `ExecutionEngine`, `FailureHandler`, `PipelineValidator`, `ParallelismManager`, `ResourceScheduler`-FastAPI Knowledge Explorer + Ontology Hub with WebSocket progress, thread-safe sessions, bidirectional path finding, and indexed search.+### Explorer++FastAPI Knowledge Explorer with Ontology Hub, WebSocket progress, bidirectional path finding, and indexed search (0.004ms on 118k nodes).```pythonfrom semantica.explorer import start_explorer@@ -374,25 +409,98 @@ start_explorer(graph=kg, port=8080)# Opens at http://localhost:8080```----+**Routes:** graph, ontology, provenance, decisions, analytics, SPARQL, temporal, annotations, export/import, vocabulary++## Utilities++### LLM Providers++Unified interface to all supported LLM providers.++```python+from semantica.llms import Groq, OpenAI, create_provider++llm = Groq(model="llama-3.3-70b-versatile")+llm = OpenAI(model="gpt-4o")+llm = create_provider("anthropic", model="claude-opus-4-7")+```++**Supported providers:** OpenAI, Anthropic, Google Gemini, Groq, Ollama, DeepSeek, Novita AI, LiteLLM (20+ models via one interface)++### MCP Server++Exposes Semantica as an MCP stdio server for IDE and agent integrations.++```bash+python -m semantica.mcp_server+```++**Integrations:** Claude Desktop, VS Code, Cursor, Windsurf, Cline — 12 MCP tools exposed++### Seed++Deterministic data seeding for testing and development.++```python+from semantica.seed import SeedManager++seed = SeedManager()+seed.populate(kg, dataset="companies", count=100)+```++### Evals++Evaluation harness for extraction and reasoning quality.++```python+from semantica.evals import Evaluator++evaluator = Evaluator()+scores = evaluator.evaluate(predicted_entities, ground_truth)+# Returns: {"precision": 0.91, "recall": 0.87, "f1": 0.89}+```++**Metrics:** precision, recall, F1 for NER, relation extraction, and reasoning++### Core++Base classes, shared data models, and the plugin registry used across all modules.++```python+from semantica.core import Orchestrator, PluginRegistry++registry = PluginRegistry()+registry.register("my_ingestor", MyCustomIngestor)+```++**Components:** `Orchestrator`, `PluginRegistry`, `ConfigManager`, `Lifecycle`++### Utils++Shared utilities for ID generation, date parsing, validation, and logging.++```python+from semantica.utils import helpers, validators, logging+```++**Components:** `helpers`, `validators`, `constants`, `types`, `exceptions`, `logging`, `ProgressTracker`## Common Module Chains-| Goal | Modules |-|------|---------|+| Goal | Pipeline |+| ---- | -------- || 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 || Temporal analysis | KG (Temporal) → Context → Change Management → Export || Compliance pipeline | Ingest → Semantic Extract → KG → Provenance → Export |-----+| Evaluation workflow | Ingest → Parse → Semantic Extract → Evals |## Module Index| 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` |@@ -410,16 +518,16 @@ start_explorer(graph=kg, port=8080)| [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` |+| [export](reference/export) | Data export | `RDFExporter`, `ParquetExporter` || [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+| [pipeline](reference/pipeline) | Workflow orchestration | `Pipeline`, `PipelineBuilder` |+| [explorer](reference/explorer) | Knowledge Explorer UI | `start_explorer` |+| [llms](reference/llms) | LLM providers | `Groq`, `OpenAI`, `create_provider` |+| [mcp_server](reference/mcp_server) | MCP stdio server | `python -m semantica.mcp_server` |+| [seed](reference/seed) | Test data seeding | `SeedManager` |+| [evals](reference/evals) | Quality evaluation | `Evaluator` |+| [core](reference/core) | Base classes & registry | `Orchestrator`, `PluginRegistry` |+| [utils](reference/utils) | Shared utilities | `helpers`, `validators` |<CardGroup cols={2}><Card title="Getting Started" icon="rocket" href="getting-started">diff --git a/docs/quickstart.md b/docs/quickstart.mdindex 00767e6c..ae68c050 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -8,9 +8,7 @@ icon: "rocket"**v0.5.0** — Ontology Hub, Distance Intelligence, Parquet & XML ingestion, 12 security fixes. [What's new →](index#whats-new)</Info>-This guide walks you through the end-to-end pipeline for building your first knowledge graph in 5 minutes. Start here after installation. If you still need setup help, see [Installation](installation). You need Python 3.8+ and nothing else to start. An LLM API key is optional; pattern-based extraction works out of the box.-----+This guide walks you through the end-to-end pipeline for building your first knowledge graph. Start here after installation. An LLM API key is optional — pattern-based extraction works out of the box.## Install@@ -39,8 +37,6 @@ python -c "import semantica; print(semantica.__version__)"# 0.5.0```-----## Full Pipeline<Steps>@@ -55,7 +51,7 @@ Load a document from a file, directory, URL, or database.from semantica.ingest import FileIngestoringestor = FileIngestor()-sources = ingestor.ingest("data/report.pdf")+sources = ingestor.ingest("data/report.pdf")# Also accepts: .docx, .html, .json, .csv, .xlsx, .pptx, .parquet, .xml```@@ -63,13 +59,13 @@ sources = ingestor.ingest("data/report.pdf")from semantica.ingest import WebIngestoringestor = WebIngestor(max_depth=2)-sources = ingestor.ingest("https://example.com/article")+sources = ingestor.ingest("https://example.com/article")``````python Parquet / XML (v0.5.0)from semantica.ingest import ParquetIngestor, XMLIngestor-# Parquet — single file or Hive-partitioned directory+# Single file or Hive-partitioned directorysources = ParquetIngestor().ingest("data/events.parquet")# XML with XSD schema validation@@ -90,12 +86,12 @@ from semantica.parse import DocumentParserparser = DocumentParser()parsed = parser.parse(sources[0])-print(parsed.text[:200]) # extracted text-print(parsed.metadata) # title, author, date, source+print(parsed.text[:200]) # extracted text+print(parsed.metadata) # title, author, date, source```<Tip>- For PDFs with tables, charts, or multi-column layouts, use `DoclingParser` — it uses advanced layout analysis and returns structured table data alongside text.+ For PDFs with tables, charts, or multi-column layouts, use `DoclingParser` — it applies advanced layout analysis and returns structured table data alongside text.</Tip>```python@@ -103,7 +99,7 @@ from semantica.parse import DoclingParserparser = DoclingParser()parsed = parser.parse(sources[0])-print(parsed.tables) # structured table objects+print(parsed.tables) # structured table objects```</Step>@@ -117,11 +113,11 @@ Identify named entities and extract typed relationships between them.```python Pattern-based (fast, no API key)from semantica.semantic_extract import NERExtractor, RelationExtractor-ner = NERExtractor(method="pattern")+ner = NERExtractor(method="pattern")entities = ner.extract(parsed)# Returns: [{"text": "Apple Inc.", "type": "ORGANIZATION", "confidence": 0.98}, ...]-rel = RelationExtractor(method="rule")+rel = RelationExtractor(method="rule")relationships = rel.extract(parsed, entities=entities)# Returns: [{"subject": "Steve Jobs", "predicate": "founded", "object": "Apple Inc."}, ...]```@@ -132,10 +128,10 @@ from semantica.llms import Groqllm = Groq(model="llama-3.3-70b-versatile")-ner = NERExtractor(method="llm", llm_provider=llm)-entities = ner.extract(parsed)+ner = NERExtractor(method="llm", llm_provider=llm)+entities = ner.extract(parsed)-rel = RelationExtractor(method="llm", llm_provider=llm)+rel = RelationExtractor(method="llm", llm_provider=llm)relationships = rel.extract(parsed, entities=entities)```@@ -151,17 +147,17 @@ Assemble extracted entities and relationships into a queryable knowledge graph.from semantica.kg import GraphBuilderbuilder = GraphBuilder(merge_entities=True)-graph = builder.build(entities=entities, relationships=relationships)+graph = builder.build(entities=entities, relationships=relationships)print(f"Graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges")# Query the graph-apple = graph.get_node("Apple Inc.")+apple = graph.get_node("Apple Inc.")founders = graph.get_neighbors("Apple Inc.", predicate="founded_by")```<Note>- `merge_entities=True` automatically resolves duplicate entity references (e.g., "Apple", "Apple Inc.", "AAPL") using semantic similarity — no manual deduplication needed.+ `merge_entities=True` automatically resolves duplicate entity references — "Apple", "Apple Inc.", "AAPL" — using semantic similarity. No manual deduplication needed.</Note></Step>@@ -174,8 +170,8 @@ Render an interactive, zoomable knowledge graph in the browser.from semantica.visualization import GraphVisualizerviz = GraphVisualizer(- layout="force", # "force" | "hierarchical" | "circular"- node_color_by="type", # color nodes by entity type+ layout="force", # "force" | "hierarchical" | "circular"+ node_color_by="type", # color nodes by entity typeshow_confidence=True,)viz.visualize(graph, output="graph.html")@@ -205,14 +201,14 @@ from semantica.export import ParquetExporterexporter = ParquetExporter()exporter.export(graph, output_dir="output/")-# Writes: nodes.parquet, edges.parquet — ready for Spark / BigQuery / Databricks+# Writes nodes.parquet + edges.parquet — ready for Spark, BigQuery, Databricks``````python ArangoDBfrom semantica.export import ArangoDBExporterexporter = ArangoDBExporter()-aql = exporter.export(graph)+aql = exporter.export(graph)# Returns ready-to-run AQL INSERT statements```@@ -222,8 +218,6 @@ aql = exporter.export(graph)</Steps>-----## Add Decision IntelligenceTrack every agent decision with full causal chains and provenance — one extra import:@@ -255,8 +249,6 @@ precedents = context.find_precedents("model selection reasoning", limit=5)influence = context.analyze_decision_influence(decision_id)```-----## Common Patterns<AccordionGroup>@@ -268,10 +260,10 @@ from semantica.semantic_extract import NERExtractor, RelationExtractortext = "Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976 in Cupertino, California."-ner = NERExtractor()-entities = ner.extract(text)+ner = NERExtractor()+entities = ner.extract(text)-rel = RelationExtractor()+rel = RelationExtractor()relationships = rel.extract(text, entities=entities)```@@ -282,12 +274,12 @@ relationships = rel.extract(text, entities=entities)```pythonfrom semantica.kg import GraphBuilder-builder = GraphBuilder(merge_entities=True)+builder = GraphBuilder(merge_entities=True)all_entities, all_rels = [], []for doc in parsed_docs:entities = ner.extract(doc)- rels = rel.extract(doc, entities=entities)+ rels = rel.extract(doc, entities=entities)all_entities.extend(entities)all_rels.extend(rels)@@ -296,7 +288,7 @@ 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">+<Accordion title="Temporal knowledge graph with point-in-time queries" icon="clock">```pythonfrom semantica.kg import TemporalKnowledgeGraph@@ -304,13 +296,13 @@ from datetime import datetimetkg = TemporalKnowledgeGraph()-tkg.add_node("Tim Cook", role="CEO", valid_from=datetime(2011, 8, 24))+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 ✓+print(snapshot.get_node("Steve Jobs")) # role: CEO```</Accordion>@@ -328,7 +320,7 @@ store = Neo4jStore()builder = GraphBuilder(merge_entities=True, graph_store=store)-graph = builder.build(entities=entities, relationships=relationships)+graph = builder.build(entities=entities, relationships=relationships)# Graph persisted to Neo4j — survives process restarts```@@ -342,7 +334,7 @@ from semantica.kg import GraphBuildertracker = ProvenanceTracker()builder = GraphBuilder(merge_entities=True, provenance=tracker)-graph = builder.build(entities=entities, relationships=relationships)+graph = builder.build(entities=entities, relationships=relationships)# Every node and edge has full lineagenode = graph.get_node("Apple Inc.")@@ -359,20 +351,18 @@ print(node.provenance)</AccordionGroup>-----## Troubleshooting<AccordionGroup><Accordion title="No entities extracted" icon="magnifying-glass">-The document likely contains scanned images rather than machine-readable text. Use OCR:+The document likely contains scanned images rather than machine-readable text. Enable OCR:```pythonfrom semantica.parse import DocumentParser-parser = DocumentParser(ocr=True) # enables Tesseract OCR+parser = DocumentParser(ocr=True) # enables Tesseract OCRparsed = parser.parse(sources[0])```@@ -395,14 +385,14 @@ pipeline.run(sources)</Accordion>-<Accordion title="Memory errors" icon="memory">+<Accordion title="Memory errors on large graphs" icon="memory">Switch from in-memory NetworkX to a persistent backend:```pythonfrom semantica.graph_store import FalkorDBStore-store = FalkorDBStore(host="localhost", port=6379)+store = FalkorDBStore(host="localhost", port=6379)builder = GraphBuilder(merge_entities=True, graph_store=store)```@@ -420,16 +410,14 @@ pip install --upgrade semantica</AccordionGroup>-----## Next Steps<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="Cookbook" icon="code" href="cookbook">- 15+ copy-paste examples for healthcare, finance, legal, and cybersecurity.+ <Card title="Module Reference" icon="puzzle-piece" href="modules">+ Every module explained with key classes and common chains.</Card><Card title="API Reference" icon="rectangle-terminal" href="reference/context">Complete documentation for every module, class, and parameter.diff --git a/docs/reference/change_management.md b/docs/reference/change_management.mdindex 0981f4ba..365fc66a 100644--- a/docs/reference/change_management.md+++ b/docs/reference/change_management.md@@ -4,34 +4,19 @@ description: "Version control, SHA-256 checksums, diff analysis, rollback, and aicon: "clock-rotate-left"----> Enterprise-grade version control and audit trails for knowledge graphs with data integrity verification.+`semantica.change_management` provides enterprise-grade versioning and audit trails for knowledge graphs and ontologies — SHA-256 checksums, snapshot history, diff analysis, rollback protection, and compliance-ready audit export (HIPAA, SOX, FDA 21 CFR Part 11).------## Overview--The **Change Management Module** provides versioning for knowledge graphs — SHA-256 checksums, full snapshot history, diff analysis, rollback protection, and compliance-grade audit trails (HIPAA, SOX, FDA 21 CFR Part 11).--<CardGroup cols={2}>- <Card title="TemporalVersionManager" icon="clock">- Snapshot, diff, rollback, and audit trail for knowledge graphs.- </Card>- <Card title="OntologyVersionManager" icon="sitemap">- Version control for OWL ontologies with diff and migration support.- </Card>- <Card title="VersionStorage" icon="database">- Pluggable storage — in-memory for tests, SQLite for production.- </Card>- <Card title="Integrity Verification" icon="shield-check">- SHA-256 checksums to detect unauthorized modifications.- </Card>-</CardGroup>+## What You Get----+- **`TemporalVersionManager`** — snapshot, diff, rollback, and audit trail for knowledge graphs+- **`OntologyVersionManager`** — version control for OWL ontologies with diff and migration support+- **`VersionStorage`** — pluggable storage: `InMemoryVersionStorage` for tests, `SQLiteVersionStorage` for production+- **`compute_checksum` / `verify_checksum`** — SHA-256 integrity verification+- **`ChangeLogEntry`** — structured record of every change in a snapshot## TemporalVersionManager-Version control for knowledge graphs:+Version control for knowledge graphs — snapshot, diff, and rollback:```pythonfrom semantica.change_management import TemporalVersionManager@@ -46,13 +31,11 @@ snapshot_id = manager.create_snapshot(message="Initial knowledge graph")-print(f"Snapshot {snapshot_id}")+print(f"Snapshot: {snapshot_id}")print(f"Checksum: {manager.get_checksum(snapshot_id)}")```------## Versioning+### List, Retrieve, and Rollback```python# List all versions@@ -63,14 +46,21 @@ for v in versions:# Retrieve a specific versionkg_v1 = manager.get_version("v1.0")-# Rollback+# Rollback to a previous version (safe by default — fails if data would be lost)manager.rollback(target_version="v1.0", allow_data_loss=False)```----+### Constructor Parameters++| Parameter | Type | Default | Description |+| --------- | ---- | ------- | ----------- |+| `storage_path` | `str` | `None` | Path to SQLite database; uses in-memory if omitted |+| `storage` | `VersionStorage` | `None` | Explicit storage backend instance |## Diff Analysis+Compare any two snapshots to see exactly what changed:+```pythondiff = manager.diff("v1.0", "v2.0")@@ -82,11 +72,9 @@ for change in diff.changes:print(f" [{change.type}] {change.element}: {change.description}")```-----## OntologyVersionManager-Version control for OWL ontologies:+Version control for OWL ontologies — save, diff, and track schema migrations:```pythonfrom semantica.change_management import OntologyVersionManager, OntologyVersion@@ -107,34 +95,27 @@ for change in diff.changes:print(f"[{change.type}] {change.class_name}: {change.description}")```------## VersionStorage--Pluggable storage backends:+## VersionStorage Backends```pythonfrom semantica.change_management import (- VersionStorage,InMemoryVersionStorage,SQLiteVersionStorage,)-# In-memory (tests and development)+# In-memory — for tests and development (data not persisted)storage = InMemoryVersionStorage()-# SQLite (production — persistent across restarts)+# SQLite — for production (persistent across restarts)storage = SQLiteVersionStorage(db_path="versions.db")# Pass to a version managermanager = TemporalVersionManager(storage=storage)```-----## Integrity Verification-SHA-256 checksums detect any unauthorized modification to the graph:+SHA-256 checksums detect any unauthorized modification to a graph between snapshots:```pythonfrom semantica.change_management import compute_checksum, verify_checksum@@ -142,30 +123,28 @@ from semantica.change_management import compute_checksum, verify_checksum# Compute checksum for a graphchecksum = compute_checksum(kg)-# Verify graph against stored checksum+# Verify graph against a stored checksumis_valid = verify_checksum(kg, expected_checksum=checksum)if not is_valid:- print("Warning: Graph has been modified since the checksum was recorded")+ raise RuntimeError("Graph has been modified since the checksum was recorded")```-----## Audit Trail+Full per-entity audit trail with CSV and JSON export for compliance reporting:+```python-# Full audit trail for an entity+# Get all changes for a specific entitytrail = 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+# Export audit trail for compliancemanager.export_audit_trail("audit.csv", format="csv")manager.export_audit_trail("audit.json", format="json")```-----## ChangeLogEntryEvery version snapshot includes a structured `ChangeLogEntry`:@@ -175,18 +154,14 @@ from semantica.change_management import ChangeLogEntryentry: ChangeLogEntry = manager.get_log_entry(snapshot_id)-print(entry.version)-print(entry.author)-print(entry.message)-print(entry.checksum)-print(entry.created_at)-print(entry.changes) # list of individual change records+print(entry.version) # "v1.0"+print(entry.author) # "[email protected]"+print(entry.message) # "Initial knowledge graph"+print(entry.checksum) # SHA-256 hex digest+print(entry.created_at) # datetime+print(entry.changes) # list of individual change records```------## See Also-<CardGroup cols={2}><Card title="Provenance" icon="link" href="provenance">W3C PROV-O lineage tracking.diff --git a/docs/reference/conflicts.md b/docs/reference/conflicts.mdindex 5185ca57..71cb232b 100644--- a/docs/reference/conflicts.md+++ b/docs/reference/conflicts.md@@ -4,68 +4,51 @@ description: "Multi-source conflict detection and resolution — value, type, teicon: "triangle-exclamation"----> Detect and resolve contradictions across multiple data sources before they silently corrupt your knowledge graph.+`semantica.conflicts` detects and resolves contradictions when multiple sources disagree on the same fact. It surfaces five conflict types, seven resolution strategies, and generates investigation guides for manual review — so conflicts never silently corrupt your knowledge graph.------## Overview--When multiple sources disagree on the same fact, the **Conflicts Module** detects and resolves the conflict rather than silently picking one value. It supports five detection types, seven resolution strategies, and generates investigation guides for manual review.+## What You Get-<CardGroup cols={2}>- <Card title="ConflictDetector" icon="magnifying-glass">- Value, type, temporal, logical, and relationship conflict detection.- </Card>- <Card title="ConflictResolver" icon="check-circle">- 7 resolution strategies including voting, credibility-weighted, and temporal.- </Card>- <Card title="ConflictAnalyzer" icon="chart-bar">- Pattern analysis, severity grouping, and trend identification.- </Card>- <Card title="InvestigationGuideGenerator" icon="list-check">- Auto-generate step-by-step investigation checklists for human review.- </Card>-</CardGroup>-----+- **`ConflictDetector`** — value, type, temporal, logical, and relationship conflict detection+- **`ConflictResolver`** — 7 resolution strategies including voting, credibility-weighted, and temporal+- **`SourceTracker`** — track which source each conflicting fact came from, with credibility scores+- **`ConflictAnalyzer`** — pattern analysis, severity grouping, and trend identification+- **`InvestigationGuideGenerator`** — auto-generate step-by-step investigation checklists for human review## ConflictDetector```python-from semantica.conflicts import ConflictDetector, ConflictType+from semantica.conflicts import ConflictDetectordetector = ConflictDetector()conflicts = detector.detect_conflicts(kg)for conflict in conflicts:print(f"[{conflict.conflict_type}] '{conflict.entity}' — {conflict.attribute}")- print(f" Sources: {conflict.sources}")+ print(f" Sources: {conflict.sources}")print(f" Severity: {conflict.severity:.2f}")```------## Detection Types--```python-# Detect all types (default)-conflicts = detector.detect_conflicts(kg)--# Detect specific types only-conflicts = detector.detect_value_conflicts(entities, "name")-conflicts = detector.detect_type_conflicts(entities)-conflicts = detector.detect_relationship_conflicts(kg)-```+### Detection Types| Type | What It Detects |-|------|-----------------|+| ---- | --------------- || `VALUE` | Same entity, same attribute, different values across sources || `TYPE` | Same entity classified as different types in different sources || `TEMPORAL` | Overlapping validity windows with contradictory facts || `LOGICAL` | Facts that violate ontology axioms or SHACL constraints || `RELATIONSHIP` | Inconsistent relationship properties across sources |----+Run targeted detection by type:++```python+# Detect all types (default)+conflicts = detector.detect_conflicts(kg)++# Detect specific types only+value_conflicts = detector.detect_value_conflicts(entities, "name")+type_conflicts = detector.detect_type_conflicts(entities)+relation_conflicts = detector.detect_relationship_conflicts(kg)+```## ConflictResolver@@ -77,20 +60,20 @@ results = resolver.resolve_conflicts(conflicts, strategy=ResolutionStrategy.VOTIfor result in results:print(f"Resolved '{result.attribute}' → {result.resolved_value}")- print(f" Strategy used: {result.strategy}")+ print(f" Strategy: {result.strategy}")```-Resolution strategies:+### Resolution Strategies| Strategy | Enum | Description ||----------|------|-------------|-| `voting` | `ResolutionStrategy.VOTING` | Most common value wins (majority vote) |-| `credibility_weighted` | `ResolutionStrategy.CREDIBILITY_WEIGHTED` | Weighted average by source credibility score |-| `most_recent` | `ResolutionStrategy.MOST_RECENT` | Prefer the most recently updated fact |-| `first_seen` | `ResolutionStrategy.FIRST_SEEN` | Prefer the first observed value |-| `highest_confidence` | `ResolutionStrategy.HIGHEST_CONFIDENCE` | Prefer the fact with the highest confidence score |-| `manual_review` | `ResolutionStrategy.MANUAL_REVIEW` | Flag for human review |-| `expert_review` | `ResolutionStrategy.EXPERT_REVIEW` | Escalate to domain expert |+| Majority vote | `ResolutionStrategy.VOTING` | Most common value wins |+| Credibility-weighted | `ResolutionStrategy.CREDIBILITY_WEIGHTED` | Weighted by source credibility score |+| Most recent | `ResolutionStrategy.MOST_RECENT` | Prefer the most recently updated fact |+| First seen | `ResolutionStrategy.FIRST_SEEN` | Prefer the first observed value |+| Highest confidence | `ResolutionStrategy.HIGHEST_CONFIDENCE` | Prefer the fact with the highest confidence score |+| Manual review | `ResolutionStrategy.MANUAL_REVIEW` | Flag for human review |+| Expert review | `ResolutionStrategy.EXPERT_REVIEW` | Escalate to a domain expert |Use the convenience aliases for shorter code:@@ -100,29 +83,29 @@ from semantica.conflicts import voting, credibility_weighted, most_recent, higheresults = resolver.resolve_conflicts(conflicts, strategy=voting)```-----## Source Credibility Scoring+Assign credibility weights per source so `CREDIBILITY_WEIGHTED` resolution favors authoritative sources:+```pythonfrom semantica.conflicts import SourceTrackertracker = SourceTracker()-tracker.set_credibility("pubmed", 0.95)-tracker.set_credibility("wikipedia", 0.80)+tracker.set_credibility("pubmed", 0.95)+tracker.set_credibility("wikipedia", 0.80)tracker.set_credibility("user_input", 0.60)-# Pass to resolver for credibility-weighted resolutionresolver = ConflictResolver(source_tracker=tracker)results = resolver.resolve_conflicts(- conflicts, strategy=ResolutionStrategy.CREDIBILITY_WEIGHTED+ conflicts,+ strategy=ResolutionStrategy.CREDIBILITY_WEIGHTED)```-`SourceTracker` also tracks property-to-source mapping, entity source references, and builds traceability chains:+`SourceTracker` also builds full traceability chains:```python-from semantica.conflicts import SourceTracker, SourceReference, PropertySource+from semantica.conflicts import SourceTrackertracker = SourceTracker()tracker.track_entity_source("apple_inc", "crunchbase")@@ -131,14 +114,12 @@ tracker.track_property_source("apple_inc", "revenue", "annual_report_2023")chain = tracker.get_traceability_chain("apple_inc")```-----## ConflictAnalyzer-Identify patterns across conflict sets:+Identify patterns and trends across large conflict sets:```python-from semantica.conflicts import ConflictAnalyzer, ConflictPattern+from semantica.conflicts import ConflictAnalyzeranalyzer = ConflictAnalyzer()@@ -151,13 +132,12 @@ for pattern in patterns:by_severity = analyzer.group_by_severity(conflicts)print(f"Critical: {len(by_severity['critical'])}")print(f"High: {len(by_severity['high'])}")+print(f"Low: {len(by_severity['low'])}")-# Trend analysis+# Trend analysis over timetrends = analyzer.analyze_trends(conflicts, time_window="30d")```-----## InvestigationGuideGeneratorAuto-generate human-readable investigation guides for conflicts that can't be automatically resolved:@@ -175,8 +155,6 @@ for step in guide.steps:print(f" Check: {step.check}")```-----## Convenience Functions```python@@ -191,10 +169,6 @@ analysis = analyze_conflicts(conflicts, method="pattern")guide = generate_investigation_guide(conflicts[0])```------## See Also-<CardGroup cols={2}><Card title="Deduplication" icon="copy" href="deduplication">Resolve duplicate entities before conflict detection.diff --git a/docs/reference/context.md b/docs/reference/context.mdindex 102288f2..1d3c4aea 100644--- a/docs/reference/context.md+++ b/docs/reference/context.md@@ -1,293 +1,261 @@---title: "Context Module"-description: "Agent context graphs, decision tracking, causal chains, and precedent search."+description: "Agent context graphs, decision tracking, causal chains, precedent search, and policy enforcement."icon: "brain"----> The intelligent brain for AI agents, providing memory, decision tracking, and knowledge organization.+`semantica.context` is the memory and decision layer for AI agents. It stores facts with provenance, records decisions as first-class objects with causal chains, and lets agents search their own history to stay consistent across runs.------## Overview+## What You Get-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.- </Card>- <Card title="Decision Intelligence" icon="diagram-project">- Track decisions, learn from past choices, and make consistent, improving decisions over time.- </Card>- <Card title="Easy-to-Use API" icon="code">- Simple methods that make complex features accessible without overwhelming complexity.- </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.- </Card>- <Card title="Production Ready" icon="check-circle">- Scalable, reliable, and tested for real-world applications.- </Card>-</CardGroup>--<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`** — unified interface for memory, decision tracking, and graph-backed retrieval+- **`ContextGraph`** — persistent knowledge graph with centrality analysis, community detection, and decision management+- **`AgentMemory`** — low-level embedding-backed memory with TTL, tagging, and importance scoring+- **`DecisionRecorder`** — records decisions with causal chains, confidence scores, and outcome tracking+- **`CausalAnalyzer`** — traces downstream impact of any decision+- **`PolicyEngine`** — validates decisions against configurable rules before they're recorded## AgentContext-The main interface that makes your agent intelligent. Handles memory, decisions, and knowledge organization automatically.--### Quick Start+The main entry point. Wraps memory, graph, and decision tracking behind a single API.```python-from semantica.context import AgentContext+from semantica.context import AgentContext, ContextGraphfrom semantica.vector_store import VectorStore-agent = AgentContext(vector_store=VectorStore(backend="inmemory", dimension=384))--memory_id = agent.store("User asked about Python programming")-results = agent.retrieve("Python tutorials")+context = AgentContext(+ vector_store=VectorStore(backend="faiss", dimension=768),+ knowledge_graph=ContextGraph(advanced_analytics=True),+ decision_tracking=True,+)```-### Decision Learning+### Store and Retrieve Memories```python-decision_id = agent.record_decision(- category="content_recommendation",- scenario="User wants Python tutorial",- reasoning="User mentioned being a beginner",- outcome="recommended_basics",- confidence=0.85+# Store a fact — embedded and indexed automatically+memory_id = context.store(+ "GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%",+ metadata={"source": "openai_blog", "date": "2024-01"})-similar_decisions = agent.find_precedents("Python tutorial", limit=3)+# Retrieve by semantic similarity+results = context.retrieve("LLM benchmark comparisons", top_k=5)+for r in results:+ print(f"{r['content']} (score: {r['score']:.3f})")```-### Full Setup+### Record and Search Decisions```python-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+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,)-insights = agent.get_context_insights()-```+# Find similar past decisions — prevents inconsistent choices+precedents = context.find_precedents("model selection reasoning", limit=5)-### 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 |+# Analyze downstream impact+influence = context.analyze_decision_influence(decision_id)+print(f"Decisions influenced: {len(influence.downstream_decisions)}")+```-### GraphRAG with Multi-Hop Reasoning+### Multi-Hop GraphRAG```pythonfrom semantica.llms import Groq-import os--llm = Groq(model="llama-3.1-8b-instant", api_key=os.getenv("GROQ_API_KEY"))-result = agent.query_with_reasoning(- query="What technologies work well together?",+llm = Groq(model="llama-3.3-70b-versatile")+result = context.query_with_reasoning(+ query="What technologies have we chosen and why?",llm_provider=llm,- max_hops=2+ max_hops=2,)-print(f"Response: {result['response']}")-print(f"Reasoning: {result['reasoning_path']}")+print(result["response"])+for step in result["reasoning_path"]:+ print(f" {step}")```----+### Constructor Parameters-## ContextGraph+| Parameter | Type | Default | Description |+| --------- | ---- | ------- | ----------- |+| `vector_store` | `VectorStore` | required | Backend for embedding-based memory retrieval |+| `knowledge_graph` | `ContextGraph` | `None` | Enables graph-backed relationships and analytics |+| `decision_tracking` | `bool` | `False` | Activates `DecisionRecorder` for every decision |+| `graph_expansion` | `bool` | `False` | Auto-expands graph from stored memories |+| `advanced_analytics` | `bool` | `False` | Enables centrality and community analysis |+| `kg_algorithms` | `bool` | `False` | Adds path-finding and link prediction |++### Core Methods-Organizes complex information and relationships into intelligent knowledge networks.+| Method | Returns | Description |+| ------ | ------- | ----------- |+| `store(content, metadata)` | `str` (memory_id) | Embed and store a fact |+| `retrieve(query, top_k)` | `List[Dict]` | Semantic similarity search |+| `record_decision(category, scenario, reasoning, outcome, confidence)` | `str` (decision_id) | Record a decision with full provenance |+| `find_precedents(scenario, category, limit)` | `List[Decision]` | Find similar past decisions |+| `analyze_decision_influence(decision_id)` | `InfluenceResult` | Trace downstream impact |+| `query_with_reasoning(query, llm_provider, max_hops)` | `Dict` | GraphRAG with multi-hop traversal |+| `get_context_insights()` | `Dict` | Analytics summary |-### Building a Knowledge Graph+## ContextGraph++The knowledge graph backing `AgentContext`. Can be used standalone for relationship modelling.```pythonfrom semantica.context import ContextGraph-knowledge = ContextGraph(advanced_analytics=True)--knowledge.add_node("Python", "language", properties={"popularity": "high"})-knowledge.add_node("FastAPI", "framework", properties={"language": "Python"})-knowledge.add_edge("Python", "FastAPI", "supports")-```+graph = ContextGraph(advanced_analytics=True)-### Decision Management+# Add nodes and edges+graph.add_node("Python", "language", properties={"paradigm": "multi-paradigm"})+graph.add_node("FastAPI", "framework", properties={"language": "Python"})+graph.add_edge("Python", "FastAPI", "enables")-```python-decision_id = knowledge.add_decision_simple(+# Decision management+decision_id = graph.add_decision_simple(category="technology_choice",- scenario="Framework selection for web API",- reasoning="FastAPI provides better performance for Python APIs",+ scenario="Web API framework selection",+ reasoning="FastAPI's async support and auto-docs match our requirements",outcome="selected_fastapi",confidence=0.92,- entities=["Python", "FastAPI", "web_project"]+ entities=["Python", "FastAPI"],)-similar = knowledge.find_precedents_by_scenario(- scenario="web framework",- category="technology_choice",- limit=3-)--impact = knowledge.analyze_decision_impact(decision_id)+similar = graph.find_precedents_by_scenario("web framework", limit=3)+impact = graph.analyze_decision_impact(decision_id)+chain = graph.trace_decision_chain(decision_id)```-### Core ContextGraph Methods+### ContextGraph Constructor Options-| 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 |+| Parameter | Type | Default | Description |+| --------- | ---- | ------- | ----------- |+| `advanced_analytics` | `bool` | `False` | PageRank, betweenness centrality |+| `centrality_analysis` | `bool` | `False` | Full centrality suite |+| `community_detection` | `bool` | `False` | Louvain community clustering |+| `node_embeddings` | `bool` | `False` | Node2Vec embeddings for structural similarity |------## Data Structures+## Decision Data Structure```python-@dataclass-class MemoryItem:- content: str- timestamp: datetime- metadata: Dict- embedding: List[float]- entities: List[Dict]-@dataclassclass Decision:- decision_id: str- category: str- scenario: str- reasoning: str- outcome: str- confidence: float # 0–1+ decision_id: str+ category: str+ scenario: str+ reasoning: str+ outcome: str+ confidence: float # 0.0 – 1.0decision_maker: str- timestamp: datetime- entities: List[str]- metadata: Dict+ timestamp: datetime+ entities: List[str]+ metadata: Dict+ causal_chain: List[str] # IDs of related decisions```----+## AgentMemory (Low-Level)-## Configuration Options+For fine-grained control over memory storage, TTL, and importance scoring:```python-# Minimal: memory only-agent = AgentContext(vector_store=vector_store)+from semantica.context import AgentMemory-# Recommended: memory + decision learning-agent = AgentContext(- vector_store=vector_store,- decision_tracking=True,- graph_expansion=True-)--# Full: all features-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+memory = AgentMemory(+ vector_store=VectorStore(backend="faiss", dimension=768),+ max_memories=10_000,+ ttl_days=90,)-# ContextGraph options-graph = ContextGraph(- advanced_analytics=True,- centrality_analysis=True,- community_detection=True,- node_embeddings=True-)+memory.store("Important fact", importance=0.9, tags=["compliance"])+results = memory.retrieve("fact query", top_k=5, min_importance=0.5)+memory.forget(memory_id)```------## Real-World Examples+## PolicyEngine-### Banking — Loan Decisions+Validate decisions against configurable rules before they're committed:```python-bank_agent = AgentContext(vector_store=bank_vector_store, decision_tracking=True)+from semantica.context import PolicyEngine-bank_agent.store("Customer has credit score 750, stable employment")+policy = PolicyEngine()+policy.add_rule("confidence_threshold", lambda d: d.confidence >= 0.7)+policy.add_rule("requires_reasoning", lambda d: len(d.reasoning) >= 20)-loan_decision = bank_agent.record_decision(- category="loan_approval",- scenario="First-time homebuyer mortgage",- reasoning="Good credit score, stable income, 20% down payment",- outcome="approved",- confidence=0.94-)--similar_loans = bank_agent.find_precedents("homebuyer", category="loan_approval")+# Validate before recording+is_valid, violations = policy.validate(decision_data)+if is_valid:+ context.record_decision(**decision_data)```+## Real-World Patterns+### Healthcare — Treatment Decisions```python-health_agent = AgentContext(vector_store=medical_vector_store, decision_tracking=True)+health_agent = AgentContext(+ vector_store=VectorStore(backend="faiss", dimension=768),+ decision_tracking=True,+)health_agent.store("Patient has hypertension, type 2 diabetes")-health_agent.store("Patient allergic to penicillin")+health_agent.store("Patient allergic to penicillin — verified 2024-01")-treatment_decision = health_agent.record_decision(+decision_id = health_agent.record_decision(category="treatment_plan",- scenario="Hypertension with diabetes",- reasoning="ACE inhibitors safe for diabetic patients",- outcome="prescribed_ace_inhibitor",- confidence=0.91+ scenario="Hypertension with comorbid diabetes",+ reasoning="ACE inhibitors are renoprotective in diabetic patients — preferred over beta blockers",+ outcome="prescribed_lisinopril",+ confidence=0.91,)++# Check for similar cases+precedents = health_agent.find_precedents("hypertension diabetes", limit=5)```----+### Finance — Loan Decisions-## See Also+```python+loan_agent = AgentContext(+ vector_store=VectorStore(backend="faiss", dimension=768),+ decision_tracking=True,+)++loan_agent.store("Applicant: credit score 750, DTI 28%, stable employment 4yr")++decision_id = loan_agent.record_decision(+ category="loan_approval",+ scenario="First-time homebuyer — 30yr fixed, 20% down",+ reasoning="Credit score above threshold, DTI within limits, stable income verified",+ outcome="approved_300k",+ confidence=0.94,+)+```<CardGroup cols={2}><Card title="Vector Store" icon="database" href="vector_store">- Long-term vector storage backend.+ Embedding storage backend for memory retrieval.</Card>- <Card title="KG Module" icon="diagram-project" href="kg">- Knowledge graph algorithms and analytics.+ <Card title="Knowledge Graph" icon="diagram-project" href="kg">+ Graph algorithms and analytics used inside ContextGraph.</Card><Card title="Reasoning" icon="microchip" href="reasoning">- Logical inference over context.+ Logical inference layered on top of context.</Card><Card title="Provenance" icon="link" href="provenance">- W3C PROV-O lineage tracking.+ W3C PROV-O lineage for every stored fact.</Card></CardGroup>-### Cookbook+### Cookbooks-- [Context Module](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb) — practical guide to agent memory and decision tracking · Intermediate-- [Advanced Context Engineering](https://github.com/semantica-agi/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/semantica-agi/semantica/blob/main/cookbook/advanced/12_Decision_Tracking_KG.ipynb) — decision lifecycle, precedent search, policy compliance · Advanced+- [Context Module](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb) — memory and decision tracking · Intermediate+- [Advanced Context Engineering](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb) — production FAISS + Neo4j setup · Advanced+- [Decision Tracking with KG Algorithms](https://github.com/semantica-agi/semantica/blob/main/cookbook/advanced/12_Decision_Tracking_KG.ipynb) — precedent search, policy enforcement · Advanceddiff --git a/docs/reference/core.md b/docs/reference/core.mdindex 1de640cd..8afa1553 100644--- a/docs/reference/core.md+++ b/docs/reference/core.md@@ -4,37 +4,24 @@ description: "Framework orchestration, lifecycle management, configuration, andicon: "gear"----> Framework infrastructure for complex workflows — lifecycle hooks, centralized config, and a plugin registry.+`semantica.core` is the coordination layer for the framework. For most tasks you should use individual modules directly (`semantica.ingest`, `semantica.kg`, etc.). Reach for Core when you need application-level lifecycle management, centralized configuration, or a plugin registry.------## Overview+## What You Get-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.+- **`Semantica`** — orchestration class for coordinating complex multi-module workflows+- **`ConfigManager`** — unified config loading, merging, and validation with environment variable overrides+- **`LifecycleManager`** — startup/shutdown hooks and component health monitoring+- **`PluginRegistry`** — dynamic plugin discovery, registration, and loading+- **`MethodRegistry`** — register and dispatch custom orchestration methods<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.+ **Use individual modules directly** 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>------## Semantica (Orchestration)+High-level entry point that coordinates the full KG construction pipeline:+```pythonfrom semantica.core import Semantica, ConfigManager@@ -56,31 +43,33 @@ finally:framework.shutdown(graceful=True)```+### Core Methods+| Method | Description |-|--------|-------------|+| ------ | ----------- || `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 |-----+| `build_knowledge_base(sources, **kwargs)` | Orchestrate full KG construction pipeline |+| `run_pipeline(pipeline, data)` | Execute an existing `Pipeline` instance |+| `get_status()` | Return system health and current state |+| `shutdown(graceful=True)` | Graceful shutdown — waits for in-flight operations |## ConfigManager+Centralized config loading with deep-merge and environment variable overrides:+```pythonfrom semantica.core import ConfigManagermanager = ConfigManager()config = manager.load_from_file("config.yaml")-# Merge base + override configs+# Merge base config with environment-specific overridesmerged = manager.merge_configs(manager.load_from_file("base.yaml"),manager.load_from_file("prod.yaml"),)-# Nested access+# Nested key access with dot notationbatch_size = config.get("processing.batch_size", default=16)config.set("processing.batch_size", 64)config.validate()@@ -105,17 +94,18 @@ logging:level: INFO```+Environment variable overrides (prefix `SEMANTICA_`):+```bash-# Environment variable overrides (SEMANTICA_ prefix)export SEMANTICA_PROCESSING_BATCH_SIZE=64export SEMANTICA_LOG_LEVEL=DEBUG```-----## LifecycleManager-State machine: `UNINITIALIZED` → `INITIALIZING` → `READY` → `RUNNING` → `STOPPING` → `STOPPED`+Manages framework state with a defined state machine and ordered startup/shutdown hooks:++**State machine:** `UNINITIALIZED` → `INITIALIZING` → `READY` → `RUNNING` → `STOPPING` → `STOPPED````pythonfrom semantica.core import LifecycleManager@@ -128,28 +118,29 @@ def init_db():def cleanup_db():print("Closing database connections...")-manager.register_startup_hook(init_db, priority=10)+# Lower priority values run first during startup+# Higher priority values run first during shutdown+manager.register_startup_hook(init_db, priority=10)manager.register_shutdown_hook(cleanup_db, priority=10)manager.startup()-# Health monitoring+# Component health monitoringclass DatabaseComponent:def health_check(self):return {"healthy": True, "message": "Connected"}manager.register_component("database", DatabaseComponent())summary = manager.get_health_summary()+# → {"database": {"healthy": True, "message": "Connected"}, ...}manager.shutdown(graceful=True)```-Lower `priority` values execute first during startup; higher values execute first during shutdown.------## PluginRegistry+Register custom components that participate in the full pipeline — provenance tracking, retry policies, and parallel execution included:+```pythonfrom semantica.core import PluginRegistry@@ -170,17 +161,15 @@ for info in registry.list_plugins():print(f"{info['name']}: {info['version']}")```-----## MethodRegistry-Register custom orchestration methods for extensibility.+Register custom orchestration methods and dispatch them by name:```pythonfrom semantica.core import method_registrydef fast_kb_builder(sources, **kwargs):- # custom logic — skip embeddings for speed+ # Custom logic — skip embeddings for speed...method_registry.register("knowledge_base", "fast", fast_kb_builder)@@ -189,13 +178,9 @@ from semantica.core.methods import build_knowledge_baseresult = build_knowledge_base(sources=["doc.pdf"], method="fast")```------## See Also-<CardGroup cols={2}><Card title="Pipeline" icon="arrows-turn-to-dots" href="pipeline">- Pipeline execution and orchestration.+ Pipeline execution and step orchestration.</Card><Card title="Utils" icon="wrench" href="utils">Shared utilities used by Core internally.diff --git a/docs/reference/deduplication.md b/docs/reference/deduplication.mdindex 57264462..6d6ad337 100644--- a/docs/reference/deduplication.md+++ b/docs/reference/deduplication.md@@ -4,34 +4,19 @@ description: "Entity deduplication v1/v2 — similarity scoring, blocking, mergiicon: "copy"----> Identify and merge duplicate entities across sources for a clean, single-source-of-truth knowledge graph.+`semantica.deduplication` detects and merges duplicate entities across sources to produce a clean, single-source-of-truth knowledge graph. **v2 strategies** (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to **7x faster** than v1 with fine-grained result control.------## Overview+## What You Get-The **Deduplication Module** detects and merges duplicate entities using similarity scoring, blocking strategies, and configurable merge policies. **v2 strategies** (`blocking_v2`, `hybrid_v2`, `semantic_v2`) are up to **7x faster** than v1 and support fine-grained result control.--<CardGroup cols={2}>- <Card title="DuplicateDetector" icon="magnifying-glass">- Pairwise and batch duplicate detection with similarity scoring.- </Card>- <Card title="EntityMerger" icon="code-merge">- Merge duplicate groups using configurable strategies with provenance preservation.- </Card>- <Card title="SimilarityCalculator" icon="percent">- Multi-factor similarity: Levenshtein, Jaro-Winkler, cosine, Jaccard, embedding.- </Card>- <Card title="ClusterBuilder" icon="layer-group">- Union-Find and hierarchical clustering for batch deduplication at scale.- </Card>-</CardGroup>-----+- **`DuplicateDetector`** — pairwise and batch duplicate detection with configurable strategies+- **`EntityMerger`** — merge duplicate groups with configurable property-level merge policies+- **`SimilarityCalculator`** — multi-factor similarity: Levenshtein, Jaro-Winkler, cosine, Jaccard, embedding+- **`ClusterBuilder`** — Union-Find and hierarchical clustering for large-scale batch deduplication+- **Convenience functions** — `detect_duplicates`, `merge_entities`, `calculate_similarity`## DuplicateDetector-The primary class for finding duplicate entity pairs:+Find duplicate entity pairs with configurable strategies and result filtering:```pythonfrom semantica.deduplication import DuplicateDetector@@ -43,23 +28,23 @@ for dup in duplicates:print(f"{dup.entity_a} ≈ {dup.entity_b} ({dup.similarity:.2f})")```-Fine-grained control:+Fine-grained control over strategy, thresholds, and result size:```pythonduplicates = detector.detect_duplicates(entities,- strategy="semantic_v2", # see strategies below- min_similarity=0.85, # minimum score to consider a match- top_k_per_entity=3, # max candidates per entity- max_results=100, # total result cap- sort_by="similarity", # "similarity" | "entity_id" | "cluster_size"+ strategy="semantic_v2", # see strategies table below+ min_similarity=0.85, # minimum score to consider a match+ top_k_per_entity=3, # max candidates per entity+ max_results=100, # total result cap+ sort_by="similarity", # "similarity" | "entity_id" | "cluster_size")```-Detection strategies:+### Detection Strategies| Strategy | Algorithm | 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 |@@ -69,11 +54,9 @@ Detection strategies:**v0.5.0 fix:** `DuplicateDetector` no longer produces duplicate definition errors when the same entity appears in multiple sources with identical definitions.</Note>-----## EntityMerger-Merges detected duplicate groups into canonical entities:+Merges detected duplicate groups into canonical entities, preserving provenance:```pythonfrom semantica.deduplication import EntityMerger@@ -81,39 +64,38 @@ from semantica.deduplication import EntityMergermerger = EntityMerger()merged_entities = merger.merge_duplicates(entities,- strategy="keep_most_complete", # see strategies below+ strategy="keep_most_complete", # see strategies table belowpreserve_provenance=True, # keep source references after merge)```-Merge strategies:+### Merge Strategies| Strategy | Behavior |-|----------|----------|+| -------- | -------- || `keep_first` | Keep the first entity in each duplicate group || `keep_last` | Keep the most recently seen entity || `keep_most_complete` | Keep the entity with the most non-null properties || `union` | Merge all properties — non-conflicting fields combined || `voting` | Most common property value wins |+Fine-grained per-property merge rules:+```python-# Fine-grained merge with custom property rules-from semantica.deduplication import PropertyMergeRule+from semantica.deduplication import EntityMerger, PropertyMergeRulemerger = EntityMerger(property_rules={- "name": PropertyMergeRule.KEEP_FIRST,- "aliases": PropertyMergeRule.UNION,+ "name": PropertyMergeRule.KEEP_FIRST,+ "aliases": PropertyMergeRule.UNION,"description": PropertyMergeRule.KEEP_LONGEST,})```-----## SimilarityCalculator-Compute multi-factor similarity between entity pairs:+Compute multi-factor similarity scores between entity pairs:```pythonfrom semantica.deduplication import SimilarityCalculator@@ -123,31 +105,24 @@ calc = SimilarityCalculator()score = calc.calculate_similarity(entity_a, entity_b)# → SimilarityResult(score=0.91, components={...})-print(score.score) # overall score 0.0–1.0-print(score.components["label"]) # label similarity-print(score.components["embedding"]) # semantic similarity-print(score.components["property"]) # property overlap+print(score.score) # overall score 0.0–1.0+print(score.components["label"]) # label similarity+print(score.components["embedding"]) # semantic similarity+print(score.components["property"]) # property overlap```-Individual metrics:+Individual string and vector metrics:```python-from semantica.deduplication import SimilarityCalculator--calc = SimilarityCalculator()--# String metrics-lev = calc.levenshtein("Apple Inc.", "Apple Inc")-jaro = calc.jaro_winkler("Steve Jobs", "Steven Jobs")-cos = calc.cosine_similarity(embedding_a, embedding_b)-jacc = calc.jaccard({"founded", "tech"}, {"founded", "technology"})+lev = calc.levenshtein("Apple Inc.", "Apple Inc")+jaro = calc.jaro_winkler("Steve Jobs", "Steven Jobs")+cos = calc.cosine_similarity(embedding_a, embedding_b)+jacc = calc.jaccard({"founded", "tech"}, {"founded", "technology"})```-----## ClusterBuilder-Build clusters from detected duplicate groups for large-scale batch processing:+Build entity clusters for large-scale batch deduplication:```pythonfrom semantica.deduplication import ClusterBuilder@@ -157,61 +132,51 @@ result = builder.build_clusters(entities, similarity_threshold=0.85)print(f"Clusters: {len(result.clusters)}")for cluster in result.clusters:- print(f" [{cluster.id}] {cluster.members} — quality: {cluster.cohesion:.2f}")-```-------## Convenience Functions--```python-from semantica.deduplication import detect_duplicates, merge_entities, calculate_similarity--# Quick detection-duplicates = detect_duplicates(entities, method="semantic_v2", similarity_threshold=0.85)--# Quick merge-merged = merge_entities(entities, duplicates, method="keep_most_complete")--# Quick similarity-score = calculate_similarity(entity_a, entity_b, method="hybrid_v2")+ print(f" [{cluster.id}] {cluster.members} — cohesion: {cluster.cohesion:.2f}")```-----## Blocking Strategies-Blocking reduces the O(n²) pairwise comparison to a manageable subset:+Blocking reduces the O(n²) pairwise comparison problem to a manageable candidate set:```python-from semantica.deduplication import DuplicateDetector-detector = DuplicateDetector(- blocking_strategy="token", # "token" | "phonetic" | "ngram"+ blocking_strategy="token", # "token" | "phonetic" | "ngram"blocking_threshold=0.6,similarity_threshold=0.85)```-----## Custom Similarity Functions+Register domain-specific similarity logic:+```python-from semantica.deduplication import MethodRegistry, method_registry+from semantica.deduplication import method_registry-def domain_similarity(entity_a, entity_b):- # e.g., match drug names by active compound+def drug_name_similarity(entity_a, entity_b):+ # Match drug names by active compoundreturn score # 0.0 to 1.0-method_registry.register("similarity", "drug_name", domain_similarity)+method_registry.register("similarity", "drug_name", drug_name_similarity)detector = DuplicateDetector(similarity_method="drug_name")```----+## Convenience Functions++```python+from semantica.deduplication import detect_duplicates, merge_entities, calculate_similarity-## See Also+# Quick detection+duplicates = detect_duplicates(entities, method="semantic_v2", similarity_threshold=0.85)++# Quick merge+merged = merge_entities(entities, duplicates, method="keep_most_complete")++# Quick similarity+score = calculate_similarity(entity_a, entity_b, method="hybrid_v2")+```<CardGroup cols={2}><Card title="Conflicts" icon="triangle-exclamation" href="conflicts">diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.mdindex 9df0ba09..6d03f996 100644--- a/docs/reference/embeddings.md+++ b/docs/reference/embeddings.md@@ -4,40 +4,20 @@ description: "Text and graph embedding generation — Sentence-Transformers, Fasicon: "vector-square"----> Unified interface for generating vector representations of text, nodes, and graphs.+`semantica.embeddings` converts text and graph structures into dense vectors for semantic search, entity resolution, and GraphRAG retrieval. A single provider-agnostic API abstracts Sentence-Transformers, FastEmbed, OpenAI, BGE, and Ollama.------## Overview+## What You Get-The **Embeddings Module** converts text and graph structures into dense vectors for semantic search, entity resolution, and GraphRAG retrieval. It abstracts multiple providers behind a single API and supports five pooling strategies.--<CardGroup cols={2}>- <Card title="EmbeddingGenerator" icon="bolt">- Main entry point — provider-agnostic text embedding generation.- </Card>- <Card title="TextEmbedder" icon="text-size">- Text-specific embedding with batching and caching.- </Card>- <Card title="GraphEmbeddingManager" icon="diagram-project">- Node and subgraph embedding for structural similarity.- </Card>- <Card title="VectorEmbeddingManager" icon="database">- Embedding lifecycle for vector store integration.- </Card>- <Card title="ProviderStore" icon="server">- Pluggable backends: OpenAI, BGE, FastEmbed, LlamaStore.- </Card>- <Card title="Pooling Strategies" icon="layer-group">- Mean, Max, CLS, Attention, Hierarchical pooling.- </Card>-</CardGroup>-----+- **`EmbeddingGenerator`** — main entry point, provider-agnostic text embedding with batching+- **`TextEmbedder`** — text-specific embedding with automatic batching and disk caching+- **`GraphEmbeddingManager`** — node and subgraph embeddings for structural similarity+- **`VectorEmbeddingManager`** — full embedding lifecycle for vector store integration+- **Provider stores** — `OpenAIStore`, `BGEStore`, `FastEmbedStore`, `LlamaStore`, `ProviderStoreFactory`+- **Pooling strategies** — Mean, Max, CLS, Attention, Hierarchical pooling## EmbeddingGenerator-Main entry point — handles provider selection and batching:+Main entry point — handles provider selection and batching automatically:```pythonfrom semantica.embeddings import EmbeddingGenerator@@ -46,7 +26,7 @@ from semantica.embeddings import EmbeddingGeneratorgenerator = EmbeddingGenerator(model="sentence-transformers")embeddings = generator.generate(["Text 1", "Text 2"])-# Specific model+# Specific BGE modelgenerator = EmbeddingGenerator(model="BAAI/bge-large-en-v1.5")embeddings = generator.generate(texts)@@ -58,29 +38,25 @@ generator = EmbeddingGenerator(api_key=os.getenv("OPENAI_API_KEY"))-# FastEmbed (fast CPU-optimized)+# FastEmbed (fast, CPU-optimized)generator = EmbeddingGenerator(model="fastembed")```------## Supported Models+### Supported Models| 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 |-| `llama` | any Ollama model | varies | Local inference |-----+| `llama` | any Ollama model | varies | Fully local inference |## TextEmbedder-Specialized for text with automatic batching:+Specialized for text with automatic batching and optional disk cache:```pythonfrom semantica.embeddings import TextEmbedder@@ -90,7 +66,7 @@ embedder = TextEmbedder(model="sentence-transformers", cache_dir=".emb_cache")# Single textembedding = embedder.embed("Hello world")-# Batch+# Batch — processes automatically in chunksembeddings = embedder.embed_batch(["Text 1", "Text 2", ..., "Text 10000"],batch_size=128,@@ -98,8 +74,6 @@ embeddings = embedder.embed_batch()```-----## Provider StoresEach provider implements the `ProviderStore` interface and can be used independently:@@ -122,7 +96,7 @@ embedding = store.embed("Hello world")store = FastEmbedStore(model="BAAI/bge-small-en-v1.5")embedding = store.embed("Hello world")-# LlamaStore (Ollama local)+# LlamaStore (Ollama — fully local)store = LlamaStore(model="llama3.2", base_url="http://localhost:11434")embedding = store.embed("Hello world")@@ -130,8 +104,6 @@ embedding = store.embed("Hello world")store = ProviderStoreFactory.create(provider="openai", model="text-embedding-3-small")```-----## Pooling StrategiesControl how token-level embeddings are aggregated into a single vector:@@ -142,14 +114,14 @@ from semantica.embeddings import (AttentionPooling, HierarchicalPooling, PoolingStrategyFactory)-# Mean pooling (default — best for most tasks)+# Mean pooling — default, best for most taskspooler = MeanPooling()pooled = pooler.pool(token_embeddings)-# Max pooling (captures strongest features)+# Max pooling — captures strongest activated featurespooler = MaxPooling()-# CLS token pooling (first token — good for classification)+# CLS token — good for classification taskspooler = CLSPooling()# Attention-weighted pooling@@ -158,15 +130,13 @@ pooler = AttentionPooling()# Hierarchical: chunk-level → global mean (best for long documents)pooler = HierarchicalPooling(chunk_size=512)-# Create from config+# Create from config stringpooler = PoolingStrategyFactory.create(strategy="mean")```-----## GraphEmbeddingManager-Embed graph nodes and subgraphs for structural similarity and GraphRAG:+Embed graph nodes and subgraphs for structural similarity and GraphRAG context:```pythonfrom semantica.embeddings import GraphEmbeddingManager@@ -176,23 +146,21 @@ manager = GraphEmbeddingManager(graph_store=graph_store)-# Embed all nodes+# Embed all nodes in the graphnode_embeddings = manager.embed_nodes(kg)-# Embed a specific subgraph (for GraphRAG context)+# Embed a subgraph centered on a node (for GraphRAG context)subgraph_embedding = manager.embed_subgraph(kg, center_node="Apple Inc.", hops=2)-# Find similar nodes+# Find semantically similar nodessimilar = manager.find_similar_nodes("apple_inc", top_k=5)```-----## VectorEmbeddingManager-Manages the full embedding lifecycle for vector store integration:+Manages the full embedding lifecycle — from raw text to stored, searchable vectors:```pythonfrom semantica.embeddings import VectorEmbeddingManager@@ -205,28 +173,45 @@ manager = VectorEmbeddingManager(vector_store=vector_store)-# Embed and store documents+# Embed documents and store in one stepids = manager.embed_and_store(documents, metadata=metadata_list)-# Search+# Search by semantic similarityresults = manager.search("machine learning algorithms", top_k=10)```-----## Similarity Computation```pythonfrom semantica.embeddings import calculate_similarity+# Cosine similarity (most common)score = calculate_similarity(embedding_a, embedding_b, method="cosine")# → 0.0 to 1.0-# Euclidean distance converted to similarity+# Euclidean distance (converted to similarity)score = calculate_similarity(embedding_a, embedding_b, method="euclidean")```----+## GPU Acceleration++```python+# Use CUDA GPU for faster embedding generation+generator = EmbeddingGenerator(model="sentence-transformers", device="cuda")+# device options: "cpu" | "cuda" | "mps"+```++## Embedding Cache++The embedding cache is used by Distance Intelligence (v0.5.0) to avoid recomputing embeddings for large N×N distance matrix calculations:++```python+embedder = TextEmbedder(+ model="sentence-transformers",+ cache_dir=".embeddings_cache",+ cache_ttl=3600 # seconds before cache entries expire+)+```## Convenience Functions@@ -242,44 +227,17 @@ emb = embed_text("Hello world", method="sentence_transformers")# Batchembs = generate_embeddings(texts, method="openai")-# Check what's installed+# Check which providers are installedproviders = check_available_providers()# → {"sentence_transformers": True, "fastembed": True, "openai": False}```------## GPU Acceleration--```python-generator = EmbeddingGenerator(model="sentence-transformers", device="cuda")-# device: "cpu" | "cuda" | "mps"-```-------## Caching--Embedding cache reuse is used by Distance Intelligence (v0.5.0) to avoid recomputing embeddings for large distance matrix calculations:--```python-embedder = TextEmbedder(- model="sentence-transformers",- cache_dir=".embeddings_cache",- cache_ttl=3600 # TTL in seconds-)-```-------## See Also-<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.+ Chunk text before embedding for better retrieval quality.</Card><Card title="KG Module" icon="diagram-project" href="kg">Distance Intelligence uses graph embeddings.diff --git a/docs/reference/evals.md b/docs/reference/evals.mdindex 7c9cdf5c..05dff800 100644--- a/docs/reference/evals.md+++ b/docs/reference/evals.md@@ -4,29 +4,30 @@ description: "Evaluation framework for measuring Knowledge Graph quality, extracicon: "chart-line"----> Measure and benchmark Knowledge Graph quality, extraction accuracy, and pipeline performance.+`semantica.evals` provides a comprehensive evaluation framework for measuring extraction accuracy, graph quality, and pipeline performance. Use it to benchmark extractors, validate pipeline output, and track quality regressions across runs.<Warning>- **Coming Soon** — This module is currently in active development. Documentation will be available in an upcoming release.+ **Coming Soon** — This module is currently in active development. Documentation will be expanded in the next release.</Warning>-----## Planned Capabilities-The Evals module will provide a comprehensive evaluation framework covering:+The Evals module will cover five evaluation areas:| 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+| ---- | ---------------- |+| **KG Quality** | Completeness, consistency, schema compliance, coverage metrics |+| **Extraction Accuracy** | NER precision / recall / F1, relation extraction metrics |+| **Pipeline Performance** | Throughput (docs/sec), latency per step, error rates |+| **Deduplication** | Merge accuracy, false positive / negative rates |+| **Reasoning** | Inference correctness, rule coverage, derivation depth |++## Scope++- **Offline evaluation** — compare against gold-standard annotated datasets+- **Regression tracking** — compare pipeline runs across commits or config changes+- **Live monitoring** — record quality metrics during production pipeline runs+- **Benchmark suites** — standard NER, RE, and KG construction benchmarks<CardGroup cols={2}><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">diff --git a/docs/reference/explorer.md b/docs/reference/explorer.mdindex d4f2c394..f387659f 100644--- a/docs/reference/explorer.md+++ b/docs/reference/explorer.md@@ -4,9 +4,7 @@ description: "Interactive FastAPI dashboard for knowledge graph exploration andicon: "map"----`semantica.explorer` provides a browser-based dashboard for exploring knowledge graphs, managing ontologies, and running visual analyses — no code required.-----+`semantica.explorer` is a browser-based dashboard for exploring knowledge graphs, managing ontologies, and running visual analyses — no code required after launch.## Installation@@ -16,8 +14,6 @@ pip install "semantica[explorer]"Requires `uvicorn` and `fastapi`. Included automatically with `pip install semantica[all]`.-----## Launch<CodeGroup>@@ -29,54 +25,48 @@ semantica-explorer --graph my_graph.json# Custom host and portsemantica-explorer --graph my_graph.json --host 0.0.0.0 --port 8080-# Don't auto-open browser+# Skip auto-opening the browsersemantica-explorer --graph my_graph.json --no-browser``````python Python-import subprocessfrom semantica.context import ContextGraphgraph = ContextGraph(advanced_analytics=True)# ... build or load your graph ...graph.save_to_file("my_graph.json")-# Launch the dashboard via CLI+import subprocesssubprocess.run(["semantica-explorer", "--graph", "my_graph.json", "--port", "8000"])``````python Module# Run directly as a Python module-# python -m semantica.explorer --graph my_graph.json --port 8000import subprocesssubprocess.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:+Core dashboard for navigating knowledge graphs:-- **Indexed search** — find any node by label or type; 0.004ms on 118k-node graphs+- **Indexed search** — find any node by label or type; 0.004ms on 118k-node graphs (v0.5.0)- **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.)+- **Filter by entity type** — focus on Person, Organization, Event, or any custom type- **Edge label display** — relationship types shown on all edges- **Graph declutter** — workspace layout controls for dense graphs@@ -92,9 +82,9 @@ Full ontology lifecycle management in the browser:### Distance Intelligence (v0.5.0)-Semantic neighborhood analysis:+Semantic neighborhood analysis centered on any node:-- **N×N distance matrices** — pairwise semantic distances across node sets+- **N×N distance matrices** — pairwise semantic distances across a set of nodes- **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@@ -108,14 +98,12 @@ Full FastAPI backend accessible at `http://localhost:8000/docs`:- Thread-safe sessions with rollback protection- Audit trail for all operations-----## API EndpointsThe 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 |@@ -126,10 +114,6 @@ The FastAPI server exposes a REST API alongside the browser dashboard: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.@@ -138,7 +122,7 @@ Full OpenAPI docs available at `http://localhost:8000/docs` when the server is rProgrammatic ontology management and SHACL generation.</Card><Card title="Visualization" icon="chart-network" href="visualization">- Programmatic graph rendering without the full Explorer server.+ Programmatic graph rendering without the Explorer server.</Card><Card title="Export" icon="file-export" href="export">Export to RDF, Parquet, AQL without launching a server.diff --git a/docs/reference/export.md b/docs/reference/export.mdindex 90d0d56a..0bf19e2f 100644--- a/docs/reference/export.md+++ b/docs/reference/export.md@@ -4,36 +4,17 @@ description: "Export knowledge graphs to RDF, Parquet, LPG, ArangoDB AQL, CSV, Gicon: "file-export"----> Export knowledge graphs and embeddings to 12+ formats with W3C-compliant serialization.+`semantica.export` serializes knowledge graphs to every downstream format — semantic web standards, analytics pipelines, graph databases, and vector stores. All exporters share a consistent `export(graph, path, format)` interface.------## Overview--The **Export Module** serializes knowledge graphs to every downstream format — semantic web standards, analytics pipelines, graph databases, and vector stores.+## What You Get-<CardGroup cols={2}>- <Card title="RDFExporter" icon="circle-nodes">- Turtle, JSON-LD, N-Triples, RDF/XML with namespace management.- </Card>- <Card title="ParquetExporter" icon="table">- Columnar storage for Spark, BigQuery, Databricks, Snowflake.- </Card>- <Card title="LPGExporter" icon="diagram-project">- Labeled Property Graph — Cypher CREATE statements for Neo4j and Memgraph.- </Card>- <Card title="ArangoAQLExporter" icon="database">- ArangoDB AQL INSERT statements for multi-model graph databases.- </Card>- <Card title="GraphExporter" icon="chart-network">- GraphML, GEXF, DOT formats for visualization tools like Gephi.- </Card>- <Card title="OWLExporter" icon="sitemap">- OWL 2.0 ontology export in Turtle, XML, and JSON-LD.- </Card>-</CardGroup>-----+- **`RDFExporter`** — Turtle, JSON-LD, N-Triples, RDF/XML with namespace management+- **`ParquetExporter`** — columnar storage for Spark, BigQuery, Databricks, Snowflake+- **`LPGExporter`** — Cypher CREATE/MERGE statements for Neo4j and Memgraph+- **`ArangoAQLExporter`** — AQL INSERT statements for ArangoDB multi-model graphs+- **`GraphExporter`** — GraphML, GEXF, DOT for visualization tools like Gephi+- **`OWLExporter`** — OWL 2.0 ontology export in Turtle, XML, and JSON-LD+- **`CSVExporter`**, **`VectorExporter`**, **`ArrowExporter`**, **`DistanceExporter`**, **`ReportGenerator`**## RDFExporter@@ -42,77 +23,74 @@ from semantica.export import RDFExporterexporter = RDFExporter()-# Turtle-rdf = exporter.export_to_rdf(graph, format="turtle")-exporter.export_to_file(graph, "output.ttl", format="turtle")+# Turtle (most readable RDF format)+exporter.export_to_file(graph, "output.ttl", format="turtle")-# JSON-LD+# JSON-LD (best for APIs and Linked Data)exporter.export_to_file(graph, "output.jsonld", format="json-ld")-# N-Triples-exporter.export_to_file(graph, "output.nt", format="nt")+# N-Triples (streaming-friendly, one triple per line)+exporter.export_to_file(graph, "output.nt", format="nt")++# RDF/XML (W3C standard, broadest compatibility)+exporter.export_to_file(graph, "output.xml", format="xml")-# RDF/XML-exporter.export_to_file(graph, "output.xml", format="xml")+# Export to string instead of file+rdf_str = exporter.export_to_rdf(graph, format="turtle")```-Namespace management:+Custom namespace management:```python-from semantica.export import NamespaceManager, RDFSerializer+from semantica.export import NamespaceManager, RDFExporterns_manager = NamespaceManager()-ns_manager.register("ex", "http://example.org/")+ns_manager.register("ex", "http://example.org/")ns_manager.register("schema", "https://schema.org/")exporter = RDFExporter(namespace_manager=ns_manager)```-----## ParquetExporter-For Spark, BigQuery, Databricks, and Snowflake analytics pipelines:+Columnar export for Spark, BigQuery, Databricks, and Snowflake analytics pipelines:```pythonfrom semantica.export import ParquetExporter-exporter = ParquetExporter(compression="snappy") # snappy | gzip | brotli | zstd | lz4+exporter = ParquetExporter(compression="snappy")+# compression options: snappy | gzip | brotli | zstd | lz4-# Export nodes and edges separately+# Export nodes and edges as separate Parquet filesexporter.export_nodes(graph, "nodes.parquet")exporter.export_edges(graph, "edges.parquet")-# Export full graph (partitioned)+# Export full graph partitioned by node typeexporter.export(graph, output_dir="graph_parquet/", partition_by="node_type")```-Parquet schema is explicitly typed with PyArrow for clean Spark/BigQuery ingestion.-----+Schema is explicitly typed with PyArrow for clean Spark/BigQuery ingestion.## LPGExporter-Labeled Property Graph — Cypher CREATE statements for Neo4j and Memgraph:+Labeled Property Graph export — Cypher statements for Neo4j and Memgraph:```pythonfrom semantica.export import LPGExporterexporter = LPGExporter()-# Generate Cypher+# CREATE statementscypher = exporter.to_cypher(graph)exporter.export(graph, "import.cypher", format="cypher")-# Generate MERGE statements (idempotent)+# MERGE statements (idempotent — safe to re-run)cypher_merge = exporter.to_cypher(graph, use_merge=True)```-----## ArangoAQLExporter-ArangoDB AQL INSERT statements for vertex and edge collections:+AQL INSERT statements for ArangoDB vertex and edge collections:```pythonfrom semantica.export import ArangoAQLExporter@@ -122,15 +100,13 @@ exporter = ArangoAQLExporter(edge_collection="relationships")-aql = exporter.export(graph) # returns AQL string+aql = exporter.export(graph) # returns AQL stringexporter.export_to_file(graph, "import.aql")```-----## GraphExporter-GraphML, GEXF, and DOT formats for visualization tools:+Export for visualization tools — GraphML, GEXF, and Graphviz DOT:```pythonfrom semantica.export import GraphExporter@@ -142,25 +118,23 @@ exporter.export(graph, "graph.gexf", format="gexf") # Gephi streamingexporter.export(graph, "graph.dot", format="dot") # Graphviz```-----## OWLExporter-OWL 2.0 ontology export:+OWL 2.0 ontology export in three serialization formats:```pythonfrom semantica.export import OWLExporterexporter = OWLExporter()-exporter.export(ontology, path="ontology.ttl", format="turtle")-exporter.export(ontology, path="ontology.owl", format="xml")+exporter.export(ontology, path="ontology.ttl", format="turtle")+exporter.export(ontology, path="ontology.owl", format="xml")exporter.export(ontology, path="ontology.json", format="json-ld")```-----## CSVExporter+Flat CSV export for spreadsheets and simple data pipelines:+```pythonfrom semantica.export import CSVExporter@@ -169,25 +143,19 @@ exporter.export_nodes(graph, "nodes.csv")exporter.export_edges(graph, "edges.csv")```-----## VectorExporter-Export embedding vectors for external vector stores:+Export embedding vectors for use in external vector stores:```pythonfrom semantica.export import VectorExporterexporter = VectorExporter()-exporter.export(embeddings, metadata, "vectors.json", format="json")-exporter.export(embeddings, metadata, "vectors.npy", format="numpy")--# FAISS-compatible binary format+exporter.export(embeddings, metadata, "vectors.json", format="json")+exporter.export(embeddings, metadata, "vectors.npy", format="numpy")exporter.export(embeddings, metadata, "vectors.faiss", format="faiss")```-----## ArrowExporterApache Arrow IPC format for zero-copy inter-process transfer:@@ -201,11 +169,9 @@ exporter.export(graph, "graph.arrow")Requires `pyarrow`. Falls back gracefully if not installed.-----## DistanceExporter-Export semantic distance matrices from Distance Intelligence:+Export semantic distance matrices produced by Distance Intelligence (v0.5.0):```pythonfrom semantica.export import DistanceExporter@@ -215,29 +181,20 @@ exporter.export_matrix(distance_matrix, node_labels, "distances.csv")exporter.export_ego(ego_neighborhood, center_node="Apple Inc.", path="ego.json")```-----## ReportGenerator-Generate human-readable reports from graph analytics:+Generate human-readable analytics reports from graph metrics:```pythonfrom semantica.export import ReportGeneratorgenerator = ReportGenerator()-# HTML report-generator.generate(graph, analytics_result, "report.html", format="html")--# Markdown-generator.generate(graph, analytics_result, "report.md", format="markdown")--# JSON-generator.generate(graph, analytics_result, "report.json", format="json")+generator.generate(graph, analytics_result, "report.html", format="html")+generator.generate(graph, analytics_result, "report.md", format="markdown")+generator.generate(graph, analytics_result, "report.json", format="json")```-----## Convenience Functions```python@@ -247,16 +204,14 @@ from semantica.export import (export_arrow, generate_report)-export_rdf(graph, "output.ttl", format="turtle")+export_rdf(graph, "output.ttl", format="turtle")export_parquet(graph, "output/", compression="snappy")-export_csv(graph, "nodes.csv", target="nodes")+export_csv(graph, "nodes.csv", target="nodes")export_lpg(graph, "import.cypher", method="cypher")export_arango(graph, "import.aql")export_graph(graph, "graph.graphml", format="graphml")```-----## Selective Export```python@@ -269,10 +224,6 @@ org_nodes = graph.filter(node_type="Organization")export_parquet(org_nodes, "organizations.parquet")```------## See Also-<CardGroup cols={2}><Card title="Triplet Store" icon="table" href="triplet_store">Store RDF exports in a SPARQL-queryable backend.@@ -281,9 +232,9 @@ export_parquet(org_nodes, "organizations.parquet")Export OWL ontologies.</Card><Card title="Provenance" icon="link" href="provenance">- Include provenance in RDF exports.+ Include provenance metadata in RDF exports.</Card><Card title="Pipeline" icon="gear" href="pipeline">- Add export as a pipeline step.+ Add export as a final pipeline step.</Card></CardGroup>diff --git a/docs/reference/graph_store.md b/docs/reference/graph_store.mdindex cef79b7b..8ee9e260 100644--- a/docs/reference/graph_store.md+++ b/docs/reference/graph_store.md@@ -4,24 +4,28 @@ description: "Unified interface for Neo4j, FalkorDB, Apache AGE, and Amazon Nepticon: "server"----> Unified interface for property graph databases.+`semantica.graph_store` provides a single API for persisting and querying knowledge graphs in production graph databases. Swap backends with a one-line change — no application code changes needed.------## Overview+## What You Get-The **Graph Store Module** provides a single API for persisting and querying knowledge graphs in production graph databases.--Backends: **Neo4j**, **FalkorDB**, **Apache AGE** (PostgreSQL), **Amazon Neptune**, and in-memory **NetworkX** for development.-----+- **`GraphStore`** — unified interface across all backends+- **Backends** — Neo4j, FalkorDB, Apache AGE (PostgreSQL), Amazon Neptune, NetworkX (in-memory)+- **Cypher queries** — full Cypher support for Neo4j and FalkorDB+- **Bulk operations** — batched node and edge loading with configurable batch sizes+- **Schema management** — create indexes and uniqueness constraints+- **Path traversal** — find paths between nodes with hop limits and relationship type filters## Basic Usage```pythonfrom semantica.graph_store import GraphStore-store = GraphStore(backend="neo4j", uri="bolt://localhost:7687", user="neo4j", password="password")+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password"+)store.add_nodes(entities)store.add_edges(relationships)@@ -29,62 +33,86 @@ store.add_edges(relationships)results = store.query("MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 10")```-----## Backends<Tabs><Tab title="Neo4j">- ```python- store = GraphStore(- backend="neo4j",- uri="bolt://localhost:7687",- user="neo4j",- password="password",- database="neo4j" # optional, default database- )- ```++```python+store = GraphStore(+ backend="neo4j",+ uri="bolt://localhost:7687",+ user="neo4j",+ password="password",+ database="neo4j" # optional — targets default database+)+```++Best for: production workloads, complex Cypher queries, Bloom visualization.+</Tab><Tab title="FalkorDB">- ```python- store = GraphStore(- backend="falkordb",- host="localhost",- port=6379,- graph_name="semantica"- )- ```++```python+store = GraphStore(+ backend="falkordb",+ host="localhost",+ port=6379,+ graph_name="semantica"+)+```++Best for: ultra-low latency queries over Redis protocol, edge deployments.+</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.++```python+store = GraphStore(+ backend="apache_age",+ connection_string="postgresql://user:pass@localhost/graphdb",+ graph_name="semantica"+)+```++Best for: teams already running PostgreSQL who want graph queries without a separate service. See the [Apache AGE Guide](../graph_stores/apache_age) for setup.++ </Tab>+ <Tab title="Amazon Neptune">++```python+store = GraphStore(+ backend="neptune",+ endpoint="your-cluster.cluster-xxxx.us-east-1.neptune.amazonaws.com",+ port=8182,+ region="us-east-1"+)+```++Best for: managed AWS deployments needing both SPARQL and Gremlin support.+</Tab><Tab title="In-Memory">- ```python- store = GraphStore(backend="networkx")- ```- For development and testing only — data is not persisted.++```python+store = GraphStore(backend="networkx")+```++Best for: development, testing, and graphs that fit in RAM. Data is not persisted.+</Tab></Tabs>-----## Querying```python-# Cypher (Neo4j, FalkorDB)+# Cypher query with parameters (Neo4j, FalkorDB)results = store.query("MATCH (p:Person)-[:WORKS_FOR]->(o:Organization) WHERE o.name = $org RETURN p",parameters={"org": "Apple Inc."})-# Path traversal+# Path traversal between two nodespaths = store.find_paths(start_node="steve_jobs",end_node="apple_inc",@@ -93,45 +121,70 @@ paths = store.find_paths()```-----## Graph Operations```python# Add a single node-store.add_node("apple_inc", node_type="Organization", properties={"founded": 1976})+store.add_node(+ "apple_inc",+ node_type="Organization",+ properties={"founded": 1976, "hq": "Cupertino"}+)-# Add a relationship-store.add_edge("steve_jobs", "apple_inc", "FOUNDED", properties={"year": 1976})+# Add a directed relationship+store.add_edge(+ "steve_jobs", "apple_inc",+ "FOUNDED",+ properties={"year": 1976}+)-# Bulk operations-store.add_nodes_bulk(entities, batch_size=1000)-store.add_edges_bulk(relationships, batch_size=1000)+# Bulk operations — use for large datasets+store.add_nodes_bulk(entities, batch_size=1000)+store.add_edges_bulk(relationships, batch_size=1000)# Deletestore.delete_node("node_id")store.delete_edge("edge_id")# Get neighbors-neighbors = store.get_neighbors("apple_inc", relationship_type="HAS_EMPLOYEE", direction="in")+neighbors = store.get_neighbors(+ "apple_inc",+ relationship_type="HAS_EMPLOYEE",+ direction="in" # "in" | "out" | "both"+)```-----## Schema Management+Create indexes and constraints to improve query performance:+```python-# Create indexes for performance+# Index for fast label lookupsstore.create_index(label="Person", property="name")-store.create_constraint(label="Organization", property="id", constraint_type="unique")-# Get schema+# Uniqueness constraint+store.create_constraint(+ label="Organization",+ property="id",+ constraint_type="unique"+)++# Inspect current schemaschema = store.get_schema()+print(schema["labels"])+print(schema["indexes"])+print(schema["constraints"])```----+## Backend Comparison-## See Also+| Backend | Query Language | Deployment | Best For |+| ------- | -------------- | ---------- | -------- |+| Neo4j | Cypher | Self-hosted / Aura | Production, complex traversals |+| FalkorDB | Cypher | Redis-based | Ultra-low latency, edge |+| Apache AGE | OpenCypher | PostgreSQL | Teams already on Postgres |+| Amazon Neptune | SPARQL / Gremlin | AWS managed | Cloud-native AWS deployments |+| NetworkX | Python API | In-memory | Development and testing |<CardGroup cols={2}><Card title="KG Module" icon="diagram-project" href="kg">@@ -141,9 +194,9 @@ schema = store.get_schema()PostgreSQL-based graph storage setup.</Card><Card title="Triplet Store" icon="table" href="triplet_store">- RDF triple store for semantic web.+ RDF triple store for semantic web and SPARQL queries.</Card><Card title="Visualization" icon="chart-bar" href="visualization">- Visualize stored graphs.+ Visualize graphs stored in any backend.</Card></CardGroup>diff --git a/docs/reference/ingest.md b/docs/reference/ingest.mdindex 3d222e82..847e226a 100644--- a/docs/reference/ingest.md+++ b/docs/reference/ingest.md@@ -4,15 +4,18 @@ description: "Universal data ingestion from files, Parquet, XML, web, feeds, stricon: "database"----> Universal data ingestion — the entry point for loading data into Semantica.+`semantica.ingest` is the entry point for loading data into Semantica. Every ingestor returns a list of `DataSource` objects with normalized content and metadata, regardless of the original format.------## Overview+## What You Get-The **Ingest Module** handles loading data from every common source into Semantica. All ingestors return a list of `DataSource` objects with content and metadata.-----+- **`FileIngestor`** — PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, ZIP/TAR archives+- **`ParquetIngestor`** — PyArrow-based Parquet with Hive-style partition support (v0.5.0)+- **`XMLIngestor`** — XXE-safe lxml with XSD/DTD validation (v0.5.0)+- **`WebIngestor`** — configurable web crawling with robots.txt support+- **`FeedIngestor`** — RSS/Atom feeds with live monitoring+- **`DBIngestor`** / **`SnowflakeIngestor`** — SQL databases and Snowflake+- **`StreamIngestor`** — Kafka, RabbitMQ, Kinesis, Pulsar real-time streams+- **`RepoIngestor`**, **`EmailIngestor`**, **`MCPIngestor`**, **`S3Ingestor`**, **`GCSIngestor`**## FileIngestor@@ -21,44 +24,40 @@ from semantica.ingest import FileIngestoringestor = FileIngestor()-# Single file+# Single file — type auto-detected from extensionsources = ingestor.ingest("data/report.pdf")-# Directory (recursive)+# Recursive directory scansources = ingestor.ingest_directory("data/", recursive=True)# Glob patternsources = ingestor.ingest("data/**/*.docx")```-Supported formats: PDF, DOCX, TXT, HTML, JSON, CSV, Excel (XLSX/XLS), PPTX, ZIP/TAR archives. File type is auto-detected.-----+Supported formats: PDF, DOCX, TXT, HTML, JSON, CSV, Excel (XLSX/XLS), PPTX, ZIP/TAR archives.## ParquetIngestor (v0.5.0)-PyArrow-based ingestion for Apache Parquet files.+PyArrow-based ingestion for Apache Parquet files, including Hive-style partitioned datasets:```pythonfrom semantica.ingest import ParquetIngestoringestor = ParquetIngestor()-# Single file+# Single Parquet filesources = ingestor.ingest("data/events.parquet")-# Partitioned directory (Hive-style: year=2024/month=01/...)+# Partitioned directory (year=2024/month=01/...)sources = ingestor.ingest("data/partitioned/")-# Selective columns+# Load only specific columnssources = ingestor.ingest("data/events.parquet", columns=["id", "text", "timestamp"])```-----## XMLIngestor (v0.5.0)-XXE-safe lxml-based ingestion with optional XSD/DTD validation.+XXE-safe lxml-based ingestion with optional schema validation:```pythonfrom semantica.ingest import XMLIngestor@@ -77,20 +76,18 @@ sources = ingestor.ingest("data/feed.xml")```<Note>- The `XMLIngestor` uses lxml with XXE disabled (`resolve_entities=False`) to prevent XML External Entity injection attacks.+ `XMLIngestor` uses lxml with `resolve_entities=False` to prevent XML External Entity (XXE) injection attacks.</Note>-----## WebIngestor```pythonfrom semantica.ingest import WebIngestoringestor = WebIngestor(- rate_limit=1.0, # seconds between requests- respect_robots=True, # honor robots.txt- max_depth=2 # crawl depth+ rate_limit=1.0, # seconds between requests+ respect_robots=True, # honor robots.txt+ max_depth=2 # crawl depth from seed URLs)# Single URL@@ -103,8 +100,6 @@ sources = ingestor.ingest_urls([])```-----## FeedIngestor (RSS/Atom)```python@@ -113,18 +108,19 @@ from semantica.ingest import FeedIngestoringestor = FeedIngestor()sources = ingestor.ingest("https://feeds.example.com/rss")-# Monitor for updates-ingestor.monitor("https://feeds.example.com/rss", interval=300, callback=process_new_items)+# Live monitoring — callback fires on new items+ingestor.monitor(+ "https://feeds.example.com/rss",+ interval=300,+ callback=process_new_items+)```------## DBIngestor (SQL / NoSQL)+## DBIngestor (SQL)```pythonfrom semantica.ingest import DBIngestor-# PostgreSQLingestor = DBIngestor(connection_string="postgresql://user:pass@localhost/db",query="SELECT id, content, created_at FROM documents WHERE status='active'"@@ -132,12 +128,11 @@ ingestor = DBIngestor(sources = ingestor.ingest()```-----## SnowflakeIngestor```pythonfrom semantica.ingest import SnowflakeIngestor+import osingestor = SnowflakeIngestor(account=os.getenv("SNOWFLAKE_ACCOUNT"),@@ -150,50 +145,59 @@ ingestor = SnowflakeIngestor(sources = ingestor.ingest(query="SELECT * FROM documents")```-----## Other Ingestors| Class | Source |-|-------|--------|+| ----- | ------ || `StreamIngestor` | Kafka, RabbitMQ, Kinesis, Pulsar || `RepoIngestor` | Git repositories (GitHub, GitLab) |-| `EmailIngestor` | IMAP/POP3 servers |+| `EmailIngestor` | IMAP/POP3 servers with attachment extraction || `MCPIngestor` | Model Context Protocol servers || `S3Ingestor` | AWS S3 buckets || `GCSIngestor` | Google Cloud Storage |-----+| `MongoIngestor` | MongoDB collections |+| `DuckDBIngestor` | DuckDB databases |+| `GDriveIngestor` | Google Drive |## DataSource Object-All ingestors return a list of `DataSource` objects:+All ingestors return a list of `DataSource` objects with a consistent schema:```python@dataclassclass 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]+ content: str # raw text content+ source_id: str # unique identifier+ source_type: str # "file" | "web" | "database" | "stream" | ...+ metadata: Dict # title, author, url, date, page_count, etc.+ raw_bytes: Optional[bytes] # original binary content if available```----+## Custom Ingestors++Register a custom ingestor and it participates in the full pipeline:++```python+from semantica.ingest.registry import method_registry++def my_ingestor(source, **kwargs):+ # Return a list of DataSource-compatible dicts+ return [{"content": "...", "metadata": {}, "source_id": source}]-## See Also+method_registry.register("file", "my_format", my_ingestor)+```<CardGroup cols={2}><Card title="Parse" icon="file-lines" href="parse">- Parse raw sources into structured text.+ Parse raw sources into structured text and tables.</Card><Card title="Pipeline" icon="gear" href="pipeline">- Orchestrate ingest as part of a pipeline.+ Orchestrate ingest as the first pipeline step.</Card><Card title="Snowflake Integration" icon="snowflake" href="../integrations/snowflake">- Snowflake-specific setup guide.+ Snowflake-specific setup and authentication guide.</Card><Card title="Provenance" icon="link" href="provenance">- Track lineage from ingest to inference.+ Track lineage from ingest through to inference.</Card></CardGroup>diff --git a/docs/reference/kg.md b/docs/reference/kg.mdindex 0b20ffad..09d4d327 100644--- a/docs/reference/kg.md+++ b/docs/reference/kg.md@@ -4,44 +4,26 @@ description: "Graph construction, temporal models, analytics, and distance intelicon: "diagram-project"----> High-level KG construction, management, and analysis system.+`semantica.kg` transforms extracted entities and relationships into structured, queryable knowledge graphs. It includes temporal support, a full suite of graph analytics algorithms, node embeddings, and Distance Intelligence (v0.5.0).------## Overview+## What You Get-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>+- **`GraphBuilder`** — construct graphs from entities and relationships with automatic entity merging+- **`TemporalKnowledgeGraph`** — time-aware edges (`valid_from`/`valid_until`) and point-in-time queries (v0.4.0)+- **`DistanceCalculator`** — semantic neighborhoods, N×N distance matrices, and distance band classification (v0.5.0)+- **`CentralityCalculator`** — PageRank, degree, betweenness, closeness, eigenvector centrality+- **`CommunityDetector`** — Louvain, Leiden, Label Propagation, K-Clique community detection+- **`PathFinder`** — Dijkstra, A\*, BFS, K-Shortest path algorithms+- **`LinkPredictor`** — Preferential Attachment, Jaccard, Adamic-Adar link prediction+- **`NodeEmbedder`** — Node2Vec, DeepWalk, Word2Vec structural embeddings<Tip>- **Related modules:** Use `semantica.conflicts` for conflict detection and `semantica.deduplication` for advanced entity resolution.+ For conflict detection and advanced entity resolution, use `semantica.conflicts` and `semantica.deduplication` alongside this module.</Tip>-----## GraphBuilder-Constructs knowledge graphs from raw entities and relationships.+Constructs knowledge graphs from extracted entities and relationships:```pythonfrom semantica.kg import GraphBuilder@@ -51,29 +33,33 @@ kg = builder.build(entities=entities, relationships=relationships)```| 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 |-----+| `build_single_source(data)` | Build graph from a single data source |+| `merge_entities()` | Deduplicate and merge entities during construction |## Temporal Knowledge Graphs (v0.4.0)+Attach `valid_from` / `valid_until` time windows to nodes and edges for point-in-time queries and historical analysis:+```pythonfrom semantica.kg import TemporalKnowledgeGraph, TemporalGraphQueryfrom datetime import datetime-# Build temporal graphtkg = 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))-# Point-in-time query+# Nodes and edges carry explicit validity windows+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)+)++# Point-in-time snapshotsnapshot = tkg.at(datetime(2021, 6, 15))-# Query evolution+# Diff between two snapshotsquery = TemporalGraphQuery(tkg)snapshot_2020 = query.at_time("2020-01-01")snapshot_2023 = query.at_time("2023-01-01")@@ -83,27 +69,25 @@ print(f"New nodes since 2020: {len(diff.nodes)}")Supports all 13 Allen interval algebra relations (before, after, meets, overlaps, during, starts, finishes, equals, and their inverses). OWL-Time export available.-----## Distance Intelligence (v0.5.0)+Semantic neighborhood exploration for any entity in the graph:+```pythonfrom semantica.kg import DistanceCalculatorcalc = DistanceCalculator(kg)-# Semantic neighborhood of a node+# Semantic neighborhood of a single nodeneighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)-# N×N distance matrix+# N×N pairwise distance matrixmatrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])-# Distance band classification: "near" | "mid" | "far"+# Classify nodes into distance bands: "near" | "mid" | "far"bands = calc.classify_bands(neighborhood)```-----## Graph Analytics### Centrality Analysis@@ -112,18 +96,24 @@ bands = calc.classify_bands(neighborhood)from semantica.kg import CentralityCalculatorcalculator = CentralityCalculator()-centrality = calculator.calculate_degree_centrality(graph)-pagerank_scores = calculator.calculate_pagerank(graph, damping_factor=0.85)++centrality = calculator.calculate_degree_centrality(graph)+pagerank = calculator.calculate_pagerank(graph, damping_factor=0.85)+betweenness = calculator.calculate_betweenness_centrality(graph)+closeness = calculator.calculate_closeness_centrality(graph)+eigenvector = calculator.calculate_eigenvector_centrality(graph)+all_metrics = calculator.calculate_all_centrality(graph)+top_nodes = calculator.get_top_nodes(centrality, top_k=10)```| Method | Algorithm |-|--------|-----------|+| ------ | --------- || `calculate_degree_centrality()` | Degree-based importance |-| `calculate_betweenness_centrality()` | Bridge-based importance |+| `calculate_betweenness_centrality()` | Bridge-based importance (bottleneck nodes) || `calculate_closeness_centrality()` | Distance-based importance || `calculate_eigenvector_centrality()` | Influence-based importance |-| `calculate_pagerank()` | PageRank scores |+| `calculate_pagerank()` | Link-based importance (PageRank) || `calculate_all_centrality()` | All measures at once |### Community Detection@@ -132,9 +122,14 @@ top_nodes = calculator.get_top_nodes(centrality, top_k=10)from semantica.kg import CommunityDetectordetector = CommunityDetector()++# Louvain (default — fast, high quality)communities = detector.detect_communities(graph, algorithm="louvain")-metrics = detector.calculate_community_metrics(graph, communities)++# Leiden (higher quality, slower)leiden_communities = detector.detect_communities_leiden(graph, resolution=1.2)++metrics = detector.calculate_community_metrics(graph, communities)```Algorithms: Louvain, Leiden, Label Propagation, K-Clique Communities.@@ -145,8 +140,9 @@ Algorithms: Louvain, Leiden, Label Propagation, K-Clique Communities.from semantica.kg import PathFinderfinder = PathFinder()-path = finder.dijkstra_shortest_path(graph, "node_a", "node_b")-paths = finder.all_shortest_paths(graph, "source", "target")++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)```@@ -170,28 +166,24 @@ Algorithms: Preferential Attachment, Common Neighbors, Jaccard, Adamic-Adar, Resfrom semantica.kg import NodeEmbedderembedder = NodeEmbedder(method="node2vec", embedding_dimension=128)-embeddings = embedder.compute_embeddings(graph_store, ["Entity"], ["RELATED_TO"])+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 Summary| Category | Algorithms | Use Cases |-|----------|------------|-----------|+| -------- | ---------- | --------- || Node Embeddings | Node2Vec, DeepWalk, Word2Vec | Structural similarity, node representation |-| Similarity Analysis | Cosine, Euclidean, Manhattan, Correlation | Node similarity, recommendation |+| Similarity | Cosine, Euclidean, Manhattan, Correlation | Node matching, 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 |+| Community Detection | Louvain, Leiden, Label Propagation | Social clustering || Connectivity | Components, Bridges, Density | Network robustness |-----## Configuration```yaml@@ -205,16 +197,12 @@ kg:default_validity: infinite```------## See Also-<CardGroup cols={2}><Card title="Graph Store" icon="server" href="graph_store">- Persistence layer (Neo4j, FalkorDB, Apache AGE).+ Persist graphs in Neo4j, FalkorDB, or Apache AGE.</Card><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">- Data source for entities and relationships.+ Source of entities and relationships fed to GraphBuilder.</Card><Card title="Visualization" icon="chart-bar" href="visualization">Visualize knowledge graphs interactively.@@ -224,7 +212,7 @@ kg:</Card></CardGroup>-### Cookbook+### Cookbooks- [Building Knowledge Graphs](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) — fundamentals of KG construction · Beginner- [Your First Knowledge Graph](https://github.com/semantica-agi/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb) — entity extraction to visualization · Beginnerdiff --git a/docs/reference/llms.md b/docs/reference/llms.mdindex 0a0e6a7f..eff097ed 100644--- a/docs/reference/llms.md+++ b/docs/reference/llms.md@@ -4,9 +4,7 @@ description: "Unified interface for Groq, OpenAI, Anthropic, Gemini, Ollama, Deeicon: "microchip"----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.-----+`semantica.llms` provides a single consistent API across 8+ LLM providers. Every provider is a drop-in replacement for the `llm_provider=` parameter in extractors, reasoning engines, and agents.## Providers@@ -60,7 +58,7 @@ llm = Gemini(model="gemini-1.5-pro",api_key=os.getenv("GOOGLE_API_KEY"),)-# Best for: long context, multimodal tasks+# Best for: long context (1M tokens), multimodal tasks``````python Ollama (Local)@@ -83,7 +81,7 @@ llm = DeepSeek(model="deepseek-chat",api_key=os.getenv("DEEPSEEK_API_KEY"),)-# Best for: coding tasks, analysis at low cost+# Best for: coding tasks and analysis at very low cost``````python LiteLLM (100+ models)@@ -107,15 +105,15 @@ llm = HuggingFace(max_new_tokens=512,temperature=0.1,)-# Bring your own model — full local control+# Bring your own model — full local control, no API key```</CodeGroup>-----## Provider Factory+Instantiate any provider by name string — useful when provider is loaded from config:+```pythonfrom semantica.llms import create_provider@@ -129,11 +127,9 @@ llm = create_provider("novita", model="deepseek/deepseek-v3.2", api_key=os.gellm = create_provider("litellm", model="gpt-4o")```-----## Custom / Enterprise Gateways-Any OpenAI-compatible gateway — internal routing layers, Qwen proxies, LLaMA proxies:+Any OpenAI-compatible endpoint — internal routing layers, Qwen proxies, or private LLaMA deployments:```pythonfrom semantica.llms import OpenAI@@ -149,24 +145,24 @@ llm = OpenAI(`base_url` is validated at construction time. Non-HTTP(S) schemes raise `ValueError` to prevent SSRF attacks (fixed in v0.5.0).</Note>-----## Using in Extractors+All extractors accept any provider as `llm_provider=`:+```pythonfrom semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor-ner = NERExtractor(method="llm", llm_provider=llm, max_retries=3)+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)rel = RelationExtractor(method="llm", llm_provider=llm)-trip = TripletExtractor(method="llm", llm_provider=llm)+trip = TripletExtractor(method="llm", llm_provider=llm)```-----## Provider Comparison-| Provider | Speed | Cost | Local | Context | Best for |-|----------|-------|------|-------|---------|----------|+| 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 |@@ -178,13 +174,9 @@ trip = TripletExtractor(method="llm", llm_provider=llm)| HuggingFace | Slow | Free | Yes | Varies | Custom models, BYOM |<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.+ For production extraction pipelines, Groq delivers the best throughput-to-cost ratio. For complex multi-hop reasoning, Claude Opus or GPT-4o provide the highest accuracy.</Tip>------## See Also-<CardGroup cols={2}><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">Use LLMs for NER and relation extraction.diff --git a/docs/reference/mcp_server.md b/docs/reference/mcp_server.mdindex 0bc5423d..929b4fe3 100644--- a/docs/reference/mcp_server.md+++ b/docs/reference/mcp_server.md@@ -6,9 +6,7 @@ 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.-----+Compatible with **Claude Desktop**, **Windsurf**, **Cline**, **Continue**, **VS Code**, **Roo Code**, **Cursor**, and any MCP-aware client.## Installation@@ -18,11 +16,9 @@ pip install semanticaThe MCP server is included in the base install — no extras required.-----## Configuration-Add Semantica to your MCP client's settings:+Add Semantica to your MCP client's settings file:<CodeGroup>@@ -63,16 +59,12 @@ Add Semantica to your MCP client's settings:</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` |-----+| `SEMANTICA_LOG_LEVEL` | `WARNING` | Log verbosity: `DEBUG`, `INFO`, `WARNING` |## Tools@@ -95,10 +87,10 @@ Extract named entities (people, places, organisations, concepts) from text using```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 }+ { "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 }]}```@@ -267,7 +259,7 @@ Run forward-chaining IF/THEN rules over a set of facts to derive new facts.<Accordion title="export_graph" icon="file-export">-Export the current knowledge graph.+Export the current knowledge graph to a serialization format.**Input:**```json@@ -280,27 +272,23 @@ Supported formats: `turtle`, `ttl`, `nt`, `xml`, `json-ld`, `json`.</AccordionGroup>-----## ResourcesThe 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)+# Run the server directly (reads from stdin, writes to stdout)semantica-mcp-# Or with Python+# Or via Python modulepython -m semantica.mcp_server```@@ -310,10 +298,6 @@ Send a JSON-RPC `initialize` message to confirm it's working: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.diff --git a/docs/reference/normalize.md b/docs/reference/normalize.mdindex fb87abdf..98f87ca2 100644--- a/docs/reference/normalize.md+++ b/docs/reference/normalize.md@@ -4,40 +4,25 @@ description: "Text cleaning, entity canonicalization, date normalization, numbericon: "broom"----> Clean, standardize, and prepare text and data for semantic processing.+`semantica.normalize` standardizes raw data before extraction and graph construction — fixing encodings, canonicalizing entity names, normalizing dates, and detecting languages. All normalizers expose both convenience functions and stateful class instances.------## Overview+## What You Get-The **Normalize Module** standardizes raw data before extraction and graph construction — fixing encodings, canonicalizing entity names, normalizing dates, and detecting languages. All normalizers expose both convenience functions and stateful class instances.+- **`TextNormalizer`** — Unicode, whitespace, HTML stripping, smart-quote/dash replacement+- **`EntityNormalizer`** — alias resolution, disambiguation, name variant handling+- **`DateNormalizer`** — ISO 8601 output, timezone conversion, relative date parsing+- **`NumberNormalizer`** — currency, unit conversion, scientific notation, percentages+- **`DataCleaner`** — duplicate detection, schema validation, missing value handling+- **`LanguageDetector`** — 50+ language detection with confidence scoring+- **`EncodingHandler`** — UTF-8 conversion, BOM removal, encoding detection-<CardGroup cols={2}>- <Card title="TextNormalizer" icon="text-size">- Unicode, whitespace, HTML stripping, smart-quote/dash replacement.- </Card>- <Card title="EntityNormalizer" icon="user-check">- Alias resolution, disambiguation, name variant handling.- </Card>- <Card title="DateNormalizer" icon="calendar">- ISO 8601 output, timezone conversion, relative date parsing.- </Card>- <Card title="NumberNormalizer" icon="hashtag">- Currency, unit conversion, scientific notation.- </Card>- <Card title="DataCleaner" icon="broom">- Duplicate detection, schema validation, missing value handling.- </Card>- <Card title="LanguageDetector" icon="globe">- 50+ language detection with confidence scoring.- </Card>-</CardGroup>-----+<Note>+ **v0.5.0 fix:** Encoding repair now handles cp1252/latin-1 characters that previously caused crashes on Windows when processing documents with non-ASCII content.+</Note>## Convenience Functions-The quickest way to normalize — dispatch via function with a `method` parameter:+The fastest path — dispatch via function with a `method` parameter:```pythonfrom semantica.normalize import (@@ -61,8 +46,6 @@ lang = detect_language("Bonjour le monde")# → {"language": "fr", "confidence": 0.98}```-----## TextNormalizer```python@@ -75,122 +58,79 @@ normalized = normalizer.normalize_text(lowercase=False,remove_punctuation=False,remove_extra_whitespace=True,- strip_html=True, # remove HTML tags- normalize_unicode=True, # NFC normalization+ strip_html=True, # remove HTML tags+ normalize_unicode=True, # NFC normalization)```-<AccordionGroup>--<Accordion title="UnicodeNormalizer — NFC/NFD/NFKC/NFKD forms" icon="font">--```python-from semantica.normalize import UnicodeNormalizer--normalizer = UnicodeNormalizer(form="NFC")-text = normalizer.normalize("café") # NFC → canonical composition-```--</Accordion>--<Accordion title="WhitespaceNormalizer — tabs, line breaks, extra spaces" icon="align-left">+Sub-normalizers for fine-grained control:```python-from semantica.normalize import WhitespaceNormalizer+from semantica.normalize import UnicodeNormalizer, WhitespaceNormalizer, SpecialCharacterProcessor-normalizer = WhitespaceNormalizer()-text = normalizer.normalize("Hello World\t\n") # → "Hello World"-```+# Unicode normalization forms: NFC | NFD | NFKC | NFKD+unicode_norm = UnicodeNormalizer(form="NFC")+text = unicode_norm.normalize("café")-</Accordion>--<Accordion title="SpecialCharacterProcessor — smart quotes, dashes, ellipsis" icon="quote-right">--```python-from semantica.normalize import SpecialCharacterProcessor+# Collapse tabs, line breaks, and extra spaces+ws_norm = WhitespaceNormalizer()+text = ws_norm.normalize("Hello World\t\n") # → "Hello World"+# Replace smart quotes, em-dashes, and ellipsis charactersprocessor = SpecialCharacterProcessor()text = processor.process("‘Hello’") # '' → ''```-</Accordion>--</AccordionGroup>--<Note>- **v0.5.0 fix:** Encoding repair now handles cp1252/latin-1 characters that previously caused crashes on Windows when processing documents with non-ASCII content.-</Note>------## EntityNormalizer+Canonicalize entity names — handles corporate suffixes, punctuation, case, and honorifics:+```pythonfrom semantica.normalize import EntityNormalizernormalizer = EntityNormalizer()-# Normalize company names — handles suffixes, punctuation, case+# Company name normalizationcompanies = ["Apple Computer, Inc.", "Apple Inc", "APPLE INC."]normalized = [normalizer.normalize_entity(c) for c in companies]# All → "Apple Inc."-# Person names+# Person name normalizationname = normalizer.normalize_entity("JOBS, STEVE", entity_type="Person")# → "Steve Jobs"```-<AccordionGroup>--<Accordion title="AliasResolver — dictionary-based alias mapping" icon="arrow-right-arrow-left">+Sub-normalizers for entity-specific use cases:```python-from semantica.normalize import AliasResolver+from semantica.normalize import AliasResolver, EntityDisambiguator, NameVariantHandler+# Dictionary-based alias expansionresolver = AliasResolver(aliases={"ML": "Machine Learning","AI": "Artificial Intelligence","DL": "Deep Learning",})-resolved = resolver.resolve("ML and DL are subsets of AI")# → "Machine Learning and Deep Learning are subsets of Artificial Intelligence"-```--</Accordion>--<Accordion title="EntityDisambiguator — context-aware disambiguation" icon="arrows-split-up-and-left">--```python-from semantica.normalize import EntityDisambiguator+# Context-aware disambiguationdisambiguator = EntityDisambiguator()result = disambiguator.disambiguate("Apple", context="Steve Jobs founded Apple in Cupertino")# → {"entity": "Apple Inc.", "type": "Organization", "confidence": 0.96}-```--</Accordion>--<Accordion title="NameVariantHandler — honorifics, titles, cultural variants" icon="id-card">--```python-from semantica.normalize import NameVariantHandler+# Honorifics, titles, and cultural name variantshandler = NameVariantHandler()canonical = handler.normalize("Dr. JOHN P. SMITH Jr.")# → "John P. Smith"```-</Accordion>--</AccordionGroup>------## DateNormalizer+Parse and normalize dates from any format to ISO 8601:+```pythonfrom semantica.normalize import DateNormalizer@@ -200,59 +140,40 @@ dates = ["January 1st, 2020","01/01/2020","2020-01-01T00:00:00Z",- "yesterday", # relative dates supported+ "yesterday","3 weeks ago",]normalized = [normalizer.normalize_date(d) for d in dates]# All → ISO 8601 strings-# With timezone conversion to UTC+# With automatic UTC conversionnormalizer_utc = DateNormalizer(target_timezone="UTC")utc_date = normalizer_utc.normalize_date("2024-01-01 09:00 EST")```-<AccordionGroup>--<Accordion title="TimeZoneNormalizer" icon="clock">+Sub-normalizers for advanced date handling:```python-from semantica.normalize import TimeZoneNormalizer--tz_normalizer = TimeZoneNormalizer(target_tz="UTC")-utc_dt = tz_normalizer.normalize("2024-01-01 09:00", source_tz="America/New_York")-```--</Accordion>+from semantica.normalize import (+ TimeZoneNormalizer, RelativeDateProcessor, TemporalExpressionParser+)-<Accordion title="RelativeDateProcessor — 'yesterday', '3 weeks ago'" icon="calendar-days">+# Timezone conversion+tz_norm = TimeZoneNormalizer(target_tz="UTC")+utc_dt = tz_norm.normalize("2024-01-01 09:00", source_tz="America/New_York")-```python-from semantica.normalize import RelativeDateProcessor+# Relative date resolutionfrom datetime import datetime-processor = RelativeDateProcessor(reference_date=datetime(2025, 1, 15))result = processor.process("3 days ago")# → datetime(2025, 1, 12)-```--</Accordion>--<Accordion title="TemporalExpressionParser — date ranges and complex expressions" icon="calendar-range">--```python-from semantica.normalize import TemporalExpressionParser+# Date range parsingparser = TemporalExpressionParser()result = parser.parse("from January 2020 to March 2021")# → {"start": "2020-01-01", "end": "2021-03-31", "type": "range"}```-</Accordion>--</AccordionGroup>------## NumberNormalizer```python@@ -260,63 +181,43 @@ from semantica.normalize import NumberNormalizernormalizer = NumberNormalizer()-# Currency-normalizer.normalize_number("$1,234.56") # → 1234.56-normalizer.normalize_number("€42K") # → 42000.0-normalizer.normalize_number("$1.2B") # → 1200000000.0--# Scientific notation-normalizer.normalize_number("3.14e-2") # → 0.0314--# Percentages-normalizer.normalize_number("42%") # → 0.42+normalizer.normalize_number("$1,234.56") # → 1234.56+normalizer.normalize_number("€42K") # → 42000.0+normalizer.normalize_number("$1.2B") # → 1200000000.0+normalizer.normalize_number("3.14e-2") # → 0.0314+normalizer.normalize_number("42%") # → 0.42```-<AccordionGroup>--<Accordion title="UnitConverter — length, weight, volume, temperature" icon="ruler">+Unit and currency conversion:```python-from semantica.normalize import UnitConverter+from semantica.normalize import UnitConverter, CurrencyNormalizerconverter = UnitConverter()result = converter.convert(100, from_unit="km/h", to_unit="m/s")# → 27.78-# All supported categories: length, weight, volume, temperature, speed, area+# Supported categories: length, weight, volume, temperature, speed, areacategories = converter.list_categories()-```--</Accordion>--<Accordion title="CurrencyNormalizer — symbol/code resolution" icon="dollar-sign">-```python-from semantica.normalize import CurrencyNormalizer--normalizer = CurrencyNormalizer()-result = normalizer.normalize("$42.50")+currency_norm = CurrencyNormalizer()+result = currency_norm.normalize("$42.50")# → {"amount": 42.50, "currency": "USD", "raw": "$42.50"}```-</Accordion>--</AccordionGroup>------## DataCleaner```python-from semantica.normalize import DataCleaner, DataValidator, DuplicateDetector+from semantica.normalize import DataCleaner, DataValidatorcleaner = DataCleaner()-# Remove duplicates from a dataset+# Remove near-duplicate recordsdeduped = cleaner.remove_duplicates(records, similarity_threshold=0.9)# Fill missing values-filled = cleaner.fill_missing(records, strategy="mean") # or "median", "mode", "remove"+filled = cleaner.fill_missing(records, strategy="mean")+# strategy options: "mean" | "median" | "mode" | "remove"# Validate schemavalidator = DataValidator()@@ -324,8 +225,6 @@ result = validator.validate(records, schema={"name": str, "age": int})print(result.valid_count, result.errors)```-----## LanguageDetector```python@@ -333,20 +232,17 @@ from semantica.normalize import LanguageDetectordetector = LanguageDetector()-# Single textlang = detector.detect("Bonjour le monde")# → {"language": "fr", "confidence": 0.98}-# Top N languages+# Top N languages for mixed-language textlangs = detector.detect_top_n("This might be mixed", n=3)# → [{"language": "en", "probability": 0.85}, ...]-# Batch+# Batch detectionresults = detector.detect_batch(["Hello", "Hola", "Bonjour"])```-----## EncodingHandler```python@@ -354,31 +250,16 @@ from semantica.normalize import EncodingHandlerhandler = EncodingHandler()-# Detect encodingencoding = handler.detect_encoding(raw_bytes)# → {"encoding": "windows-1252", "confidence": 0.73}-# Convert to UTF-8utf8_text = handler.to_utf8(raw_bytes)--# Remove BOM-clean = handler.remove_bom(text_with_bom)+clean = handler.remove_bom(text_with_bom)```------## Batch Processing--All normalizers support batch input:--```python-from semantica.normalize import normalize_text--texts = ["Text 1...", "Text 2...", "Text 3..."]-normalized = [normalize_text(t) for t in texts]-```+## Pipeline Integration-For large datasets, use the pipeline:+For large datasets, use the pipeline instead of per-item normalization:```pythonfrom semantica.pipeline import Pipeline@@ -389,21 +270,17 @@ pipeline.add_step("normalize", TextNormalizer())result = pipeline.run(documents)```------## See Also-<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.+ Chunk normalized text for embedding.</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.+ Include normalization as a pipeline step.</Card></CardGroup>diff --git a/docs/reference/ontology.md b/docs/reference/ontology.mdindex 7f8d8991..d9c43b7b 100644--- a/docs/reference/ontology.md+++ b/docs/reference/ontology.md@@ -4,40 +4,42 @@ description: "Automated ontology generation, SHACL validation, SKOS vocabulariesicon: "sitemap"----> Automated ontology generation, validation, and management system.+`semantica.ontology` provides the full lifecycle for knowledge graph schemas — from auto-generation and SHACL validation to visual editing in the Ontology Hub (v0.5.0). Use it for schema design, data modeling, semantic web interoperability, and SHACL-based data quality validation.------## Overview+## What You Get-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).--<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>-----+- **`OntologyManager`** — define classes, properties, relationships, and constraints+- **`OntologyGenerator`** — auto-generate ontologies from existing knowledge graph data (6-stage pipeline)+- **`SHACLGenerator`** / **`SHACLValidator`** — generate and validate SHACL shapes+- **`SKOSVocabulary`** — controlled vocabulary and taxonomy management+- **`OntologyAligner`** — align and merge ontologies across schemas+- **`OntologyDiff`** / **`OntologyMigrator`** — diff and migrate ontology versions+- **`OWLExporter`** — export to Turtle, RDF/XML, JSON-LD+- **Ontology Hub** — visual browser UI for the full ontology lifecycle (v0.5.0)## OntologyManager+Define and validate a schema for your knowledge graph:+```pythonfrom semantica.ontology import OntologyManagerontology = OntologyManager()-ontology.add_class("Person", properties=["name", "birth_date"])+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")+# Validate a graph against the ontologyis_valid = ontology.validate_graph(kg)++# Export as OWL Turtleowl_ttl = ontology.export_owl(format="turtle")```-----## Auto-Generation (6-Stage Pipeline)-Generate an ontology automatically from your knowledge graph data.+Generate an ontology automatically from your knowledge graph data:```pythonfrom semantica.ontology import OntologyGenerator@@ -46,7 +48,7 @@ generator = OntologyGenerator()ontology = generator.generate_from_graph(kg)```-The pipeline runs through these stages:+The pipeline runs through these stages in order:1. **Semantic Network Parsing** — extract concepts and patterns from entity/relationship data2. **YAML-to-Definition** — transform patterns into intermediate class definitions@@ -55,116 +57,114 @@ The pipeline runs through these stages:5. **TTL Generation** — serialize to Turtle format using `rdflib`6. **Quality Evaluation** — assess coverage, completeness, and granularity metrics-----## SHACL Validation+Generate SHACL shapes from an ontology and validate any graph against them:+```pythonfrom semantica.ontology import SHACLGenerator, SHACLValidator-# Generate SHACL shapes from an ontology+# Generate shapesgenerator = SHACLGenerator()-shapes = generator.generate(ontology)+shapes = generator.generate(ontology)shapes_ttl = shapes.serialize(format="turtle")-# Validate a graph against shapes+# Validate a graphvalidator = SHACLValidator()-report = validator.validate(kg, shapes=shapes)+report = validator.validate(kg, shapes=shapes)if not report.conforms:for violation in report.violations:print(f"Violation: {violation.message} on {violation.node}")+ print(f" Path: {violation.path}")+ print(f" Severity: {violation.severity}")```-----## SKOS Vocabularies+Build controlled vocabularies and taxonomies using the W3C SKOS standard:+```pythonfrom semantica.ontology import SKOSVocabularyvocab = SKOSVocabulary()-vocab.add_concept("Machine Learning", broader="Artificial Intelligence")-vocab.add_concept("Deep Learning", broader="Machine Learning")+vocab.add_concept("Machine Learning", broader="Artificial Intelligence")+vocab.add_concept("Deep Learning", broader="Machine Learning")+vocab.add_concept("Computer Vision", broader="Deep Learning")vocab.add_alt_label("ML", for_concept="Machine Learning")skos_ttl = vocab.export(format="turtle")```-----## Ontology Alignment+Map concepts across two ontologies and merge them:+```pythonfrom semantica.ontology import OntologyAligner-aligner = OntologyAligner()+aligner = OntologyAligner()alignment = aligner.align(source_ontology, target_ontology)for mapping in alignment.mappings:- print(f"{mapping.source} → {mapping.target} (confidence: {mapping.confidence:.2f})")+ print(f"{mapping.source} → {mapping.target} (confidence: {mapping.confidence:.2f})")+# Merge into a unified ontologymerged = aligner.merge(source_ontology, target_ontology, alignment)```----+## Diff and Migration-## Diff & Migration+Compare ontology versions and generate migration scripts for graph data:```pythonfrom semantica.ontology import OntologyDiff, OntologyMigrator-diff = OntologyDiff()+diff = OntologyDiff()changes = diff.compare(ontology_v1, ontology_v2)for change in changes:print(f"{change.type}: {change.element} — {change.description}")-migrator = OntologyMigrator()+# Generate and apply a migration script+migrator = OntologyMigrator()migration_script = migrator.generate_migration(changes)migrator.apply(kg, migration_script)```------## OWL/RDF Export+## OWL / RDF Export```pythonfrom semantica.ontology import OWLExporterexporter = OWLExporter()-exporter.export(ontology, path="ontology.ttl", format="turtle")-exporter.export(ontology, path="ontology.xml", format="xml")+exporter.export(ontology, path="ontology.ttl", format="turtle")+exporter.export(ontology, path="ontology.owl", format="xml")exporter.export(ontology, path="ontology.json", format="json-ld")```-----## Ontology Hub (v0.5.0)-The Ontology Hub is a visual browser UI for the full ontology lifecycle, available via `semantica.explorer`.+A visual browser UI for the full ontology lifecycle, served by `semantica.explorer`:```bash-pip install semantica[explorer]+pip install "semantica[explorer]"``````pythonfrom semantica.explorer import start_explorerstart_explorer(graph=kg, port=8080)-# Opens at http://localhost:8080 — navigate to the Ontology Hub tab+# Navigate to http://localhost:8080 → Ontology Hub tab```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+- **Visual editor** — create and edit classes, properties, and relationships in the browser+- **SHACL Studio** — author and validate SHACL shapes with live feedback+- **Alignment authoring** — map concepts across ontologies with drag-and-drop+- **Health dashboard** — coverage, completeness, and constraint violation metrics+- **Version control** — snapshot, diff, and restore ontology versions<CardGroup cols={2}><Card title="Reasoning" icon="microchip" href="reasoning">diff --git a/docs/reference/parse.md b/docs/reference/parse.mdindex 1611aab0..79a124df 100644--- a/docs/reference/parse.md+++ b/docs/reference/parse.md@@ -4,13 +4,17 @@ description: "Document parsing and text extraction — DocumentParser for standaicon: "file-lines"----> Universal data parser supporting documents, web content, structured data, emails, code, and media.+`semantica.parse` extracts structured text, layout, tables, and metadata from unstructured documents. `DocumentParser` handles clean machine-readable files; `DoclingParser` handles complex layouts, scanned PDFs, and multi-column documents.----+## What You Get++- **`DocumentParser`** — standard parser for PDF, DOCX, HTML, TXT, JSON, CSV, PPTX, XLSX+- **`DoclingParser`** — advanced parser for complex layouts, merged-cell tables, multi-column PDFs, and OCR+- **`ParsedDocument`** — structured output with `text`, `sections`, `tables`, and `metadata`## DocumentParser-Standard parser for clean, machine-readable documents.+Standard parser for clean, machine-readable documents:```pythonfrom semantica.parse import DocumentParser@@ -19,17 +23,15 @@ parser = DocumentParser()parsed = parser.parse("data/report.pdf")print(parsed.text) # full clean text-print(parsed.metadata) # title, author, date, page_count, etc.-print(parsed.sections) # document structure+print(parsed.metadata) # title, author, date, page_count, language, etc.+print(parsed.sections) # document structure as a list of Section objects```Supported formats: PDF, DOCX, HTML, TXT, JSON, CSV, PPTX, XLSX.-----## DoclingParser-Advanced parser for complex layouts using the Docling backend.+Advanced parser using the Docling backend — handles layouts that `DocumentParser` cannot:```bashpip install "semantica[docling]"@@ -39,95 +41,97 @@ pip install "semantica[docling]"from semantica.parse import DoclingParserparser = DoclingParser(- extract_tables=True, # structured table extraction- extract_images=True, # image OCR- output_format="markdown", # "markdown" | "html" | "json"+ extract_tables=True, # structured table extraction with cell type detection+ extract_images=True, # extract image regions for downstream OCR+ output_format="markdown", # "markdown" | "html" | "json")parsed = parser.parse("data/annual_report.pdf")print(parsed.text) # full clean text-print(parsed.tables) # structured table data-print(parsed.sections) # document structure+print(parsed.tables) # structured TableData objects with headers and rows+print(parsed.sections) # document structure with heading hierarchy```-Use DoclingParser for: multi-column PDFs, tables with merged cells, PPTX slides, XLSX spreadsheets, images with OCR, and scanned documents.+Use `DoclingParser` for:----+- Multi-column PDF layouts+- Tables with merged cells or complex headers+- PPTX slides with embedded charts+- XLSX spreadsheets with formulas+- Scanned documents with OCR+- Academic papers and technical reports## OCR Support```pythonparser = DoclingParser(ocr=True,- ocr_language=["en"],+ ocr_language=["en"], # ISO 639-1 codes; list for multi-language documentsextract_tables=True,)parsed = parser.parse("data/scanned_contract.pdf")```-----## Parsed Document Object+Both parsers return a `ParsedDocument` with the same structure:+```python@dataclassclass ParsedDocument:- text: str- sections: List[Section]- tables: List[TableData]- metadata: DocumentMetadata- source_id: str+ text: str # full extracted text+ sections: List[Section] # heading-based document structure+ tables: List[TableData] # structured table data (DoclingParser only)+ metadata: DocumentMetadata # title, author, dates, page count+ source_id: str # links back to the original DataSource@dataclassclass DocumentMetadata:- title: Optional[str]- author: Optional[str]+ 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" | ...+ page_count: int+ language: Optional[str] # ISO 639-1 code+ has_tables: bool+ has_images: bool+ word_count: int+ format: str # "pdf" | "docx" | "pptx" | ...```-----## Integration with FileIngestor+The most common pattern — ingest a directory then parse each source:+```pythonfrom semantica.ingest import FileIngestorfrom semantica.parse import DoclingParseringestor = FileIngestor()-parser = DoclingParser(extract_tables=True)+parser = DoclingParser(extract_tables=True)sources = ingestor.ingest("data/reports/")for source in sources:parsed = parser.parse(source)+ # → parsed.text, parsed.tables, parsed.sections```<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.+ Docling is an optional dependency. If `docling` is not installed, `DoclingParser` raises an `ImportError` with installation instructions. `DocumentParser` is always available and requires no extras.</Note>------## See Also-<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.+ Chunk parsed text for embedding and extraction.</Card><Card title="Docling Integration" icon="file-pdf" href="../integrations/docling">- Full Docling integration guide.+ Full Docling integration setup guide.</Card><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">- Extract entities from parsed text.+ Extract entities and relations from parsed text.</Card></CardGroup>diff --git a/docs/reference/pipeline.md b/docs/reference/pipeline.mdindex 3c15db51..be9c7d9b 100644--- a/docs/reference/pipeline.md+++ b/docs/reference/pipeline.md@@ -4,15 +4,15 @@ description: "Pipeline DSL with parallel workers, retry policies, failure handliicon: "gear"----> Robust orchestration engine for building and executing complex data processing workflows.+`semantica.pipeline` lets you chain Semantica components into reproducible, fault-tolerant workflows with parallel execution and configurable error handling. Pipelines are serializable — save them to YAML and reload in any environment.------## Overview+## What You Get-The **Pipeline Module** lets you chain Semantica components into reproducible, fault-tolerant workflows with parallel execution and configurable error handling.-----+- **`Pipeline`** — chain steps with parallel workers, retry policies, and failure handlers+- **`PipelineBuilder`** — fluent DSL for building pipelines with a readable chain syntax+- **`RetryPolicy`** — fixed, linear, and exponential backoff with configurable max retries+- **`FailureHandler`** — skip, stop, or retry failed documents without halting the pipeline+- **Progress tracking** — console (tqdm), WebSocket streaming, or file logging## Basic Pipeline@@ -33,12 +33,12 @@ result = pipeline.run("data/")kg = result.output```-----## Parallel Processing+Process documents concurrently across multiple workers:+```python-pipeline = Pipeline(workers=4) # run steps in parallel across documents+pipeline = Pipeline(workers=4)pipeline.add_step("ingest", FileIngestor())pipeline.add_step("parse", DocumentParser())@@ -48,9 +48,9 @@ pipeline.add_step("build", GraphBuilder())result = pipeline.run("data/")```----+## Retry and Error Handling-## Retry & Error Handling+Configure retry behavior and failure strategy independently:```pythonfrom semantica.pipeline import Pipeline, RetryPolicy, FailureHandler@@ -58,37 +58,36 @@ from semantica.pipeline import Pipeline, RetryPolicy, FailureHandlerretry = RetryPolicy(max_retries=3,backoff="exponential", # "fixed" | "linear" | "exponential"- initial_delay=1.0+ initial_delay=1.0 # seconds before first retry)handler = FailureHandler(strategy="skip", # "skip" | "stop" | "retry"- log_failures=True+ log_failures=True # write failed documents to error log)pipeline = Pipeline(retry_policy=retry, failure_handler=handler)```-----## Progress Tracking```python-# Print progress to console+# Console progress bar (tqdm)result = pipeline.run("data/", show_progress=True)-# WebSocket progress (via Knowledge Explorer)+# WebSocket progress — stream to Knowledge Explorerresult = pipeline.run("data/", websocket_port=8080)+# Inspect resultsprint(f"Processed: {result.processed_count}")-print(f"Failed: {result.failed_count}")-print(f"Duration: {result.duration_seconds:.1f}s")+print(f"Failed: {result.failed_count}")+print(f"Duration: {result.duration_seconds:.1f}s")```-----## Pipeline DSL+The `PipelineBuilder` provides a fluent chain syntax that reads as a data flow:+```pythonfrom semantica.pipeline import PipelineBuilder@@ -108,22 +107,31 @@ pipeline = (result = pipeline.run("data/")```----+## Save and Load Pipelines-## Saving & Loading Pipelines+Serialize a pipeline to YAML for reproducible runs across environments:```python-# Save pipeline definition+# Save pipeline configurationpipeline.save("pipeline_config.yaml")-# Load and run+# Load and run on any machinepipeline = Pipeline.load("pipeline_config.yaml")result = pipeline.run("data/")```----+## Pipeline Result-## See Also+```python+@dataclass+class PipelineResult:+ output: Any # final step output (e.g., a KnowledgeGraph)+ processed_count: int # documents successfully processed+ failed_count: int # documents that failed after retries+ duration_seconds: float # total wall-clock time+ step_metrics: Dict # per-step timing and counts+ errors: List # list of FailedDocument records+```<CardGroup cols={2}><Card title="Ingest" icon="database" href="ingest">diff --git a/docs/reference/provenance.md b/docs/reference/provenance.mdindex bd431d3c..84513589 100644--- a/docs/reference/provenance.md+++ b/docs/reference/provenance.md@@ -1,18 +1,18 @@---title: "Provenance Module"-description: "W3C PROV-O compliant lineage tracking, source attribution, and audit trails across all 17 modules."+description: "W3C PROV-O compliant lineage tracking, source attribution, and audit trails across all modules."icon: "link"----> W3C PROV-O compliant provenance tracking for high-stakes domains requiring complete traceability.+`semantica.provenance` 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.------## Overview+## What You Get-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.-----+- **`ProvenanceManager`** — track entities, relationships, and activities with source attribution+- **`ActivityTracker`** — record pipeline activities and which entities they produced or consumed+- **Lineage graph** — full upstream lineage from any entity back to its source document+- **W3C PROV-O export** — serialize lineage as Turtle RDF for compliance reporting+- **`GraphBuilderWithProvenance`** — drop-in replacement that auto-tracks every node and edge## ProvenanceManager@@ -21,7 +21,7 @@ from semantica.provenance import ProvenanceManagermanager = ProvenanceManager()-# Track an entity+# Track an extracted entitymanager.track_entity(entity_id="apple_inc",source="annual_report_2023.pdf",@@ -30,7 +30,7 @@ manager.track_entity(confidence=0.98)-# Track a relationship+# Track an extracted relationshipmanager.track_relationship(rel_id="steve_jobs_founded_apple",source="annual_report_2023.pdf",@@ -38,19 +38,20 @@ manager.track_relationship(confidence=0.92)-# Get full lineage+# Retrieve full lineage for any entitylineage = manager.get_lineage("apple_inc")-print(f"Source: {lineage.source}")-print(f"Extracted: {lineage.extracted_at}")-print(f"Method: {lineage.extraction_method}")+print(f"Source: {lineage.source}")+print(f"Extracted: {lineage.extracted_at}")+print(f"Method: {lineage.extraction_method}")+print(f"Confidence: {lineage.confidence}")```-----## Activity Tracking+Record pipeline activities — what was consumed and what was produced:+```python-# Track a pipeline activity+# Start and end an activityactivity_id = manager.start_activity(activity_type="ner_extraction",used=["annual_report_2023.pdf"],@@ -59,63 +60,80 @@ activity_id = manager.start_activity(manager.end_activity(activity_id)-# Query activities+# Query activities for an entityactivities = manager.get_activities(entity_id="apple_inc")+for activity in activities:+ print(f"{activity.type} at {activity.started_at}")+ print(f" Used: {activity.used}")+ print(f" Generated: {activity.generated}")```-----## Lineage Graph+Retrieve a full directed lineage graph from any entity back to its source:+```python-# Full lineage from source to current statelineage_graph = manager.get_lineage_graph("apple_inc")for node in lineage_graph.nodes:print(f"{node.id}: {node.type} — {node.timestamp}")-```----+for edge in lineage_graph.edges:+ print(f"{edge.source} → {edge.target} ({edge.relation})")+```## W3C PROV-O Export+Export lineage as W3C PROV-O Turtle for compliance reporting:+```python-# Export provenance as W3C PROV-O Turtle+# Single entity lineageprov_ttl = manager.export_prov_o("apple_inc", format="turtle")-# Export full provenance graph+# Full provenance graph for all tracked entitiesmanager.export_all(path="provenance.ttl", format="turtle")-```----+# Compliance-ready JSON-LD export+manager.export_all(path="provenance.jsonld", format="json-ld")+```-## Integration with Other Modules+## Integration with GraphBuilder-Provenance is automatically tracked when using `GraphBuilderWithProvenance`:+`GraphBuilderWithProvenance` automatically records provenance for every node and edge constructed:```pythonfrom semantica.kg import GraphBuilderWithProvenancebuilder = GraphBuilderWithProvenance(provenance=True)-result = builder.build_single_source(graph_data)+result = builder.build_single_source(graph_data)-# The builder records what was used to produce each node/edge-lineage = result.provenance_manager.get_lineage("entity_id")+# Each node and edge has a source_id linking back to the originating document+lineage = result.provenance_manager.get_lineage("apple_inc")+print(f"Source document: {lineage.source}")+print(f"Extracted by: {lineage.extraction_method}")```----+## Compliance Standards++Provenance tracking in Semantica is designed to satisfy:-## See Also+| Standard | Requirement Met |+| -------- | --------------- |+| **W3C PROV-O** | Full PROV-O compliant serialization (Turtle and JSON-LD) |+| **HIPAA** | Complete audit trail linking clinical facts to source documents |+| **SOX** | Immutable change history with timestamps and actor IDs |+| **GDPR** | Data lineage supporting right-to-erasure impact analysis |+| **FDA 21 CFR Part 11** | Electronic records with origination timestamp and extraction method |<CardGroup cols={2}><Card title="Change Management" icon="clock-rotate-left" href="change_management">- Version control and audit trails.+ Version control and snapshot audit trails.</Card><Card title="Ingest" icon="database" href="ingest">- Provenance begins at ingestion.+ Provenance begins at the ingestion stage.</Card><Card title="Export" icon="file-export" href="export">- Include provenance in exports.+ Include provenance metadata in RDF exports.</Card><Card title="Context" icon="brain" href="context">Decision provenance via AgentContext.diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.mdindex a0515173..9012abbb 100644--- a/docs/reference/reasoning.md+++ b/docs/reference/reasoning.md@@ -4,36 +4,17 @@ description: "Forward chaining, Rete, deductive, abductive, SPARQL, Datalog, andicon: "microchip"----> Logical inference engine supporting rule-based, SPARQL, Rete, Datalog, and temporal reasoning — all with explainable paths.+`semantica.reasoning` derives new knowledge from existing facts using logical rules. Every engine produces **explainable inference paths** — traceable chains of rules and facts, not black-box conclusions.------## Overview+## What You Get-The **Reasoning Module** derives new knowledge from existing facts using logical rules. Every engine produces **explainable inference paths** — not black-box conclusions.--<CardGroup cols={2}>- <Card title="Reasoner" icon="brain">- Main facade — forward chaining with IF/THEN rules and variable substitution.- </Card>- <Card title="ReteEngine" icon="bolt">- High-performance pattern matching for large rule sets via the Rete algorithm.- </Card>- <Card title="SPARQLReasoner" icon="database">- Query expansion and property chain inference over RDF graphs.- </Card>- <Card title="DatalogReasoner" icon="code">- Recursive Horn clause rules with bottom-up fixpoint semantics (v0.4.0).- </Card>- <Card title="TemporalReasoningEngine" icon="clock">- All 13 Allen interval algebra relations for time-aware inference.- </Card>- <Card title="ExplanationGenerator" icon="list-check">- Structured explanation paths — how each conclusion was derived.- </Card>-</CardGroup>-----+- **`Reasoner`** — main facade for IF/THEN forward-chaining with variable substitution+- **`GraphReasoner`** — inference over full knowledge graph structure (transitivity, symmetry, inverses)+- **`ReteEngine`** — high-performance pattern matching via the Rete algorithm for large rule sets+- **`SPARQLReasoner`** — query expansion and property chain inference over RDF graphs+- **`DatalogReasoner`** — recursive Horn clause rules with guaranteed fixpoint termination (v0.4.0)+- **`TemporalReasoningEngine`** — all 13 Allen interval algebra relations for time-aware inference+- **`ExplanationGenerator`** — structured explanation paths for every derived conclusion## Reasoner (Main Facade)@@ -44,11 +25,11 @@ from semantica.reasoning import Reasoner, Rule, Fact, RuleTypereasoner = Reasoner()-# Add facts+# Add base factsreasoner.add_fact(Fact(subject="John", predicate="is_a", obj="Manager"))reasoner.add_fact(Fact(subject="John", predicate="is_a", obj="Employee"))-# Add rules+# Add an IF/THEN rulereasoner.add_rule(Rule(rule_type=RuleType.FORWARD_CHAIN,conditions=[@@ -64,7 +45,20 @@ for inference in result.derived_facts:print(f" Derived via: {inference.explanation}")```----+### Built-In Rule Templates++```python+engine = Reasoner()++# Transitive closure: A→B, B→C ⟹ A→C+engine.apply_transitivity("located_in")++# Symmetry: A knows B ⟹ B knows A+engine.apply_symmetry("knows")++# Inverse: A parent_of B ⟹ B child_of A+engine.apply_inverse("parent_of", "child_of")+```## GraphReasoner@@ -75,7 +69,7 @@ from semantica.reasoning import GraphReasonergraph_reasoner = GraphReasoner(kg)-# Infer transitive closure+# Define a transitive ancestor rulegraph_reasoner.add_rule({"if": [{"subject": "?a", "predicate": "parent_of", "object": "?b"},@@ -89,26 +83,24 @@ for inf in inferences:print(f"{inf['subject']} {inf['predicate']} {inf['object']}")```-----## ReteEngine-High-performance pattern matching using the Rete algorithm — far faster than naive forward chaining for large rule sets because it caches partial matches:+High-performance pattern matching using the Rete algorithm — far faster than naive forward chaining for large rule sets because it caches partial matches across iterations:```python-from semantica.reasoning import ReteEngine, ReteNode, AlphaNode, BetaNode+from semantica.reasoning import ReteEngineengine = ReteEngine()engine.load_rules("rules/domain_rules.json")results = engine.run(kg)-# Inspect the network-root: ReteNode = engine.get_root()+# Inspect the Rete network+root = engine.get_root()alpha_nodes = engine.get_alpha_nodes() # single-condition filtersbeta_nodes = engine.get_beta_nodes() # join nodes```-Rule format for Rete:+Rule format (JSON):```json{@@ -124,18 +116,16 @@ Rule format for Rete:}```-----## SPARQLReasoner-Query-based inference over RDF graphs:+Query-based inference over RDF graphs with property chain support:```python-from semantica.reasoning import SPARQLReasoner, SPARQLQueryResult+from semantica.reasoning import SPARQLReasonerreasoner = SPARQLReasoner(graph=rdf_graph)-result: SPARQLQueryResult = reasoner.query("""+result = reasoner.query("""PREFIX ex: <http://example.org/>SELECT ?person ?company WHERE {?person ex:founded ?company .@@ -145,32 +135,26 @@ result: SPARQLQueryResult = reasoner.query("""for row in result.bindings:print(row["person"], row["company"])-```--Property chain inference:-```python-# Infer: if A knows B and B is colleague_of C, then A knows C+# Property chain inference: A knows B, B colleague_of C ⟹ A knows Creasoner.add_property_chain("knows", ["knows", "colleague_of"])inferences = reasoner.infer_property_chains()```-----## DatalogReasoner (v0.4.0)-Pure-Python bottom-up semi-naive fixpoint evaluation for recursive Horn clause rules. Termination is guaranteed:+Pure-Python bottom-up semi-naive fixpoint evaluation for recursive Horn clause rules. Termination is **guaranteed** — the engine detects fixpoint convergence and stops:```pythonfrom semantica.reasoning import DatalogReasoner, DatalogFact, DatalogRuledatalog = DatalogReasoner()-# Add base facts+# Base factsdatalog.add_fact(DatalogFact("parent", ("alice", "bob")))-datalog.add_fact(DatalogFact("parent", ("bob", "charlie")))+datalog.add_fact(DatalogFact("parent", ("bob", "charlie")))-# Add recursive rules (Horn clauses)+# Recursive rules (Horn clauses)datalog.add_rule(DatalogRule("ancestor(?X, ?Y) :- parent(?X, ?Y)."))datalog.add_rule(DatalogRule("ancestor(?X, ?Z) :- parent(?X, ?Y), ancestor(?Y, ?Z)."))@@ -182,12 +166,6 @@ results = datalog.query("ancestor(alice, ?Z)")# → [{"Z": "bob"}, {"Z": "charlie"}]```-<Note>- Datalog termination is guaranteed — the engine detects fixpoint convergence and stops automatically. No infinite loops.-</Note>------## TemporalReasoningEngineReason about time intervals using all 13 Allen interval algebra relations:@@ -197,77 +175,58 @@ from semantica.reasoning import TemporalReasoningEngine, TemporalInterval, Interengine = TemporalReasoningEngine()-# Define intervals-ceo_tenure = TemporalInterval(start="1997-09-16", end="2011-08-24")+ceo_tenure = TemporalInterval(start="1997-09-16", end="2011-08-24")board_member = TemporalInterval(start="2000-01-01", end="2012-06-01")-# Check interval relations (all 13 Allen relations supported)relation = engine.get_relation(ceo_tenure, board_member)-# → IntervalRelation.DURING (ceo_tenure is during board_member)--# Named relations-IntervalRelation.BEFORE # a ends before b starts-IntervalRelation.MEETS # a ends exactly when b starts-IntervalRelation.OVERLAPS # a starts before b, ends inside b-IntervalRelation.DURING # a is fully inside b-IntervalRelation.STARTS # a and b start together, a ends first-IntervalRelation.FINISHES # a and b end together, a starts later-IntervalRelation.EQUALS # identical intervals-# + 6 inverse relations (AFTER, MET_BY, OVERLAPPED_BY, CONTAINS, STARTED_BY, FINISHED_BY)+# → IntervalRelation.DURING (ceo_tenure is fully inside board_member)```----+All 13 Allen interval algebra relations are supported:++| Relation | Meaning |+| -------- | ------- |+| `BEFORE` | A ends before B starts |+| `MEETS` | A ends exactly when B starts |+| `OVERLAPS` | A starts before B, ends inside B |+| `DURING` | A is fully inside B |+| `STARTS` | A and B start together, A ends first |+| `FINISHES` | A and B end together, A starts later |+| `EQUALS` | Identical intervals |+| + 6 inverses | `AFTER`, `MET_BY`, `OVERLAPPED_BY`, `CONTAINS`, `STARTED_BY`, `FINISHED_BY` |## ExplanationGenerator-Generate structured explanations for inferences:+Generate structured step-by-step explanations for any derived conclusion:```python-from semantica.reasoning import ExplanationGenerator, Explanation, ReasoningPath+from semantica.reasoning import ExplanationGeneratorgenerator = ExplanationGenerator(reasoner)-explanation: Explanation = generator.explain(+explanation = generator.explain(conclusion={"subject": "John", "predicate": "has_authority", "object": "true"})print(explanation.conclusion)-print(explanation.confidence)+print(f"Confidence: {explanation.confidence:.2f}")for step in explanation.reasoning_path.steps:- print(f" Step {step.depth}: {step.fact} via rule '{step.rule_name}'")+ print(f" Step {step.depth}: {step.fact}")+ print(f" via rule: '{step.rule_name}'")```------## Built-In Rule Templates--```python-from semantica.reasoning import Reasoner--engine = Reasoner()--# Apply common logical patterns-engine.apply_transitivity("located_in") # A→B, B→C ⟹ A→C-engine.apply_symmetry("knows") # A knows B ⟹ B knows A-engine.apply_inverse("parent_of", "child_of") # A parent_of B ⟹ B child_of A-```-------## See Also-<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 axioms and SHACL constraints.+ Ontology axioms and SHACL constraints for logical reasoning.</Card><Card title="Triplet Store" icon="table" href="triplet_store">- RDF backend for SPARQL reasoning.+ RDF backend for SPARQL-based reasoning.</Card><Card title="Context" icon="brain" href="context">- Reasoning integrated into agent intelligence.+ Reasoning integrated into agent decision intelligence.</Card></CardGroup>diff --git a/docs/reference/seed.md b/docs/reference/seed.mdindex 899f5f45..50471a90 100644--- a/docs/reference/seed.md+++ b/docs/reference/seed.md@@ -4,112 +4,108 @@ description: "Seed data management for initializing Knowledge Graphs from trusteicon: "database"----> Bootstrap Knowledge Graphs with verified taxonomies, reference data, and foundation graphs.+`semantica.seed` provides a system for bootstrapping Knowledge Graphs with verified, structured data from trusted sources — taxonomies, reference tables, user lists, product catalogs — so you start with a reliable foundation rather than an empty graph.------## Overview+## What You Get-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>+- **`SeedDataManager`** — register sources, build a foundation graph, and integrate with extracted data+- **`SeedDataSource`** — define individual data sources with format, path, and config+- **Merge strategies** — `seed_first`, `extracted_first`, `smart_merge` for combining seed and extracted data+- **Validation** — check data quality and schema compliance before loading+- **Versioning** — track and manage versions of seed data sources<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>+ **When to use the Seed Module:**----+- **Bootstrapping** — you have existing structured data (taxonomies, user lists, product catalogs) to build on+- **Reference data** — load immutable reference information (countries, ISO codes, ontology terms)+- **Testing** — load consistent, reproducible datasets for development and CI pipelines+</Tip>## SeedDataManager+The primary interface for seed data:+```pythonfrom semantica.seed import SeedDataManagermanager = SeedDataManager()-manager.register_source("countries", "csv", "data/countries.csv")+manager.register_source("countries", "csv", "data/countries.csv")+manager.register_source("taxonomy", "json", "data/taxonomy.json")++# Build a foundation KG from all registered sourcesfoundation_kg = manager.create_foundation_graph()```+### Core Methods+| 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 |+| ------ | ----------- |+| `register_source(name, format, location)` | Add a data source to the registry |+| `create_foundation_graph()` | Build a KG from all registered sources |+| `validate_quality(seed_data)` | Check data quality and completeness || `integrate_with_extracted(seed, extracted)` | Merge seed and extracted graphs |-| `export_seed_data(path, format)` | Export seed data |-----+| `export_seed_data(path, format)` | Export seed data to RDF, JSON, or CSV |## SeedDataSource+Define a source with format-specific configuration:+```pythonfrom semantica.seed import SeedDataSourcesource = SeedDataSource(name="taxonomy",- type="json", # "csv" | "json" | "api" | "sql"+ type="json", # "csv" | "json" | "api" | "sql"path="taxonomy.json",config={"encoding": "utf-8"})```-----## Merge Strategies+Control how seed data and extracted data are combined:+```pythonfinal_kg = manager.integrate_seed_extracted(seed_graph=foundation_kg,extracted_data=new_data,- strategy="seed_first" # "seed_first" | "extracted_first" | "smart_merge"+ strategy="seed_first" # see options below)```| Strategy | Behavior |-|----------|----------|-| `seed_first` | Seed data overrides extracted data |-| `extracted_first` | Extracted data overrides seed data |-| `smart_merge` | Property-level merging with conflict resolution |-----+| -------- | -------- |+| `seed_first` | Seed data wins on conflicts — use for authoritative reference data |+| `extracted_first` | Extracted data overrides seed — use when new data is more current |+| `smart_merge` | Property-level merging with conflict detection and resolution |## Bootstrapping a KG+Full example — load foundation data then merge with freshly ingested content:+```pythonfrom semantica.seed import SeedDataManagerfrom semantica.ingest import FileIngestor+from semantica.semantic_extract import NERExtractor+from semantica.llms import Groq+import os-# Load foundation from verified data+# Build foundation from verified reference datamanager = SeedDataManager()-manager.register_source("taxonomy", "json", "taxonomy.json")+manager.register_source("taxonomy", "json", "taxonomy.json")+manager.register_source("employees", "csv", "employees.csv")foundation_kg = manager.create_foundation_graph()-# Ingest and merge new data+# Ingest and extract from new sources+llm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))ingestor = FileIngestor()-new_data = ingestor.ingest("news_articles.pdf")+ner = NERExtractor(method="llm", llm_provider=llm)++sources = ingestor.ingest("news_articles/")+new_data = [ner.extract(s.content) for s in sources]+# Merge — seed data takes precedence for reference factsfinal_kg = manager.integrate_seed_extracted(seed_graph=foundation_kg,extracted_data=new_data,@@ -117,8 +113,6 @@ final_kg = manager.integrate_seed_extracted()```-----## Configuration```yaml@@ -127,32 +121,33 @@ seed:- name: "employees"type: "csv"path: "./data/employees.csv"+ - name: "taxonomy"+ type: "json"+ path: "./data/taxonomy.json"merge:strategy: "seed_first"validation:strict: true```+Environment variable overrides:+```bashexport SEED_DATA_DIR=./data/seedexport SEED_MERGE_STRATEGY=seed_first```------## See Also-<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.+ The target graph that seed data populates.</Card><Card title="Deduplication" icon="copy" href="deduplication">- Handle duplicates during merge.+ Handle duplicates during seed-extracted merge.</Card><Card title="Pipeline" icon="gear" href="pipeline">- Incorporate seed loading in a pipeline.+ Incorporate seed loading as a pipeline step.</Card></CardGroup>diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.mdindex e987f0c5..b3f1cd18 100644--- a/docs/reference/semantic_extract.md+++ b/docs/reference/semantic_extract.md@@ -4,30 +4,15 @@ description: "Named entity recognition, relation extraction, event detection, anicon: "magnifying-glass-chart"----> Advanced information extraction system for Entities, Relations, Events, and Triplets.+`semantica.semantic_extract` extracts structured information from unstructured text — the foundation of every knowledge graph in Semantica. All extractors support three modes: pattern-based (no API key), ML-based, and LLM-based.------## 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>+## What You Get----+- **`NERExtractor`** — named entity recognition: Person, Organization, Location, Date, and custom types+- **`RelationExtractor`** — typed semantic relationships between entities (`founded_by`, `located_in`, etc.)+- **`TripletExtractor`** — direct `(subject, predicate, object)` triplet generation for RDF-ready output+- **`EventExtractor`** — event detection with participants, temporal context, and confidence scores+- **`CoreferenceResolver`** — resolve "Apple" and "the company" to the same entity across a document## NERExtractor@@ -36,15 +21,15 @@ from semantica.semantic_extract import NERExtractorfrom semantica.llms import Groqimport os-# Pattern-based (fast, no API key needed)+# Pattern-based — fast, no API key, good for standard entity typesner = NERExtractor(method="pattern")entities = ner.extract("Apple Inc. was founded by Steve Jobs in Cupertino.")-# ML-based+# ML-based — higher accuracy, no API costner = NERExtractor(method="ml", model="dslim/bert-large-NER")entities = ner.extract(text)-# LLM-based (most accurate for complex schemas)+# LLM-based — best accuracy, handles complex schemas and custom typesllm = 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)@@ -60,12 +45,22 @@ Output format:]```+### Custom Entity Types++```python+ner = NERExtractor(+ method="pattern",+ custom_entities={+ "DRUG": ["aspirin", "ibuprofen", "metformin"],+ "GENE": ["BRCA1", "TP53", "EGFR"]+ }+)+```+<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.+ **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, with a plain `generate()` + JSON parsing fallback applied automatically.</Note>-----## RelationExtractor```python@@ -84,25 +79,26 @@ Output format:]```-Methods: `"rule"`, `"ml"` (REBEL model), `"llm"`.-----+Available methods: `"rule"` (pattern-based), `"ml"` (REBEL model), `"llm"`.## TripletExtractor+Generate RDF-ready `(subject, predicate, object)` triplets directly from text:+```pythonfrom semantica.semantic_extract import TripletExtractortrip = TripletExtractor(method="llm", llm_provider=llm)triplets = trip.extract(text)+# → [{"subject": "Steve Jobs", "predicate": "founded", "object": "Apple Inc.", ...}]```-Generates RDF-ready `(subject, predicate, object)` triplets directly from text, suitable for loading into a triplet store.-----+Triplets are suitable for loading directly into a triplet store or knowledge graph.## EventExtractor+Detect events with participants and temporal context:+```pythonfrom semantica.semantic_extract import EventExtractor@@ -110,26 +106,26 @@ extractor = EventExtractor(method="llm", llm_provider=llm)events = extractor.extract(text)```-Output includes event type, participants, temporal information, and confidence score.+Output includes: event type, participants (with roles), temporal information, location, and confidence score.----+## CoreferenceResolver-## Custom Entity Types+Resolve pronoun and alias references to canonical entities before extraction:```python-ner = NERExtractor(- method="pattern",- custom_entities={- "DRUG": ["aspirin", "ibuprofen", "metformin"],- "GENE": ["BRCA1", "TP53", "EGFR"]- }+from semantica.semantic_extract import CoreferenceResolver++resolver = CoreferenceResolver()+resolved_text = resolver.resolve(+ "Apple Inc. was founded in 1976. The company is headquartered in Cupertino.")+# "Apple Inc." replaces "The company" for consistent downstream extraction```-----## Batch Processing+All extractors support batch input for efficient large-scale processing:+```pythontexts = ["Text 1...", "Text 2...", "Text 3..."]@@ -137,27 +133,33 @@ ner = NERExtractor(method="llm", llm_provider=llm)batch_results = ner.extract_batch(texts, batch_size=10)```-----## Using All Extractors Together+The standard extraction pipeline — entities → relationships → triplets:+```pythonfrom semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor+from semantica.llms import Groq+import osllm = Groq(model="llama-3.3-70b-versatile", api_key=os.getenv("GROQ_API_KEY"))-ner = NERExtractor(method="llm", llm_provider=llm, max_retries=3)+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)+trip = TripletExtractor(method="llm", llm_provider=llm, max_retries=3)entities = ner.extract(text)relationships = rel.extract(text, entities=entities)triplets = trip.extract(text)```----+## Extraction Method Comparison-## See Also+| Method | Speed | Cost | Accuracy | Custom Types |+| ------ | ----- | ---- | -------- | ------------ |+| `pattern` | Very fast | Free | Medium | Yes (dictionary) |+| `ml` | Fast | Free | High | Limited |+| `llm` | Medium | API cost | Highest | Yes (schema) |<CardGroup cols={2}><Card title="LLM Providers" icon="microchip" href="llms">diff --git a/docs/reference/split.md b/docs/reference/split.mdindex a209e6e7..f156f7aa 100644--- a/docs/reference/split.md+++ b/docs/reference/split.md@@ -4,15 +4,15 @@ description: "15+ text chunking methods including recursive, semantic, entity-awicon: "scissors"----> Comprehensive document chunking for optimal RAG, embedding, and extraction pipelines.+`semantica.split` breaks documents into chunks while preserving semantic context — critical for embedding quality in RAG systems and accurate entity extraction in NER pipelines.------## Overview+## What You Get-The **Split Module** breaks documents into chunks while preserving context and semantic meaning — critical for embedding quality in RAG systems.-----+- **`TextSplitter`** — unified interface for 9+ chunking strategies+- **Entity-aware chunking** — entity mentions never split across chunk boundaries+- **Relation-aware chunking** — subject–predicate–object triplets kept intact+- **Semantic chunking** — split at topic shift boundaries using embedding similarity+- **`Chunk`** — output object with text, token count, character offsets, and metadata## TextSplitter@@ -20,36 +20,35 @@ The **Split Module** breaks documents into chunks while preserving context and sfrom semantica.split import TextSplittersplitter = TextSplitter(- method="semantic", # see methods below- chunk_size=1000,- overlap=200+ method="semantic", # see methods table below+ chunk_size=1000, # target tokens per chunk+ overlap=200 # token overlap between adjacent chunks)chunks = splitter.split(text)for chunk in chunks:- print(f"Chunk: {chunk.text[:80]}... ({chunk.token_count} tokens)")+ print(f"Chunk {chunk.metadata['chunk_index']}: {chunk.text[:80]}...")+ print(f" Tokens: {chunk.token_count}")```-----## Splitting Methods-| Method | Description | Best for |-|--------|-------------|----------|-| `recursive` | Split by paragraph → sentence → word | General purpose |-| `semantic` | Split at semantic boundaries (topic shifts) | RAG systems |+| Method | Description | Best For |+| ------ | ----------- | -------- |+| `recursive` | Split by paragraph → sentence → word (cascading) | General purpose |+| `semantic` | Split at semantic topic boundaries | RAG retrieval || `entity-aware` | Keep entity mentions intact across boundaries | NER pipelines || `relation-aware` | Keep relation triplets intact | KG construction |-| `sentence` | Split by sentence | Short content |+| `sentence` | Split by sentence boundary | 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 |-----+| `markdown` | Split by Markdown heading hierarchy | Documentation |+| `code` | Split by function/class/method boundaries | Code analysis |## Entity-Aware Chunking+Entity mentions are never split across chunk boundaries, preserving context for downstream NER:+```pythonfrom semantica.split import TextSplitterfrom semantica.semantic_extract import NERExtractor@@ -59,25 +58,25 @@ entities = ner.extract(text)splitter = TextSplitter(method="entity-aware")chunks = splitter.split(text, entities=entities)+# → Each chunk contains only complete entity mentions```-Entity mentions are never split across chunk boundaries, preserving context for downstream NER.------## Relation-Aware Chunking+Subject–predicate–object triplets are kept within the same chunk:+```python+from semantica.split import TextSplitter+splitter = TextSplitter(method="relation-aware")chunks = splitter.split(text, relationships=relationships)+# → Triplets are never split across chunk boundaries```-Keeps subject–predicate–object triplets within the same chunk.------## Semantic Chunking+Split at topic shift boundaries detected via embedding similarity:+```pythonfrom semantica.split import TextSplitterfrom semantica.embeddings import EmbeddingGenerator@@ -86,42 +85,61 @@ embedder = EmbeddingGenerator(model="sentence-transformers")splitter = TextSplitter(method="semantic",embedder=embedder,- similarity_threshold=0.7 # split when topic similarity drops below this+ similarity_threshold=0.7 # split when consecutive sentence similarity drops below this)chunks = splitter.split(text)```----+## Token-Based Chunking++Use tiktoken for precise token-count control when preparing LLM context windows:++```python+splitter = TextSplitter(+ method="token",+ chunk_size=512, # max tokens per chunk+ overlap=50, # overlap in tokens+ tokenizer="cl100k_base" # OpenAI tokenizer+)+chunks = splitter.split(text)+```## Chunk Object```python@dataclassclass 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+ text: str # chunk text content+ start_char: int # character offset in source document+ end_char: int # character offset in source document+ token_count: int # number of tokens+ metadata: Dict # source_id, chunk_index, section_title, page_number, etc.+ entities: List[Dict] # entities in chunk (entity-aware splitting only)```----+## Pipeline Integration-## See Also+```python+from semantica.pipeline import Pipeline+from semantica.split import TextSplitter++pipeline = Pipeline()+pipeline.add_step("split", TextSplitter(method="semantic", chunk_size=512))+result = pipeline.run(documents)+```<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.+ Embed chunks for vector search and semantic chunking.</Card><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">- Extract entities from chunks.+ Extract entities from individual chunks.</Card><Card title="Pipeline" icon="gear" href="pipeline">- Integrate splitting into a pipeline.+ Integrate splitting as a pipeline step.</Card></CardGroup>diff --git a/docs/reference/triplet_store.md b/docs/reference/triplet_store.mdindex 9eb5605e..89d6729a 100644--- a/docs/reference/triplet_store.md+++ b/docs/reference/triplet_store.md@@ -4,17 +4,15 @@ description: "RDF triple storage with SPARQL queries and bulk loading — Blazegicon: "table"----> Store and query RDF triplets with SPARQL support.+`semantica.triplet_store` provides W3C-standard RDF storage with full SPARQL query support. Use it when you need semantic web compatibility, OWL reasoning, SPARQL-based queries, or standards-compliant RDF serialization.------## Overview--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.+## What You Get-Backends: **Blazegraph**, **Apache Jena (Fuseki)**, **RDF4J**.-----+- **`TripletStore`** — unified interface for all RDF backends+- **Backends** — Blazegraph, Apache Jena (Fuseki), RDF4J+- **SPARQL** — full SELECT, CONSTRUCT, ASK, and UPDATE query support+- **Bulk loading** — efficient batch import for large triple sets+- **Import / Export** — Turtle, JSON-LD, N-Triples, RDF/XML## Basic Usage@@ -26,23 +24,21 @@ store = TripletStore(endpoint="http://localhost:9999/blazegraph/sparql")-# Add triplets+# Add a single tripletstore.add_triplet(subject="http://example.org/apple_inc",predicate="http://example.org/founded_by",obj="http://example.org/steve_jobs")-# Bulk load+# Bulk load a list of tripletsstore.add_triplets_bulk(triplets)```-----## SPARQL Queries```python-# SELECT query+# SELECT — returns tabular resultsresults = store.sparql("""PREFIX ex: <http://example.org/>SELECT ?person ?company WHERE {@@ -51,7 +47,10 @@ results = store.sparql("""}""")-# CONSTRUCT query (returns graph)+for row in results:+ print(row["person"], row["company"])++# CONSTRUCT — returns a graph of matched triplesgraph = store.sparql_construct("""PREFIX ex: <http://example.org/>CONSTRUCT {@@ -61,28 +60,40 @@ graph = store.sparql_construct("""?company ex:has_investor ?o .}""")-```----+# ASK — returns True/False+exists = store.sparql_ask("""+ PREFIX ex: <http://example.org/>+ ASK { ex:apple_inc ex:founded_by ex:steve_jobs . }+""")++# UPDATE — insert or delete triples+store.sparql_update("""+ PREFIX ex: <http://example.org/>+ INSERT DATA {+ ex:apple_inc ex:listed_on ex:NASDAQ .+ }+""")+```## Backends```python-# Blazegraph+# Blazegraph — open source, SPARQL 1.1store = TripletStore(backend="blazegraph",endpoint="http://localhost:9999/blazegraph/sparql",namespace="semantica")-# Apache Jena Fuseki+# Apache Jena Fuseki — open source, widely usedstore = TripletStore(backend="jena",endpoint="http://localhost:3030/dataset/sparql",update_endpoint="http://localhost:3030/dataset/update")-# RDF4J+# RDF4J — enterprise-grade, Eclipse Foundationstore = TripletStore(backend="rdf4j",server_url="http://localhost:8080/rdf4j-server",@@ -90,33 +101,82 @@ store = TripletStore()```----+## Backend Comparison-## Import / Export+| Backend | License | Query Language | Best For |+| ------- | ------- | -------------- | -------- |+| Blazegraph | Open source | SPARQL 1.1 | Wikidata-style workloads |+| Apache Jena | Apache 2.0 | SPARQL 1.1 | General RDF, OWL reasoning |+| RDF4J | Eclipse 1.0 | SPARQL 1.1 | Enterprise, Java ecosystems |++## Import and Export```python# Import from file-store.import_file("ontology.ttl", format="turtle")-store.import_file("data.jsonld", format="json-ld")+store.import_file("ontology.ttl", format="turtle")+store.import_file("data.jsonld", format="json-ld")+store.import_file("triples.nt", format="nt")# Export to filestore.export("output.ttl", format="turtle")store.export("output.nt", format="nt")+store.export("output.xml", format="xml")```----+## Graph Management-## See Also+```python+# Named graphs — store triples in isolated contexts+store.add_triplet(+ subject="http://example.org/a",+ predicate="http://example.org/p",+ obj="http://example.org/b",+ graph="http://example.org/graph1"+)++# Query a specific named graph+results = store.sparql("""+ SELECT ?s ?p ?o FROM <http://example.org/graph1> WHERE {+ ?s ?p ?o .+ }+""")++# List all named graphs+graphs = store.list_graphs()++# Clear a named graph+store.clear_graph("http://example.org/graph1")+```++## Integration with Export Module++The Export module can write RDF that the triplet store then imports:++```python+from semantica.export import RDFExporter+from semantica.triplet_store import TripletStore++# Export KG to Turtle+exporter = RDFExporter()+exporter.export_to_file(kg, "output.ttl", format="turtle")++# Load into triplet store+store = TripletStore(backend="jena", endpoint="http://localhost:3030/dataset/sparql")+store.import_file("output.ttl", format="turtle")++# Now query with SPARQL+results = store.sparql("SELECT * WHERE { ?s ?p ?o } LIMIT 10")+```<CardGroup cols={2}><Card title="Export" icon="file-export" href="export">- Export to RDF formats.+ Export knowledge graphs 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.+ SPARQL-based property chain inference.</Card><Card title="Graph Store" icon="server" href="graph_store">Property graph alternative for Cypher queries.diff --git a/docs/reference/utils.md b/docs/reference/utils.mdindex 2f5b955e..8618b687 100644--- a/docs/reference/utils.md+++ b/docs/reference/utils.md@@ -4,36 +4,15 @@ description: "Shared utilities for logging, validation, error handling, progressicon: "wrench"----> Internal utilities used across all Semantica modules — logging, validation, error handling, and helpers.+`semantica.utils` provides shared infrastructure used throughout Semantica. Most users won't call it directly, but its APIs are available when you need fine-grained control over logging, validation, progress tracking, or error handling.------## 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>+## What You Get----+- **Logging** — structured logging with `@log_performance` decorator and quality metrics+- **Validation** — `validate_entity`, `validate_config` with a typed `ValidationError`+- **Progress tracking** — `track_progress` wraps any iterable with console, Jupyter, or file output+- **Helper functions** — `clean_text`, `hash_data`, `safe_filename`+- **Exception hierarchy** — `SemanticaError` → `ValidationError`, `ProcessingError`## Logging@@ -46,58 +25,72 @@ logger = get_logger(__name__)@log_performancedef process_data(data):logger.info(f"Processing {len(data)} items")+ # Decorator automatically logs function name, duration, and any exception```+Configure via environment variables:+```bashexport SEMANTICA_LOG_LEVEL=DEBUGexport SEMANTICA_LOG_FORMAT=json # "json" | "text"export SEMANTICA_PROGRESS_BAR=true```-----## Validation```pythonfrom semantica.utils import validate_entity, validate_config, ValidationError+# Validate an entity dicttry:validate_entity({"id": "1", "type": "PERSON", "text": "Alice"})except ValidationError as e:- print(f"Invalid entity: {e}")+ print(f"Invalid entity: {e.message}")+ print(f" Field: {e.field}")+ print(f" Value: {e.value}")++# Validate a configuration dict+try:+ validate_config(config)+except ValidationError as e:+ print(f"Invalid config: {e}")```| Function | Description |-|----------|-------------|-| `validate_entity(data)` | Check entity structure |-| `validate_config(cfg)` | Check configuration dict |-----+| -------- | ----------- |+| `validate_entity(data)` | Check entity dict has required fields and correct types |+| `validate_config(cfg)` | Check configuration dict against schema |## Progress Tracking```pythonfrom semantica.utils import track_progress+# Wraps any iterable — auto-detects console vs Jupyterfor item in track_progress(items, desc="Processing documents"):process(item)```-Supports console (tqdm), Jupyter notebooks, and file logging automatically.+Supports:----+- **Console** — tqdm progress bar with ETA+- **Jupyter** — notebook-compatible widget+- **File** — write progress to a log file## Helper Functions```pythonfrom semantica.utils import clean_text, hash_data, safe_filename-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"-```+# Normalize whitespace and strip control characters+clean = clean_text(" Hello World ") # → "Hello World"----+# Deterministic SHA-256 hash of any serializable object+uid = hash_data({"key": "value"}) # → hex digest string++# Sanitize a string for use as a filename+fname = safe_filename("My File?.txt") # → "My_File_.txt"+```## Exception Hierarchy@@ -105,27 +98,29 @@ fname = safe_filename("My File?.txt") # "My_File_.txt"from semantica.utils import SemanticaError, ValidationError, ProcessingErrortry:- ...+ run_pipeline(data)except ValidationError as e:- # Input data did not pass validation- ...+ # Input data did not pass schema validation+ logger.error(f"Validation failed: {e}")except ProcessingError as e:# Failure during extraction or graph construction- ...+ logger.error(f"Processing failed at step {e.step}: {e}")except SemanticaError as e:- # Catch-all for all framework errors- ...+ # Catch-all for all Semantica framework errors+ logger.error(f"Framework error: {e}")```------## See Also+| Exception | When Raised |+| --------- | ----------- |+| `SemanticaError` | Base class — all framework errors inherit from this |+| `ValidationError` | Input data failed schema or type validation |+| `ProcessingError` | Failure during extraction, graph build, or pipeline step |<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.+ Uses ProgressTracker for per-step tracking.</Card></CardGroup>diff --git a/docs/reference/vector_store.md b/docs/reference/vector_store.mdindex d5f76493..881e5df1 100644--- a/docs/reference/vector_store.md+++ b/docs/reference/vector_store.md@@ -4,30 +4,16 @@ description: "Unified interface for FAISS, Pinecone, Weaviate, Qdrant, Milvus, aicon: "database"----> Unified vector database interface supporting multiple backends and hybrid search.+`semantica.vector_store` provides a unified API for storing and searching vector embeddings across all major backends. Swap backends with a one-line change — no application code changes needed.------## Overview+## What You Get-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>-----+- **`VectorStore`** — unified interface across all backends+- **Backends** — FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory+- **Hybrid search** — combine dense vector similarity with sparse keyword/metadata filtering+- **Metadata filtering** — rich filter expressions: `eq`, `ne`, `gt`, `lt`, `in`, `contains`, `$and`, `$or`+- **Namespace isolation** — multi-tenant support via isolated namespaces+- **Batch operations** — bulk add, delete, and metadata updates## Basic Usage@@ -47,84 +33,109 @@ store.add_vectors(embeddings=embeddings, ids=["doc1", "doc2"], metadata=[{}, {}]results = store.search(query_vector, top_k=10)for r in results:print(f"{r['id']} — score: {r['score']:.3f}")+ print(f" metadata: {r['metadata']}")```-----## 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.++```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. No API key required.+</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"- )- ```++```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"- )- ```++```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"- )- ```++```bash+pip install "semantica[qdrant]"+```++```python+store = VectorStore(+ backend="qdrant",+ dimension=768,+ url="http://localhost:6333",+ collection_name="semantica"+)+```+</Tab>-</Tabs>+ <Tab title="PgVector">----+```bash+pip install "semantica[pgvector]"+```++```python+store = VectorStore(+ backend="pgvector",+ dimension=768,+ connection_string="postgresql://user:pass@localhost/db",+ table_name="embeddings"+)+```++See the [PgVector Guide](../vector_stores/pgvector) for full setup.++ </Tab>+</Tabs>## Hybrid Search-Combines vector similarity with keyword/metadata filters.+Combine vector similarity with keyword/metadata filters for higher precision:```pythonresults = store.hybrid_search(query_vector=query_embedding,- query_text="machine learning", # keyword component+ query_text="machine learning", # keyword componenttop_k=10,- alpha=0.7, # 0=keyword only, 1=vector only+ alpha=0.7, # 0.0 = keyword only, 1.0 = vector onlyfilters={"category": "research", "year": {"$gte": 2022}})```-----## Metadata Filtering```python@@ -137,53 +148,64 @@ results = store.search(query_vector, filters={"date": {"$gte": "2023-01-01"}})# Set membershipresults = store.search(query_vector, filters={"tag": {"$in": ["ai", "ml"]}})-# Compound+# Compound ANDresults = store.search(query_vector, filters={- "$and": [{"category": "research"}, {"year": {"$gte": 2022}}]+ "$and": [+ {"category": "research"},+ {"year": {"$gte": 2022}}+ ]})```----+## Namespace Isolation-## Namespaces (Multi-Tenant)+Isolate vectors per tenant, project, or use case:```pythonstore = VectorStore(backend="faiss", dimension=768)-store.add_vectors(embeddings, ids, namespace="tenant_a")-store.add_vectors(embeddings, ids, namespace="tenant_b")+# Write to separate namespaces+store.add_vectors(embeddings_a, ids_a, namespace="tenant_a")+store.add_vectors(embeddings_b, ids_b, namespace="tenant_b")+# Search is scoped to the specified namespaceresults = store.search(query_vector, namespace="tenant_a")```-----## Batch Operations```python-# Batch add+# Batch add — automatically chunked for memory efficiencystore.add_vectors_batch(embeddings_list, ids_list, batch_size=1000)# Batch deletestore.delete_vectors(ids=["doc1", "doc2", "doc3"])-# Update metadata-store.update_metadata("doc1", {"status": "archived"})+# Update metadata without re-embedding+store.update_metadata("doc1", {"status": "archived", "reviewed": True})```----+## Backend Comparison-## See Also+| Backend | Deployment | API Key | Hybrid Search | Best For |+| ------- | ---------- | ------- | ------------- | -------- |+| FAISS | Local | No | No | On-premise, offline |+| Pinecone | Cloud | Yes | Yes | Managed cloud, serverless |+| Weaviate | Self-hosted / Cloud | Optional | Yes | Rich metadata filtering |+| Qdrant | Self-hosted / Cloud | Optional | Yes | High-performance filtering |+| Milvus | Self-hosted | No | Yes | Large-scale production |+| PgVector | PostgreSQL | No | Limited | Postgres-native integration |+| In-memory | Process | No | No | Development, testing |<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.+ AgentContext uses VectorStore for memory retrieval.</Card><Card title="PgVector Guide" icon="database" href="../vector_stores/pgvector">- PostgreSQL vector storage with pgvector.+ PostgreSQL vector storage with pgvector extension.</Card><Card title="Ingest" icon="download" href="ingest">Ingest documents before embedding and storing.diff --git a/docs/reference/visualization.md b/docs/reference/visualization.mdindex ad059df7..f16fe818 100644--- a/docs/reference/visualization.md+++ b/docs/reference/visualization.md@@ -4,9 +4,15 @@ description: "Interactive and static knowledge graph, ontology, embedding, and ticon: "chart-bar"----> Comprehensive visualization suite for knowledge graphs, ontologies, embeddings, and temporal data.+`semantica.visualization` renders knowledge graphs, ontologies, embedding spaces, and temporal data as interactive HTML or static images — without launching the full Explorer server.----+## What You Get++- **`GraphVisualizer`** — interactive HTML (PyVis) and static image (Matplotlib) graph rendering+- **`OntologyVisualizer`** — class hierarchy and property relationship visualization+- **`EmbeddingVisualizer`** — UMAP, t-SNE, and PCA dimensionality reduction plots+- **`TemporalVisualizer`** — timeline views and animated graph evolution+- **`DistanceVisualizer`** — ego-mode neighborhood views and distance matrix heatmaps (v0.5.0)## GraphVisualizer@@ -15,97 +21,111 @@ from semantica.visualization import GraphVisualizerviz = GraphVisualizer()-# Interactive HTML (PyVis)+# Interactive HTML — opens in browser, supports hover and clickviz.visualize(graph, output="graph.html")-# Static image (Matplotlib)+# Static image — for reports and exportviz.visualize(graph, output="graph.png", backend="matplotlib")-# Open directly in browser+# Display inline (Jupyter or default browser)viz.show(graph)```------## Layout Options+### Layout and Styling Options```pythonviz.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+ layout="force_directed", # "force_directed" | "hierarchical" | "circular" | "spring"+ node_color_by="type", # color nodes by entity type attribute+ edge_label="relation", # show edge relationship labels+ max_nodes=500 # limit rendering for large graphs)```----+### Layout Options++| Layout | Description | Best For |+| ------ | ----------- | -------- |+| `force_directed` | Physics simulation — clusters emerge naturally | General graphs |+| `hierarchical` | Top-down tree layout | Taxonomies, org charts |+| `circular` | Nodes on a circle, edges as chords | Small dense graphs |+| `spring` | Spring-force layout (Fruchterman-Reingold) | Medium graphs |-## Ontology Visualization+## OntologyVisualizer++Visualize class hierarchies and property relationships:```pythonfrom semantica.visualization import OntologyVisualizerviz = OntologyVisualizer()++# Full ontology graphviz.visualize(ontology, output="ontology.html")-# Hierarchy view+# Class hierarchy onlyviz.visualize_hierarchy(ontology, output="hierarchy.html")```----+## EmbeddingVisualizer-## Embedding Visualization+Project high-dimensional embeddings into 2D for cluster analysis:```pythonfrom semantica.visualization import EmbeddingVisualizerviz = EmbeddingVisualizer()-# UMAP projectionviz.visualize(embeddings=embeddings,labels=labels,output="embeddings.html",- method="umap" # umap | tsne | pca+ method="umap" # "umap" | "tsne" | "pca")```----+| Method | Speed | Preserves | Best For |+| ------ | ----- | --------- | -------- |+| `umap` | Fast | Global + local structure | Large datasets, cluster discovery |+| `tsne` | Medium | Local structure | Tight cluster separation |+| `pca` | Very fast | Variance | Quick overview, linear structure |-## Temporal Visualization+## TemporalVisualizer++Visualize how a knowledge graph changes over time:```pythonfrom semantica.visualization import TemporalVisualizerviz = TemporalVisualizer()-# Timeline of graph changes+# Static timeline of additions and removalsviz.visualize_timeline(temporal_kg, output="timeline.html")-# Animated graph evolution+# Animated evolution — one frame per time stepviz.animate(temporal_kg, output="evolution.html", fps=2)```----+## DistanceVisualizer (v0.5.0)-## Distance / Ego-Mode Visualization (v0.5.0)+Semantic neighborhood and distance matrix visualization from Distance Intelligence:```pythonfrom semantica.visualization import DistanceVisualizerviz = DistanceVisualizer()-# Ego-mode: neighborhood of a node colored by distance band+# Ego-mode: neighborhood of one node colored by distance bandviz.visualize_ego(graph,center_node="Apple Inc.",output="ego.html",- radius=0.5+ radius=0.5 # semantic distance radius)-# Distance matrix heatmap+# N×N distance matrix heatmapviz.visualize_distance_matrix(matrix=distance_matrix,labels=node_labels,@@ -113,11 +133,9 @@ viz.visualize_distance_matrix()```------## Graph Explorer (v0.4.0/v0.5.0)+## Graph Explorer (Full Dashboard)-The full-featured browser UI — bidirectional path finding, indexed search (0.004ms on 118k nodes), workspace management.+For a full browser-based UI with search, path finding, and the Ontology Hub, use `semantica.explorer`:```pythonfrom semantica.explorer import start_explorer@@ -126,21 +144,19 @@ start_explorer(graph=kg, port=8080)# Opens at http://localhost:8080```------## See Also+See the [Explorer reference](explorer) for the full feature set and REST API.<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.+ Visualize ontology class structure.</Card><Card title="Embeddings" icon="vector-square" href="embeddings">- Visualize embedding space.+ Generate the embeddings visualized here.</Card><Card title="Explorer" icon="globe" href="explorer">- Full Knowledge Explorer UI.+ Full interactive Knowledge Explorer UI.</Card></CardGroup>diff --git a/docs/use-cases.md b/docs/use-cases.mdindex aa9d39b9..da3b0092 100644--- a/docs/use-cases.md+++ b/docs/use-cases.md@@ -4,10 +4,12 @@ description: "Real-world applications of Semantica across domains, with linked cicon: "briefcase"----## Overview+Semantica is purpose-built for environments where AI outputs must be explainable, auditable, and traceable. The use cases below span regulated industries, advanced research, and high-stakes operational domains — each with linked Jupyter notebooks you can run today.++## At a Glance| Use Case | Domain | Difficulty | Estimated Time |-|----------|--------|------------|----------------|+| -------- | ------ | ---------- | -------------- || Biomedical Knowledge Graphs | Healthcare | Intermediate | 1–2 hours || Financial Data Integration | Finance | Intermediate | 1–2 hours || Fraud Detection | Finance | Advanced | 2–3 hours |@@ -17,112 +19,120 @@ icon: "briefcase"| Intelligence Analysis Orchestrator | Intelligence | Intermediate | 1–2 hours || Supply Chain Optimization | Operations | Intermediate | 1–2 hours || Renewable Energy Management | Energy | Intermediate | 1–2 hours |-| GraphRAG | AI | Advanced | 1–2 hours |+| GraphRAG | AI / LLM | Advanced | 1–2 hours |**Difficulty levels:**-- **Beginner** — basic Semantica knowledge only-- **Intermediate** — some domain knowledge helpful-- **Advanced** — domain expertise + advanced Semantica features-----+- **Beginner** — basic Semantica knowledge only, no domain expertise needed+- **Intermediate** — some domain knowledge helpful, uses 2–4 Semantica modules+- **Advanced** — domain expertise expected, uses advanced features (temporal graphs, multi-source pipelines, reasoning)## Research & Science### Biomedical Knowledge Graphs-Connect genes, proteins, drugs, and diseases from scientific literature and databases to accelerate drug discovery and understand disease pathways.+Connect genes, proteins, drugs, and diseases from scientific literature and databases to accelerate drug discovery and understand disease mechanisms. Semantica's temporal graphs and provenance tracking make every fact in the knowledge base traceable to its source publication.++**Key modules:** `ingest` (PubMed RSS), `semantic_extract`, `kg`, `deduplication`, `context`**Cookbooks:**+- [Drug Discovery Pipeline](https://github.com/semantica-agi/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/semantica-agi/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb) — bioRxiv RSS, temporal KGs, deduplication, pathway analysis-----## Finance & Trading### Financial Data Integration-Unify financial data from APIs, MCP servers, and real-time streams into a single queryable knowledge graph.+Unify financial data from APIs, MCP servers, and real-time streams into a single queryable knowledge graph — with conflict detection when sources disagree and full provenance back to each data feed.++**Key modules:** `ingest` (API, MCP, stream), `normalize`, `kg`, `conflicts`, `provenance`**Cookbook:** [Financial Data Integration (MCP)](https://github.com/semantica-agi/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.+Detect complex fraud rings using temporal graphs and pattern detection over transaction, device, and user data. Temporal edges let you query: "what connections existed during this window?" — critical for reconstructing fraud timelines.++**Key modules:** `kg` (temporal), `conflicts`, `reasoning`, `visualization`**Cookbook:** [Fraud Detection](https://github.com/semantica-agi/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.+Map transaction flows, analyze DeFi protocols, and detect illicit activity across wallet and exchange networks. Graph algorithms (centrality, community detection) surface high-risk actors that linear transaction analysis misses.**Cookbooks:**+- [DeFi Protocol Intelligence](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb)- [Transaction Network Analysis](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb)-----## Security & Intelligence### Cybersecurity Threat Intelligence-Ingest threat feeds (CVE databases, security RSS), detect anomalies in streaming data, and build threat intelligence knowledge graphs for proactive defense.+Ingest threat feeds (CVE databases, security RSS), detect anomalies in streaming data, and build threat intelligence knowledge graphs for proactive defense. Real-time streaming ingestion with temporal provenance means every threat event is timestamped and traceable.++**Key modules:** `ingest` (stream, feed), `kg` (temporal), `context`, `reasoning`, `export`**Cookbooks:**+- [Real-Time Anomaly Detection](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)- [Threat Intelligence Hybrid RAG](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)### Criminal Network Analysis-Build knowledge graphs from police reports, court records, and OSINT feeds to identify key players, communities, and suspicious patterns using network centrality analysis.+Build knowledge graphs from police reports, court records, and OSINT feeds to identify key players, communities, and suspicious patterns. Network centrality analysis (PageRank, betweenness) surfaces actors that text search alone would miss.++**Key modules:** `ingest`, `semantic_extract`, `kg`, `visualization` (community detection)**Cookbook:** [Criminal Network Analysis](https://github.com/semantica-agi/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.+Process multiple intelligence sources in parallel using an orchestrator-worker pipeline pattern with multi-source conflict detection and resolution. When sources disagree on the same fact, Semantica flags and resolves rather than silently discarding.-**Cookbook:** [Intelligence Analysis Orchestrator-Worker](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)+**Key modules:** `pipeline`, `ingest`, `conflicts`, `provenance`, `export`----+**Cookbook:** [Intelligence Analysis Orchestrator-Worker](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)## Industry & Operations### Supply Chain Optimization-Map suppliers, logistics routes, and inventory levels to identify bottlenecks and optimize global supply chains.+Map suppliers, logistics routes, inventory levels, and delivery relationships to identify bottlenecks and optimize global supply chains. Graph path-finding reveals indirect dependencies that spreadsheet analysis cannot.++**Key modules:** `ingest`, `kg`, `reasoning`, `visualization`, `export` (Parquet for analytics)**Cookbook:** [Supply Chain Data Integration](https://github.com/semantica-agi/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.+Connect sensor data, weather forecasts, and maintenance logs to predict equipment failures and optimize grid operations. Temporal graphs let you track asset states over time and correlate maintenance events with performance degradation.-**Cookbook:** [Energy Market Analysis](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)+**Key modules:** `ingest` (stream, API), `kg` (temporal), `reasoning`, `visualization`----+**Cookbook:** [Energy Market Analysis](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)## Advanced AI Patterns### GraphRAG (Graph-Augmented Generation)-Use knowledge graphs to retrieve precise, structured context for LLM responses — with hybrid retrieval, logical inference, and source attribution.+Use knowledge graphs to retrieve precise, structured context for LLM responses — with hybrid retrieval (vector + graph traversal), logical inference, and source attribution on every claim. Every answer links back to a node in the graph, making hallucination auditable rather than invisible.-**Cookbooks:**-- [GraphRAG Complete](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) — production-ready implementation-- [RAG vs. GraphRAG Comparison](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) — side-by-side comparison+**Key modules:** `context`, `vector_store`, `kg`, `reasoning`, `llms`----+**Cookbooks:**-## Next Steps+- [GraphRAG Complete](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) — production-ready implementation with hybrid retrieval+- [RAG vs. GraphRAG Comparison](https://github.com/semantica-agi/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) — side-by-side benchmark on real-world data<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.+ Every module with code examples.</Card><Card title="API Reference" icon="code" href="reference/context">Complete technical documentation.