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
fix: remove non-existent classes and fix wrong API signatures across reference docs
KaifAhmad16f726c708f9e
diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.mdindex c81cbf4d..5d2cb1d4 100644--- a/docs/reference/embeddings.md+++ b/docs/reference/embeddings.md@@ -70,18 +70,21 @@ providers = check_available_providers()from semantica.embeddings import EmbeddingGenerator# Default — Sentence-Transformers, free, runs locally- generator = EmbeddingGenerator(model="sentence-transformers")+ generator = EmbeddingGenerator()++ # Custom model via config dict+ generator = EmbeddingGenerator(config={"text": {"method": "sentence_transformers", "model_name": "BAAI/bge-large-en-v1.5"}})```</Step><Step title="Generate embeddings">```python- embeddings = generator.generate(["Text about AI", "Machine learning concepts"])+ embeddings = generator.generate_embeddings(["Text about AI", "Machine learning concepts"])```</Step><Step title="Compute similarity">```python# Cosine similarity — 0.0 (unrelated) to 1.0 (identical meaning)- score = generator.similarity(embeddings[0], embeddings[1])+ score = generator.compare_embeddings(embeddings[0], embeddings[1], method="cosine")print(f"Similarity: {score:.3f}")```</Step>@@ -124,14 +127,14 @@ providers = check_available_providers()```pythonfrom semantica.embeddings import EmbeddingGenerator- # Default model — all-MiniLM-L6-v2, dimension 384- generator = EmbeddingGenerator(model="sentence-transformers")+ # Default — Sentence-Transformers with all-MiniLM-L6-v2+ generator = EmbeddingGenerator()- # Specific HuggingFace model- generator = EmbeddingGenerator(model="BAAI/bge-large-en-v1.5")+ # Custom model via set_text_model+ generator.set_text_model("sentence_transformers", "BAAI/bge-large-en-v1.5")- embeddings = generator.generate(texts)- similarity = generator.similarity(embeddings[0], embeddings[1])+ embeddings = generator.generate_embeddings(texts)+ similarity = generator.compare_embeddings(embeddings[0], embeddings[1])```Best for: default prototyping, no API key, good quality.@@ -140,23 +143,20 @@ providers = check_available_providers()```pythonfrom semantica.embeddings import EmbeddingGenerator- generator = EmbeddingGenerator(model="fastembed")- embeddings = generator.generate(texts)+ generator = EmbeddingGenerator()+ generator.set_text_model("fastembed", "BAAI/bge-small-en-v1.5")+ embeddings = generator.generate_embeddings(texts)```Best for: CPU-only production, lowest latency without GPU.</Tab><Tab title="OpenAI">```python- from semantica.embeddings import EmbeddingGenerator+ from semantica.embeddings import OpenAIStoreimport os- generator = EmbeddingGenerator(- model="openai",- model_name="text-embedding-3-small",- api_key=os.getenv("OPENAI_API_KEY"),- )- embeddings = generator.generate(texts)+ store = OpenAIStore(api_key=os.getenv("OPENAI_API_KEY"), model="text-embedding-3-small")+ embedding = store.embed("Hello world")```Best for: highest quality (3-large), or matching an OpenAI LLM pipeline.@@ -175,14 +175,11 @@ providers = check_available_providers()```pythonfrom semantica.embeddings import EmbeddingGenerator- # NVIDIA GPU- generator = EmbeddingGenerator(model="sentence-transformers", device="cuda")+ # Set device via text embedder config+ generator = EmbeddingGenerator(config={"text": {"device": "cuda"}})# Apple Silicon (M1/M2/M3)- generator = EmbeddingGenerator(model="sentence-transformers", device="mps")-- # CPU (default)- generator = EmbeddingGenerator(model="sentence-transformers", device="cpu")+ generator = EmbeddingGenerator(config={"text": {"device": "mps"}})```GPU reduces embedding time by 5–20× depending on batch size and model.@@ -193,13 +190,10 @@ providers = check_available_providers()| Parameter | Type | Default | Description || --------- | ---- | ------- | ----------- |-| `model` | `str` | `"sentence-transformers"` | Provider name or HuggingFace model ID |-| `model_name` | `str` | Provider default | Specific model within a provider (OpenAI) |-| `api_key` | `str` | `None` | API key for cloud providers; reads env var if omitted |-| `device` | `str` | `"cpu"` | Compute device: `"cpu"` / `"cuda"` / `"mps"` |-| `batch_size` | `int` | `32` | Texts per forward pass |-| `normalize` | `bool` | `True` | L2-normalise output vectors (required for cosine similarity) |-| `cache_dir` | `str` | `None` | Directory for disk caching of computed embeddings |+| `config` | `dict` | `None` | Config dict; `config["text"]` is passed to `TextEmbedder` |+| `**kwargs` | | | Additional key/value config merged into `config` |++Use `generator.set_text_model(method, model_name)` to switch the embedding model after construction.## TextEmbedderdiff --git a/docs/reference/evals.md b/docs/reference/evals.mdindex 0411dac4..4da8b3db 100644--- a/docs/reference/evals.md+++ b/docs/reference/evals.md@@ -1,230 +1,42 @@---title: "Evals Module"-description: "Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance."+description: "Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance — coming soon."icon: "chart-line"----`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.+`semantica.evals` is planned as a comprehensive evaluation framework for measuring extraction accuracy, graph quality, and pipeline performance.-## What You Get--<CardGroup cols={2}>- <Card title="KGEvaluator" icon="diagram-project">- Completeness, consistency, schema compliance, coverage, and orphan node metrics.- </Card>- <Card title="ExtractionEvaluator" icon="magnifying-glass">- NER precision / recall / F1 and relation extraction metrics against gold-standard datasets.- </Card>- <Card title="PipelineEvaluator" icon="gear">- Throughput (docs/sec), per-step latency, peak memory, and error rate benchmarking.- </Card>- <Card title="RegressionTracker" icon="clock-rotate-left">- Record pipeline runs and compare metrics across commits or config changes.- </Card>- <Card title="Deduplication Accuracy" icon="copy">- Merge precision, false positive / false negative rates for deduplication strategies.- </Card>- <Card title="Reasoning Correctness" icon="microchip">- Inference accuracy, rule coverage, and derivation depth for reasoning engines.- </Card>-</CardGroup>--## Quick Start--<Steps>- <Step title="Evaluate KG quality">- ```python- from semantica.evals import KGEvaluator-- evaluator = KGEvaluator()- report = evaluator.evaluate(kg, ontology=ontology)-- print(f"Completeness: {report.completeness:.2%}")- print(f"Consistency: {report.consistency:.2%}")- print(f"Coverage: {report.coverage:.2%}")- print(f"Orphan nodes: {report.orphan_count}")- ```- </Step>- <Step title="Evaluate extraction accuracy against gold standard">- ```python- from semantica.evals import ExtractionEvaluator-- evaluator = ExtractionEvaluator()- report = evaluator.evaluate_ner(- predictions=extracted_entities,- gold_standard=annotated_entities,- )-- print(f"Precision: {report.precision:.3f}")- print(f"Recall: {report.recall:.3f}")- print(f"F1: {report.f1:.3f}")- print(f"By type: {report.per_type_metrics}")- ```- </Step>- <Step title="Benchmark pipeline throughput">- ```python- from semantica.evals import PipelineEvaluator-- evaluator = PipelineEvaluator()- metrics = evaluator.benchmark(pipeline, data="data/", warmup_runs=2, bench_runs=5)-- print(f"Throughput: {metrics.docs_per_second:.1f} docs/sec")- print(f"Total duration: {metrics.total_seconds:.1f}s")- print(f"Per-step latency: {metrics.step_latencies}")- print(f"Peak memory (MB): {metrics.peak_memory_mb:.0f}")- print(f"Error rate: {metrics.error_rate:.2%}")- ```- </Step>- <Step title="Track regressions across releases">- ```python- from semantica.evals import RegressionTracker-- tracker = RegressionTracker(db_path="eval_history.db")-- run_id = tracker.record_run(- pipeline_version="v1.2.0",- metrics=metrics,- config=config.to_dict(),- )-- diff = tracker.compare(run_id, baseline_run_id="run_abc123")- for metric, change in diff.items():- direction = "↑" if change > 0 else "↓"- print(f" {metric}: {direction} {abs(change):.2%}")- ```- </Step>-</Steps>--## Evaluation Areas--<Tabs>- <Tab title="KG Quality">- Measure completeness, consistency, schema compliance, and structural health of a knowledge graph:-- ```python- from semantica.evals import KGEvaluator-- evaluator = KGEvaluator()- report = evaluator.evaluate(kg, ontology=ontology)-- print(f"Completeness: {report.completeness:.2%}") # % entities with all required fields- print(f"Consistency: {report.consistency:.2%}") # % entities without type conflicts- print(f"Coverage: {report.coverage:.2%}") # % entity types in ontology- print(f"Total nodes: {report.node_count}")- print(f"Orphan nodes: {report.orphan_count}") # nodes with no edges- ```-- **Key behaviours:**- - `consistency` requires an ontology — without one, it always returns 1.0- - `orphan_count` flags disconnected nodes that likely represent extraction or deduplication errors- - `completeness` checks required properties defined in the ontology schema- </Tab>- <Tab title="Extraction Accuracy">- Compare extracted entities and relations against annotated gold-standard data:-- ```python- from semantica.evals import ExtractionEvaluator-- evaluator = ExtractionEvaluator()-- # NER evaluation- ner_report = evaluator.evaluate_ner(- predictions=extracted_entities,- gold_standard=annotated_entities,- )- print(f"Precision: {ner_report.precision:.3f}")- print(f"Recall: {ner_report.recall:.3f}")- print(f"F1: {ner_report.f1:.3f}")- print(f"By type: {ner_report.per_type_metrics}")-- # Relation extraction evaluation- rel_report = evaluator.evaluate_relations(- predictions=extracted_relations,- gold_standard=annotated_relations,- )- print(f"Relation F1: {rel_report.f1:.3f}")- ```- </Tab>- <Tab title="Pipeline Performance">- Benchmark throughput, latency, memory, and error rate across multiple runs:-- ```python- from semantica.evals import PipelineEvaluator-- evaluator = PipelineEvaluator()- metrics = evaluator.benchmark(- pipeline,- data="data/",- warmup_runs=2, # eliminate cold-start noise- bench_runs=5, # average over 5 real runs- )-- print(f"Throughput: {metrics.docs_per_second:.1f} docs/sec")- print(f"Total duration: {metrics.total_seconds:.1f}s")- print(f"Per-step latency: {metrics.step_latencies}")- print(f"Peak memory (MB): {metrics.peak_memory_mb:.0f}")- print(f"Error rate: {metrics.error_rate:.2%}")- ```- </Tab>- <Tab title="Regression Tracking">- Store runs and compare metrics across pipeline versions:-- ```python- from semantica.evals import RegressionTracker-- tracker = RegressionTracker(db_path="eval_history.db")-- # Record a run with version tag and full config snapshot- run_id = tracker.record_run(- pipeline_version="v1.2.0",- metrics=metrics,- config=config.to_dict(),- )-- # Compare to a previous run- diff = tracker.compare(run_id, baseline_run_id="run_abc123")- for metric, change in diff.items():- direction = "↑" if change > 0 else "↓"- print(f" {metric}: {direction} {abs(change):.2%}")- ```- </Tab>-</Tabs>--## When to Evaluate+<Warning>+ **`semantica.evals` is not yet implemented.** The module exists as a placeholder (`__all__ = []`). No classes or functions are available for import. This page describes the planned API.+</Warning>-| Trigger | Evaluator to Use | What to Check |-| ------- | ---------------- | ------------- |-| New extraction model or method | `ExtractionEvaluator` | Precision, recall, F1 vs gold standard |-| After changing LLM provider | `ExtractionEvaluator` | Per-type F1 — check if rare types regressed |-| Before releasing new pipeline version | `PipelineEvaluator` | Throughput, latency, error rate |-| After deduplication strategy change | `KGEvaluator` | Orphan count, consistency score |-| Every production deployment | `RegressionTracker` | Compare vs previous baseline run |+## Planned Features-## Tips and Common Pitfalls+When released, `semantica.evals` will provide:-<Warning>- **Build a gold standard dataset early.** `ExtractionEvaluator` requires annotated ground truth. Without it, you're evaluating subjectively. Even 100 carefully annotated documents give you a meaningful baseline to track regressions against.-</Warning>+- **KG quality metrics** — completeness, consistency, schema compliance, coverage, and orphan node detection+- **Extraction accuracy** — NER precision / recall / F1 and relation extraction metrics against gold-standard datasets+- **Pipeline benchmarking** — throughput (docs/sec), per-step latency, peak memory, and error rate+- **Regression tracking** — record runs and compare metrics across commits or config changes+- **Deduplication accuracy** — merge precision, false positive / false negative rates+- **Reasoning correctness** — inference accuracy, rule coverage, and derivation depth-<Tip>- **Evaluate per entity type, not just overall F1.** Aggregate F1 can hide regressions — if your model's PERSON F1 drops from 0.95 to 0.80 but ORGANIZATION improves, the average may look stable. Use `report.per_type_metrics` to catch type-specific regressions.-</Tip>+## Current Workaround-<Tip>- **Store every benchmark run with `RegressionTracker`.** Run ID + version tag + config snapshot gives you a reproducible audit trail. Without it, "did the last release make things better?" has no objective answer.-</Tip>+Until `semantica.evals` ships, use `semantica.ontology.OntologyEvaluator` for ontology quality metrics:-<Tip>- **Run `PipelineEvaluator` with `warmup_runs=2`.** Cold starts are unrepresentative — model weights get cached, JIT compilation kicks in. Warmup runs eliminate this noise from your benchmark numbers.-</Tip>+```python+from semantica.ontology import OntologyEvaluator-<Warning>- **`KGEvaluator` needs an ontology for consistency scoring.** Without an ontology, `consistency` always returns 1.0 — there's nothing to check against. Pass `ontology=ontology` to get meaningful consistency metrics.-</Warning>+evaluator = OntologyEvaluator()+report = evaluator.evaluate(ontology, kg)+print(f"Coverage: {report.coverage:.2%}")+print(f"Completeness: {report.completeness:.2%}")+```<CardGroup cols={2}><Card title="Semantic Extract" icon="magnifying-glass" href="semantic_extract">- Extraction module to evaluate.+ Extraction module.</Card><Card title="Knowledge Graph" icon="diagram-project" href="kg">Graph quality assessment.@@ -232,7 +44,7 @@ icon: "chart-line"<Card title="Pipeline" icon="gear" href="pipeline">Pipeline performance metrics.</Card>- <Card title="Deduplication" icon="copy" href="deduplication">- Deduplication accuracy evaluation.+ <Card title="Ontology Evaluator" icon="sitemap" href="ontology">+ Available now for ontology quality metrics.</Card></CardGroup>diff --git a/docs/reference/explorer.md b/docs/reference/explorer.mdindex 0389d42b..c89448a8 100644--- a/docs/reference/explorer.md+++ b/docs/reference/explorer.md@@ -40,52 +40,34 @@ Requires `uvicorn` and `fastapi`. Included automatically with `pip install seman## Launch<Steps>- <Step title="Build your graph and launch Explorer">+ <Step title="Save your graph and launch Explorer">```python- from semantica.explorer import start_explorer+ import jsonfrom semantica.kg import GraphBuilder- from semantica.ontology import OntologyManager-- kg = GraphBuilder().build(entities=entities, relationships=relationships)- ontology = OntologyManager()-- start_explorer(- graph=kg,- ontology=ontology, # optional — enables Ontology Hub tab- port=8080,- host="127.0.0.1",- open_browser=True,- )- # → Serving at http://127.0.0.1:8080++ kg = GraphBuilder().build(entities=entities, relationships=relationships)++ # Export graph to JSON file+ with open("my_graph.json", "w") as f:+ json.dump({"entities": kg.entities, "relationships": kg.relationships}, f)```- </Step>- <Step title="Or launch from the CLI">+```bash- # Start on a saved graphsemantica-explorer --graph my_graph.json-- # Custom host and port+ # → Serving at http://127.0.0.1:8000+ ```+ </Step>+ <Step title="Custom host and port">+ ```bashsemantica-explorer --graph my_graph.json --host 0.0.0.0 --port 8080# Skip auto-opening the browsersemantica-explorer --graph my_graph.json --no-browser```</Step>- <Step title="Enable authentication for shared environments">- ```python- start_explorer(- graph=kg,- port=8080,- enable_auth=True,- api_key="my-secret-key",- cors_origins=["https://app.example.com"],- session_timeout=1800, # 30-minute inactivity timeout- )- ```- </Step><Step title="Switch graphs without restarting">```bash- curl -X POST http://localhost:8080/api/import \+ curl -X POST http://localhost:8000/api/import \-H "Content-Type: multipart/form-data" \-F "file=@updated_graph.json"# Browser dashboard reloads automatically@@ -93,21 +75,6 @@ Requires `uvicorn` and `fastapi`. Included automatically with `pip install seman</Step></Steps>-## `start_explorer()` Parameters--| Parameter | Type | Default | Description |-| --------- | ---- | ------- | ----------- |-| `graph` | `KnowledgeGraph` or `ContextGraph` | *(required)* | The graph to load into Explorer |-| `ontology` | `OntologyManager` | `None` | Ontology to load into the Ontology Hub tab |-| `port` | `int` | `8000` | Port to bind the server |-| `host` | `str` | `"127.0.0.1"` | Host to bind. Use `"0.0.0.0"` for network access |-| `open_browser` | `bool` | `True` | Auto-open the dashboard in the default browser |-| `session_timeout` | `int` | `3600` | Session inactivity timeout in seconds; `None` disables |-| `enable_auth` | `bool` | `False` | Require `X-API-Key` header on all API requests |-| `api_key` | `str` | `None` | API key value when `enable_auth=True` |-| `cors_origins` | `list[str]` | `["*"]` | Allowed CORS origins. Restrict in production |-| `log_level` | `str` | `"info"` | Uvicorn log level (`"debug"` / `"info"` / `"warning"`) |-## CLI Reference| Flag | Default | Description |@@ -154,15 +121,6 @@ Requires `uvicorn` and `fastapi`. Included automatically with `pip install seman<Tab title="Session Management">Thread-safe sessions with rollback protection:- ```python- start_explorer(- graph=kg,- session_timeout=1800, # 30-minute inactivity timeout- enable_auth=True,- api_key="my-secret-key",- )- ```-- Sessions are per connected browser tab- Write operations (annotate, import) roll back automatically on failure- All writes appended to audit trail at `/api/provenance/audit`@@ -296,12 +254,12 @@ WebSocket event schema:| SPARQL SELECT (simple pattern) | < 20ms || N×N distance matrix (100 nodes) | ~2s (with embedding cache) |-The node search index is built on startup. For graphs > 500k nodes, pass `index_build_timeout=120` to `start_explorer()` to allow more time.+The node search index is built on startup. For graphs > 500k nodes, allow extra startup time before connecting.## Tips and Common Pitfalls<Warning>- **Set `max_nodes` when loading large graphs.** `start_explorer(graph=kg, max_nodes=50000)` limits the rendered node count — Explorer's force-directed layout becomes unusable above ~10k nodes without limiting. Use `graph.filter(node_type="Organization")` first to focus on what matters.+ **Filter large graphs before saving to JSON.** The CLI loads the entire JSON file into memory. For graphs > 10k nodes, filter to the relevant subgraph (e.g., by entity type) before exporting to JSON — Explorer's force-directed layout becomes unusable on very large graphs.</Warning><Warning>diff --git a/docs/reference/ingest.md b/docs/reference/ingest.mdindex af0c9e52..8f28de6b 100644--- a/docs/reference/ingest.md+++ b/docs/reference/ingest.md@@ -150,16 +150,12 @@ icon: "database"from semantica.ingest import WebIngestoringestor = WebIngestor(- rate_limit=1.0, # seconds between requests+ delay=1.0, # seconds between requestsrespect_robots=True, # honor robots.txt- max_depth=2 # crawl depth from seed URLs+ timeout=30,)- sources = ingestor.ingest("https://example.com/about")- sources = ingestor.ingest_urls([- "https://example.com/page1",- "https://example.com/page2",- ])+ sources = ingestor.ingest_url("https://example.com/about")```### FeedIngestor (RSS/Atom)@@ -168,13 +164,12 @@ icon: "database"from semantica.ingest import FeedIngestoringestor = FeedIngestor()- sources = ingestor.ingest("https://feeds.example.com/rss")+ feed = ingestor.ingest_feed("https://feeds.example.com/rss")- # Live monitoring — callback fires on new items- ingestor.monitor(- "https://feeds.example.com/rss",- interval=300,- callback=process_new_items+ # Live monitoring — returns a FeedMonitor; callback fires on new items+ monitor = ingestor.monitor_feeds(+ ["https://feeds.example.com/rss"],+ callback=process_new_items,)```@@ -264,11 +259,11 @@ icon: "database"```pythonfrom semantica.ingest import DBIngestor- ingestor = DBIngestor(+ ingestor = DBIngestor()+ result = ingestor.ingest_database(connection_string="postgresql://user:pass@localhost/db",- query="SELECT id, content, created_at FROM documents WHERE status='active'"+ include_tables=["documents"],)- sources = ingestor.ingest()```### SnowflakeIngestor@@ -283,9 +278,10 @@ icon: "database"password=os.getenv("SNOWFLAKE_PASSWORD"),warehouse="COMPUTE_WH",database="ANALYTICS",- schema="PUBLIC"+ schema="PUBLIC",)- sources = ingestor.ingest(query="SELECT * FROM documents")+ result = ingestor.ingest_query("SELECT * FROM documents")+ result = ingestor.ingest_table("documents")```</Tab>@@ -297,48 +293,32 @@ icon: "database"```pythonfrom semantica.ingest import StreamIngestor- # Kafka- ingestor = StreamIngestor(- backend="kafka",- bootstrap_servers="localhost:9092",+ ingestor = StreamIngestor()++ # Kafka — returns KafkaProcessor+ processor = ingestor.ingest_kafka(topic="documents",- group_id="semantica-consumer",- auto_offset_reset="earliest",+ bootstrap_servers=["localhost:9092"],)- sources = ingestor.ingest(max_messages=1000)- # RabbitMQ- ingestor = StreamIngestor(- backend="rabbitmq",- host="localhost",+ # RabbitMQ — returns RabbitMQProcessor+ processor = ingestor.ingest_rabbitmq(queue="document_queue",- routing_key="docs.ingest",- prefetch_count=100,+ connection_url="amqp://guest:guest@localhost/",)- # AWS Kinesis- ingestor = StreamIngestor(- backend="kinesis",+ # AWS Kinesis — returns KinesisProcessor+ processor = ingestor.ingest_kinesis(stream_name="documents-stream",region="us-east-1",- shard_iterator_type="TRIM_HORIZON",)- # Apache Pulsar- ingestor = StreamIngestor(- backend="pulsar",- service_url="pulsar://localhost:6650",+ # Apache Pulsar — returns PulsarProcessor+ processor = ingestor.ingest_pulsar(topic="persistent://public/default/documents",- subscription_name="semantica-sub",+ service_url="pulsar://localhost:6650",)-- # Live monitoring — callback fires on each new message- ingestor.monitor(callback=process_document, poll_interval=1.0)```-- <Warning>- Without a `max_messages` limit, `StreamIngestor.ingest()` blocks indefinitely waiting for new messages. Use `max_messages=1000` for batch processing; use `.monitor(callback=...)` for continuous streaming.- </Warning></Tab></Tabs>@@ -349,23 +329,21 @@ Ingest existing OWL or RDF ontology files as structured knowledge sources:```pythonfrom semantica.ingest import OntologyIngestor-ingestor = OntologyIngestor(- format="turtle", # "turtle" | "xml" | "json-ld" | "nt" | "n3"-)+ingestor = OntologyIngestor()-sources = ingestor.ingest("domain_ontology.owl")-sources = ingestor.ingest("ontologies/")+ontology_data = ingestor.ingest_ontology("domain_ontology.owl", format="turtle")+ontology_list = ingestor.ingest_directory("ontologies/", recursive=True)```-## DataSource Object+## FileObject-All ingestors return a list of `DataSource` objects with a consistent schema:+`FileIngestor` returns `FileObject` instances:-<Accordion title="DataSource schema">+<Accordion title="FileObject schema">```python@dataclass-class DataSource:+class FileObject:content: str # raw text contentsource_id: str # unique identifiersource_type: str # "file" | "web" | "database" | "stream" | ...@@ -402,16 +380,8 @@ method_registry.register("file", "my_format", my_ingestor)**`XMLIngestor` is XXE-safe by default.** Do not use standard `xml.etree.ElementTree` to pre-parse XML before passing to Semantica — it doesn't block XXE attacks. `XMLIngestor` uses lxml with `resolve_entities=False` to safely parse untrusted XML.</Warning>-<Warning>- **Stream ingestors need explicit `max_messages` for batch runs.** Without a limit, `StreamIngestor.ingest()` blocks indefinitely waiting for new messages. Use `max_messages=1000` for batch processing; use `.monitor(callback=...)` for continuous streaming.-</Warning>--<Tip>- **Rate-limit web crawling.** `WebIngestor(rate_limit=1.0, respect_robots=True)` is the responsible default. Without rate limiting, you risk getting blocked by the target server or violating its terms of service.-</Tip>-<Tip>- **All ingestors return the same `DataSource` schema.** This means you can mix sources in a single pipeline without any adapter code — `FileIngestor`, `DBIngestor`, and `StreamIngestor` outputs are all directly composable with `DocumentParser` and `NERExtractor`.+ **Rate-limit web crawling.** `WebIngestor(delay=1.0, respect_robots=True)` is the responsible default. Without rate limiting, you risk getting blocked by the target server or violating its terms of service.</Tip><CardGroup cols={2}>diff --git a/docs/reference/kg.md b/docs/reference/kg.mdindex 3b72c8d9..683e8fdc 100644--- a/docs/reference/kg.md+++ b/docs/reference/kg.md@@ -12,11 +12,11 @@ icon: "diagram-project"<Card title="GraphBuilder" icon="hammer">Construct graphs from entities and relationships with automatic entity merging.</Card>- <Card title="TemporalKnowledgeGraph" icon="clock">- Time-aware edges (`valid_from`/`valid_until`) and point-in-time queries (v0.4.0).+ <Card title="TemporalGraphQuery" icon="clock">+ Time-aware queries — filter by `valid_from`/`valid_until`, range queries, and evolution analysis.</Card>- <Card title="DistanceCalculator" icon="ruler">- Semantic neighborhoods, N×N distance matrices, and distance band classification (v0.5.0).+ <Card title="ConnectivityAnalyzer" icon="circle-nodes">+ Connected components, bridge detection, and edge density analysis.</Card><Card title="CentralityCalculator" icon="star">PageRank, degree, betweenness, closeness, and eigenvector centrality.@@ -104,60 +104,40 @@ kg = builder.build(entities=entities, relationships=relationships)Always use `merge_entities=True` in production. Without it, "Steve Jobs" extracted from five different documents creates five separate person nodes. `GraphBuilder(merge_entities=True)` uses edit distance matching to consolidate them at build time.</Warning>-## Temporal Knowledge Graphs (v0.4.0)+## Temporal Queries-Attach `valid_from` / `valid_until` time windows to nodes and edges for point-in-time queries and historical analysis:+Use `TemporalGraphQuery` to run time-aware queries against a knowledge graph whose relationships carry `valid_from` / `valid_until` fields:```python-from semantica.kg import TemporalKnowledgeGraph, TemporalGraphQuery+from semantica.kg import TemporalGraphQueryfrom datetime import datetime-tkg = TemporalKnowledgeGraph()--tkg.add_node("ceo_role", valid_from=datetime(2020, 1, 1), valid_until=datetime(2023, 6, 1))-tkg.add_edge(- "alice", "acme_corp", "ceo_of",- valid_from=datetime(2020, 1, 1),- valid_until=datetime(2023, 6, 1)+query_engine = TemporalGraphQuery(+ enable_temporal_reasoning=True,+ temporal_granularity="day",)-# Point-in-time snapshot-snapshot = tkg.at(datetime(2021, 6, 15))--# Query and diff via TemporalGraphQuery-query = TemporalGraphQuery(tkg)-snap_2020 = query.query_at_time(datetime(2020, 1, 1))-snap_2023 = query.query_at_time(datetime(2023, 1, 1))-added = [r for r in snap_2023.relationships if r not in snap_2020.relationships]-print(f"New edges since 2020: {len(added)}")-```--<Note>- Edges added without `valid_from`/`valid_until` are treated as **always-valid**. For historical data, always attach timestamps — otherwise point-in-time queries return misleading results.-</Note>+# Point-in-time query — returns only edges valid at the given time+result_2021 = query_engine.query_at_time(kg, query="", at_time=datetime(2021, 6, 15))+result_2023 = query_engine.query_at_time(kg, query="", at_time=datetime(2023, 1, 1))-## Distance Intelligence (v0.5.0)+# Compare what changed between two snapshots+added = [+ r for r in result_2023["relationships"]+ if r not in result_2021["relationships"]+]+print(f"New edges since 2021: {len(added)}")-Semantic neighborhood exploration for any entity in the graph:--```python-from semantica.kg import DistanceCalculator+# Range query — edges valid within a time window+range_result = query_engine.query_time_range(kg, query="", start_time=datetime(2020, 1, 1), end_time=datetime(2023, 1, 1))-calc = DistanceCalculator(kg)--# Semantic neighborhood of a single node-neighborhood = calc.semantic_neighborhood("Apple Inc.", radius=0.4)--# N×N pairwise distance matrix-matrix = calc.distance_matrix(["Apple Inc.", "Google", "Microsoft"])--# Classify nodes into distance bands: "near" | "mid" | "far"-bands = calc.classify_bands(neighborhood)+# Evolution analysis+evolution = query_engine.analyze_evolution(kg)```-<Warning>- `DistanceCalculator` is expensive at large scale — the N×N matrix requires embedding all entities and computing pairwise cosine similarities. Cache the result between runs and only recompute for changed entities.-</Warning>+<Note>+ Relationships added without `valid_from`/`valid_until` are treated as **always-valid**. For historical data, always attach timestamps — otherwise point-in-time queries return misleading results.+</Note>## Graph Analyticsdiff --git a/docs/reference/llms.md b/docs/reference/llms.mdindex 4b27127a..55b8fea6 100644--- a/docs/reference/llms.md+++ b/docs/reference/llms.md@@ -15,8 +15,8 @@ icon: "microchip"<Card title="Unified LLMProvider Interface" icon="arrows-left-right">`complete()`, `chat()`, and `stream()` work identically across all providers — swap with a one-line change.</Card>- <Card title="create_provider() Factory" icon="gear">- Instantiate any provider from a name string — drive provider selection entirely from YAML config or environment variables.+ <Card title="LiteLLM (100+ Models)" icon="gear">+ One class, every provider — Anthropic, Gemini, Ollama, DeepSeek, Azure, Bedrock, and 90+ more via LiteLLM model strings.</Card><Card title="Local Inference" icon="server">Ollama and HuggingFace run fully on-premise — no API key, no data leaves your machine, air-gap compatible.@@ -69,14 +69,15 @@ The base install includes Groq and DeepSeek. Other providers require optional exentities = ner.extract("Apple Inc. was founded by Steve Jobs in 1976.")```</Step>- <Step title="Use create_provider() for config-driven selection">+ <Step title="Use LiteLLM for config-driven provider selection">```python- from semantica.llms import create_provider+ from semantica.llms import LiteLLMfrom semantica.core import ConfigManagerconfig = ConfigManager("config.yaml")- llm = create_provider(- config.get("llm_provider.name"),+ # LiteLLM model strings include the provider prefix:+ # "anthropic/claude-opus-4-7", "gemini/gemini-1.5-pro", "ollama/llama3.2"+ llm = LiteLLM(model=config.get("llm_provider.model"),api_key=config.get("llm_provider.api_key"),)@@ -117,69 +118,77 @@ llm = OpenAI()```-```python Anthropic-from semantica.llms import Anthropic+```python Anthropic (via LiteLLM)+from semantica.llms import LiteLLMimport os-llm = Anthropic(- model="claude-opus-4-7",+# Anthropic Claude is accessed via LiteLLM using the "anthropic/" prefix+llm = LiteLLM(+ model="anthropic/claude-opus-4-7",api_key=os.getenv("ANTHROPIC_API_KEY"),max_tokens=8192,temperature=0.0,- max_retries=3,- timeout=120,)```-```python Gemini-from semantica.llms import Gemini+```python Gemini (via LiteLLM)+from semantica.llms import LiteLLMimport os-llm = Gemini(- model="gemini-1.5-pro",+# Google Gemini is accessed via LiteLLM using the "gemini/" prefix+llm = LiteLLM(+ model="gemini/gemini-1.5-pro",api_key=os.getenv("GOOGLE_API_KEY"),temperature=0.0,max_tokens=8192,- timeout=120,)```-```python Ollama (Local)-from semantica.llms import Ollama+```python Ollama / Local (via LiteLLM)+from semantica.llms import LiteLLM-llm = Ollama(- model="llama3.2",- base_url="http://localhost:11434", # default Ollama address+# Ollama local models via LiteLLM using the "ollama/" prefix+llm = LiteLLM(+ model="ollama/llama3.2",+ base_url="http://localhost:11434", # default Ollama addresstemperature=0.0,- timeout=180, # local models can be slower; increase for large models+ timeout=180, # local models can be slower; increase for large models)# No API key — model runs entirely on your machine```-```python DeepSeek-from semantica.llms import DeepSeek+```python DeepSeek (via Groq or LiteLLM)+from semantica.llms import Groq # Groq hosts DeepSeek modelsimport os-llm = DeepSeek(- model="deepseek-chat",+llm = Groq(+ model="deepseek-r1-distill-llama-70b",+ api_key=os.getenv("GROQ_API_KEY"),+ temperature=0.0,+ max_tokens=4096,+)++# Or via LiteLLM for the native DeepSeek endpoint:+from semantica.llms import LiteLLM+llm = LiteLLM(+ model="deepseek/deepseek-chat",api_key=os.getenv("DEEPSEEK_API_KEY"),temperature=0.0,max_tokens=4096,- max_retries=3,)```-```python Novita AI-from semantica.llms import NovitaAI+```python Novita AI (via LiteLLM)+from semantica.llms import LiteLLMimport os-llm = NovitaAI(- model="deepseek/deepseek-v3.2",+# Novita AI via LiteLLM using the "novita/" prefix+llm = LiteLLM(+ model="novita/deepseek/deepseek-v3",api_key=os.getenv("NOVITA_API_KEY"),temperature=0.0,max_tokens=4096,)-# OpenAI-compatible endpoint; also accepts deepseek/deepseek-r1, meta-llama models``````python LiteLLM (100+ models)@@ -193,13 +202,13 @@ llm = LiteLLM(max_tokens=4096,)# Supports: OpenAI, Anthropic, Gemini, Cohere, Azure, Bedrock, Together AI, and 90+ more-# Use the LiteLLM model string format: "anthropic/claude-3-5-sonnet", "bedrock/anthropic.claude-v2"+# Use the LiteLLM model string format: "anthropic/claude-opus-4-7", "bedrock/anthropic.claude-v2"``````python HuggingFace (Local)-from semantica.llms import HuggingFace+from semantica.llms import HuggingFaceLLM-llm = HuggingFace(+llm = HuggingFaceLLM(model="mistralai/Mistral-7B-Instruct-v0.3",device="cuda", # "cpu" | "cuda" | "mps" (Apple Silicon)max_new_tokens=512,@@ -231,11 +240,11 @@ llm = HuggingFace(| -------- | --------- | ----------- || `OpenAI` | `organization` | OpenAI organisation ID || `OpenAI` | `project` | OpenAI project ID |-| `Ollama` | `base_url` | Ollama server address (default: `http://localhost:11434`) |-| `HuggingFace` | `device` | Compute device: `"cpu"` / `"cuda"` / `"mps"` |-| `HuggingFace` | `load_in_4bit` | Enable 4-bit quantisation (requires `bitsandbytes`) |-| `HuggingFace` | `max_new_tokens` | Maximum new tokens to generate (replaces `max_tokens`) |-| `LiteLLM` | `model` | Full LiteLLM model string, e.g. `"anthropic/claude-3-5-sonnet"` |+| `LiteLLM` | `model` | Full LiteLLM model string, e.g. `"anthropic/claude-opus-4-7"`, `"gemini/gemini-1.5-pro"`, `"ollama/llama3.2"` |+| `LiteLLM` | `base_url` | Override endpoint — use for Ollama (`http://localhost:11434`) or proxies |+| `HuggingFaceLLM` | `device` | Compute device: `"cpu"` / `"cuda"` / `"mps"` |+| `HuggingFaceLLM` | `load_in_4bit` | Enable 4-bit quantisation (requires `bitsandbytes`) |+| `HuggingFaceLLM` | `max_new_tokens` | Maximum new tokens to generate (replaces `max_tokens`) |## Direct API Usagediff --git a/docs/reference/ontology.md b/docs/reference/ontology.mdindex d387ccdc..52383ade 100644--- a/docs/reference/ontology.md+++ b/docs/reference/ontology.md@@ -1,72 +1,64 @@---title: "Ontology Module"-description: "Automated ontology generation, SHACL validation, SKOS vocabularies, alignment, diff/migration, and the visual Ontology Hub."+description: "Automated ontology generation, OWL export, SHACL validation, domain ontologies, and modular ontology development."icon: "sitemap"----`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.+`semantica.ontology` provides the full lifecycle for knowledge graph schemas — from auto-generation and OWL export to SHACL validation and modular ontology development. Use it for schema design, data modeling, and semantic web interoperability.## What You Get<CardGroup cols={2}>- <Card title="OntologyManager" icon="sitemap">- Define classes, properties, relationships, and constraints for your knowledge graph schema.- </Card><Card title="OntologyGenerator" icon="wand-magic-sparkles">Auto-generate ontologies from existing graph data using a 6-stage pipeline.</Card>- <Card title="SHACLGenerator / SHACLValidator" icon="shield-check">- Generate SHACL shapes from an ontology and validate graphs for constraint compliance.+ <Card title="SHACLGenerator / OntologyValidator" icon="shield-check">+ Generate SHACL shapes from an ontology and validate ontologies for structural consistency.+ </Card>+ <Card title="CompetencyQuestionsManager" icon="circle-question">+ Capture, manage, and validate competency questions that define ontology requirements.</Card>- <Card title="SKOSVocabulary" icon="list-tree">- Controlled vocabulary and taxonomy management using the W3C SKOS standard.+ <Card title="ReuseManager" icon="arrows-left-right">+ Integrate published ontologies (schema.org, FOAF) instead of generating from scratch.</Card>- <Card title="OntologyAligner" icon="arrows-left-right">- Align and merge ontologies across schemas — maps concepts with confidence scores.+ <Card title="DomainOntologies" icon="list-tree">+ Pre-built domain ontologies for biomedical, finance, legal, supply chain, and more.</Card>- <Card title="Ontology Hub (v0.5.0)" icon="display">- Visual browser UI for the full ontology lifecycle — editor, SHACL Studio, and health dashboard.+ <Card title="OntologyEvaluator" icon="chart-bar">+ Measure coverage, completeness, and granularity — validate against competency questions.</Card></CardGroup>## Quick Start<Steps>- <Step title="Define your schema">+ <Step title="Generate an ontology from your knowledge graph">```python- from semantica.ontology import OntologyManager+ from semantica.ontology import OntologyGenerator- ontology = OntologyManager()- ontology.add_class("Person", properties=["name", "birth_date"])- ontology.add_class("Organization", properties=["name", "founded_date"])- ontology.add_relationship("works_for", domain="Person", range="Organization")- ontology.add_constraint("Person", "must_have_name")+ generator = OntologyGenerator()+ ontology = generator.generate_from_graph(kg)```</Step>- <Step title="Validate your graph against the schema">+ <Step title="Validate the ontology">```python- is_valid = ontology.validate_graph(kg)+ from semantica.ontology import OntologyValidator- # Or use SHACL for granular constraint reporting- from semantica.ontology import SHACLGenerator, SHACLValidator+ validator = OntologyValidator(reasoner="hermit", check_consistency=True)+ result = validator.validate(ontology)- shapes = SHACLGenerator().generate(ontology)- validator = SHACLValidator()- report = validator.validate(kg, shapes=shapes)-- if not report.conforms:- for v in report.violations:- print(f"Violation: {v.message} on {v.node} (path: {v.path})")+ if not result.is_valid:+ for issue in result.issues:+ print(f"Issue: {issue.message} (severity: {issue.severity})")```</Step><Step title="Export to OWL">```python- from semantica.ontology import OWLExporter+ from semantica.ontology import OWLGenerator- exporter = OWLExporter()- 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")+ owl_gen = OWLGenerator()+ owl_gen.export_owl(ontology, file_path="ontology.ttl", format="turtle")+ owl_gen.export_owl(ontology, file_path="ontology.owl", format="xml")```</Step></Steps>@@ -148,59 +140,6 @@ The pipeline runs through these stages in order:</Step></Steps>-## SKOS Vocabularies--Build controlled vocabularies and taxonomies using the W3C SKOS standard:--```python-from semantica.ontology import SKOSVocabulary--vocab = SKOSVocabulary()-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--<Tabs>- <Tab title="Align Two Ontologies">- Map concepts across two ontologies:-- ```python- from semantica.ontology import 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})")-- merged = aligner.merge(source_ontology, target_ontology, alignment)- ```- </Tab>- <Tab title="Diff and Migration">- Compare versions and generate migration scripts:-- ```python- from semantica.ontology import OntologyDiff, OntologyMigrator-- diff = OntologyDiff()- changes = diff.compare(ontology_v1, ontology_v2)-- for change in changes:- print(f"{change.type}: {change.element} — {change.description}")-- migrator = OntologyMigrator()- migration_script = migrator.generate_migration(changes)- migrator.apply(kg, migration_script)- ```- </Tab>-</Tabs>-## Advanced Generation Tools<Tabs>@@ -351,20 +290,15 @@ for q, result in zip(questions, cq_results):## Ontology Hub (v0.5.0)-A visual browser UI for the full ontology lifecycle, served by `semantica.explorer`:+A visual browser UI for the full ontology lifecycle, served by the Explorer CLI:```bashpip install "semantica[explorer]"-```--```python-from semantica.explorer import start_explorer--start_explorer(graph=kg, port=8080)+semantica explore# Navigate to http://localhost:8080 → Ontology Hub tab```-Features: visual editor, SHACL Studio, alignment authoring, health dashboard, and version control.+Features: visual editor, SHACL Studio, health dashboard, and version control.## Tips and Common Pitfalls@@ -381,7 +315,7 @@ Features: visual editor, SHACL Studio, alignment authoring, health dashboard, an</Warning><Warning>- **Always validate with SHACL after schema changes.** When you add new classes or properties, run `SHACLValidator.validate(kg, shapes)` immediately. SHACL violations often surface data quality issues that were silently passing before.+ **Always validate after schema changes.** When you add new classes or properties, run `OntologyValidator.validate(ontology)` immediately. Validation issues often surface data quality problems that were silently passing before.</Warning><Tip>@@ -392,10 +326,6 @@ Features: visual editor, SHACL Studio, alignment authoring, health dashboard, an**Namespace your terms consistently.** All classes and properties need stable IRIs. Use `NamespaceManager` to generate them programmatically — never hardcode IRI strings in code, because base URIs change when projects move.</Tip>-<Warning>- **Diff before migration.** Always run `OntologyDiff.compare()` before `OntologyMigrator.apply()`. The diff shows exactly which graph entities will be affected — some migrations (renaming a class) require updating thousands of existing nodes.-</Warning>-<CardGroup cols={2}><Card title="Reasoning" icon="microchip" href="reasoning">Apply inference rules over ontology axioms.diff --git a/docs/reference/provenance.md b/docs/reference/provenance.mdindex bd782c3d..8cc594c1 100644--- a/docs/reference/provenance.md+++ b/docs/reference/provenance.md@@ -12,8 +12,8 @@ icon: "link"<Card title="ProvenanceManager" icon="link">Track entities, relationships, and activities with full source attribution and confidence scores.</Card>- <Card title="ActivityTracker" icon="clock">- Record pipeline activities and which entities they produced or consumed.+ <Card title="ProvenanceTracker" icon="clock">+ Track entity and relationship lineage within a knowledge graph.</Card><Card title="Lineage Graph" icon="diagram-project">Full directed lineage from any entity back to its originating source document.diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.mdindex 0594fc49..9e3d91db 100644--- a/docs/reference/semantic_extract.md+++ b/docs/reference/semantic_extract.md@@ -64,7 +64,7 @@ icon: "magnifying-glass-chart"<Card title="TripletExtractor" icon="table">Direct `(subject, predicate, object)` triplet generation for RDF-ready output.</Card>- <Card title="EventExtractor" icon="calendar">+ <Card title="EventDetector" icon="calendar">Event detection with participants, temporal context, and confidence scores.</Card><Card title="CoreferenceResolver" icon="link">@@ -215,14 +215,14 @@ triplets = trip.extract(text)Triplets are suitable for loading directly into a triplet store or knowledge graph without a separate relation extraction step.-## EventExtractor+## EventDetectorDetect events with participants and temporal context:```python-from semantica.semantic_extract import EventExtractor+from semantica.semantic_extract import EventDetector-extractor = EventExtractor(method="llm", llm_provider=llm)+extractor = EventDetector(method="llm", llm_provider=llm)events = extractor.extract(text)```diff --git a/docs/reference/triplet_store.md b/docs/reference/triplet_store.mdindex fd3d53a2..79011323 100644--- a/docs/reference/triplet_store.md+++ b/docs/reference/triplet_store.md@@ -12,8 +12,8 @@ icon: "table"<Card title="TripletStore" icon="server">Unified interface across Blazegraph, Apache Jena (Fuseki), and RDF4J — swap backends with one parameter.</Card>- <Card title="InMemoryTripletStore" icon="bolt">- Zero-setup in-memory store for unit tests and small datasets — no server, no Docker required.+ <Card title="TripletStore (in-memory)" icon="bolt">+ Zero-setup in-memory mode via `backend="memory"` for unit tests and small datasets — no server required.</Card><Card title="SPARQL" icon="magnifying-glass">Full SELECT, CONSTRUCT, ASK, and UPDATE query support with pagination for large result sets.@@ -138,30 +138,6 @@ icon: "table"Best for: Enterprise Java ecosystems, Eclipse Foundation deployments, plugin-based reasoning.</Tab>- <Tab title="InMemory">- ```python- from semantica.triplet_store import InMemoryTripletStore-- store = InMemoryTripletStore()-- store.add_triplet("ex:alice", "ex:knows", "ex:bob")- store.add_triplet("ex:bob", "ex:works_for", "ex:acme")-- results = store.sparql("""- SELECT ?person ?company WHERE {- ?person ex:works_for ?company .- }- """)-- # Serialize to string for inspection- ttl = store.export_to_string(format="turtle")- print(ttl)- ```-- `InMemoryTripletStore` shares the same interface as `TripletStore` — swap backends without changing query code.-- Best for: unit tests, CI pipelines, small datasets, zero-infrastructure local exploration.- </Tab><Tab title="Backend Comparison">| Backend | License | OWL Reasoning | Hosted Option | Best For |@@ -305,7 +281,7 @@ results = store.sparql("SELECT * WHERE { ?s ?p ?o } LIMIT 10")## Tips and Common Pitfalls<Tip>- **Use `InMemoryTripletStore` for unit tests, Jena or Blazegraph for production.** The in-memory backend requires zero server setup and is safe for CI. It does not persist across process restarts — switch to a server-backed store before deploying. No code changes needed, just the `backend=` parameter.+ **Use Apache Jena (Fuseki) for development and Blazegraph for production.** Jena runs with a single Docker command, supports OWL reasoning natively, and requires no licence. Switch to Blazegraph for high-throughput workloads by changing the `backend=` parameter — no other code changes needed.</Tip><Warning>diff --git a/docs/reference/visualization.md b/docs/reference/visualization.mdindex 2a3f9027..39f5a541 100644--- a/docs/reference/visualization.md+++ b/docs/reference/visualization.md@@ -9,20 +9,17 @@ icon: "chart-bar"## What You Get<CardGroup cols={2}>- <Card title="GraphVisualizer" icon="diagram-project">- Interactive HTML (PyVis) and static image (Matplotlib) graph rendering with layout options.+ <Card title="KGVisualizer" icon="diagram-project">+ Interactive network and community graph rendering with force, hierarchical, and circular layouts.</Card><Card title="OntologyVisualizer" icon="sitemap">- Class hierarchy and property relationship visualization from any OntologyManager.+ Class hierarchy and property relationship visualization from any ontology.</Card><Card title="EmbeddingVisualizer" icon="vector-square">UMAP, t-SNE, and PCA dimensionality reduction plots for embedding cluster analysis.</Card><Card title="TemporalVisualizer" icon="clock">- Timeline views, animated evolution, snapshot comparison, and temporal pattern highlights.- </Card>- <Card title="DistanceVisualizer (v0.5.0)" icon="circle-nodes">- Ego-mode neighborhood views and N×N distance matrix heatmaps from Distance Intelligence.+ Timeline views, network evolution animation, snapshot comparison, and temporal pattern highlights.</Card><Card title="AnalyticsVisualizer" icon="chart-bar">Centrality rankings, community-colored graphs, and degree distribution histograms.@@ -34,37 +31,33 @@ icon: "chart-bar"<Steps><Step title="Render a knowledge graph">```python- from semantica.visualization import GraphVisualizer+ from semantica.visualization import KGVisualizer- viz = GraphVisualizer()+ viz = KGVisualizer(layout="force", color_scheme="default")- # Interactive HTML — opens in browser, supports hover and click- viz.visualize(graph, output="graph.html")+ # Interactive — opens in browser, supports hover and click+ viz.visualize_network(graph, output="interactive")```</Step><Step title="Apply layout and color options">```python- viz.visualize(+ viz = KGVisualizer(layout="force", color_scheme="vibrant")++ viz.visualize_network(graph,- output="graph.html",- layout="force_directed", # "force_directed" | "hierarchical" | "circular" | "spring"+ output="html",+ file_path="graph.html",node_color_by="type", # color nodes by entity type attribute- edge_label="relation", # show edge relationship labels- color_scheme="vibrant", # color palette — see Color Schemes section- max_nodes=500, # limit rendering for large graphs)```</Step><Step title="Export to static formats">```python# Static PNG — for reports and embedding in documents- viz.visualize(graph, output="graph.png", dpi=150)+ viz.visualize_network(graph, output="png", file_path="graph.png")# Vector SVG — for publications and scalable diagrams- viz.visualize(graph, output="graph.svg")-- # PDF — for print or compliance reports- viz.visualize(graph, output="graph.pdf")+ viz.visualize_network(graph, output="svg", file_path="graph.svg")```</Step></Steps>@@ -72,32 +65,34 @@ icon: "chart-bar"## Visualizers<Tabs>- <Tab title="GraphVisualizer">+ <Tab title="KGVisualizer">Interactive and static knowledge graph rendering:```python- from semantica.visualization import GraphVisualizer+ from semantica.visualization import KGVisualizer- viz = GraphVisualizer()+ viz = KGVisualizer(layout="force", color_scheme="default")- # Interactive HTML- viz.visualize(graph, output="graph.html")+ # Interactive — opens in browser+ viz.visualize_network(graph, output="interactive")- # Static PNG with custom DPI- viz.visualize(graph, output="graph.png", backend="matplotlib", dpi=150)+ # Save as HTML file+ viz.visualize_network(graph, output="html", file_path="graph.html")- # Display inline (Jupyter or default browser)- viz.show(graph)+ # Static PNG+ viz.visualize_network(graph, output="png", file_path="graph.png")++ # Community-colored graph+ viz.visualize_communities(graph, communities, file_path="communities.html")```- **Layout options:**+ **Layout options (`layout=`):**| Layout | Description | Best For || ------ | ----------- | -------- |- | `force_directed` | Physics simulation — clusters emerge naturally | General graphs |+ | `force` | 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 |</Tab><Tab title="OntologyVisualizer">Visualize class hierarchies and property relationships:@@ -122,10 +117,11 @@ icon: "chart-bar"viz = EmbeddingVisualizer()- viz.visualize(+ viz.visualize_2d_projection(embeddings=embeddings,labels=labels,- output="embeddings.html",+ output="interactive",+ file_path="embeddings.html",method="umap", # "umap" | "tsne" | "pca")```@@ -141,47 +137,20 @@ icon: "chart-bar"```pythonfrom semantica.visualization import TemporalVisualizer- from datetime import datetimeviz = TemporalVisualizer()- # Static timeline of additions and removals- viz.visualize_timeline(temporal_kg, output="timeline.html")+ # Timeline of entity/relationship changes+ viz.visualize_timeline(temporal_kg, output="interactive")- # Animated evolution — one frame per time step- viz.animate(temporal_kg, output="evolution.html", fps=2)+ # Animated network evolution — one frame per time step+ viz.visualize_network_evolution(temporal_kg, output="html", file_path="evolution.html")# Side-by-side snapshot comparison- snap_a = temporal_kg.at(datetime(2020, 1, 1))- snap_b = temporal_kg.at(datetime(2023, 1, 1))- viz.compare_snapshots(snap_a, snap_b, output="snapshot_diff.html")+ viz.visualize_snapshot_comparison(snap_a, snap_b, output="html", file_path="diff.html")- # Pattern visualization — highlight recurring temporal patterns- viz.visualize_patterns(temporal_kg, pattern_type="recurrence", output="patterns.html")- ```- </Tab>- <Tab title="DistanceVisualizer (v0.5.0)">- Semantic neighborhood and distance matrix visualization from Distance Intelligence:-- ```python- from semantica.visualization import DistanceVisualizer-- viz = DistanceVisualizer()-- # Ego-mode: neighborhood of one node colored by distance band- viz.visualize_ego(- graph,- center_node="Apple Inc.",- output="ego.html",- radius=0.5, # semantic distance radius- )-- # N×N distance matrix heatmap- viz.visualize_distance_matrix(- matrix=distance_matrix,- labels=node_labels,- output="distance_heatmap.html",- )+ # Recurring temporal patterns+ viz.visualize_temporal_patterns(temporal_kg, output="html", file_path="patterns.html")```</Tab><Tab title="AnalyticsVisualizer">@@ -245,13 +214,10 @@ viz.visualize(graph, output="graph.html", color_scheme="vibrant")## Graph Explorer (Full Dashboard)-For a full browser-based UI with search, path finding, and the Ontology Hub, use `semantica.explorer`:--```python-from semantica.explorer import start_explorer+For a full browser-based UI with search, path finding, and the Ontology Hub, launch the Explorer via the CLI:-start_explorer(graph=kg, port=8080)-# Opens at http://localhost:8080+```bash+semantica explore```See the [Explorer reference](explorer) for the full feature set and REST API.@@ -279,7 +245,7 @@ See the [Explorer reference](explorer) for the full feature set and REST API.</Warning><Tip>- **For interactive dashboards, prefer Explorer.** `GraphVisualizer.visualize()` generates a self-contained HTML file. `start_explorer()` gives a full live web app with search, filtering, path-finding, and REST API. Use Explorer for team exploration, Visualizer for standalone report embeds.+ **For interactive dashboards, prefer Explorer.** `KGVisualizer.visualize_network()` generates a self-contained HTML file. The Explorer CLI (`semantica explore`) gives a full live web app with search, filtering, path-finding, and REST API. Use Explorer for team exploration, Visualizer for standalone report embeds.</Tip><CardGroup cols={2}>