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
Merge branch 'main' into docs
Mohd Kaif35ebccbdd740
diff --cc README.mdindex 4e61f544,0b0ae144..e4560c20--- a/README.md+++ b/README.md@@@ -53,54 -57,194 +53,176 @@@ pip install semantic----## What's New in v0.3.0+## π What's New in v0.4.0-> First stable release β `Production/Stable` on PyPI. Ships across three stages: 0.3.0-alpha, 0.3.0-beta, and 0.3.0 stable.+**1,162+ tests Β· 0 failures Β· 0 regressions**-| Area | Highlights |-|------|-----------|-| **Context Graphs** | Temporal validity windows (`valid_from`/`valid_until`), weighted BFS (`min_weight`), cross-graph navigation (`link_graph`, `navigate_to`, `resolve_links`) with full save/load persistence |-| **Decision Intelligence** | Complete lifecycle: `record_decision` β `trace_decision_chain` β `analyze_decision_impact` β `find_similar_decisions`; hybrid precedent search; `PolicyEngine` with versioned rules |-| **KG Algorithms** | PageRank, betweenness, community detection (Louvain), Node2Vec embeddings, link prediction, path finding β all returning structured dicts |-| **Semantic Extraction** | LLM relation extraction fixed (no silent drops); `_match_pattern` rewritten; duplicate relation bug removed; `"llm_typed"` metadata corrected |-| **Deduplication v2** | `blocking_v2`/`hybrid_v2` candidate generation (**63.6% faster**); two-stage prefilter (**18β25% faster**); semantic dedup v2 (**6.98x faster**) |-| **Delta Processing** | SPARQL-based incremental diff; `delta_mode` pipelines; snapshot versioning with `prune_versions()` |-| **Export** | RDF format aliases (`"ttl"`, `"json-ld"`, etc.); ArangoDB AQL export; Apache Parquet export (Spark/BigQuery/Databricks ready) |-| **Pipeline** | `FailureHandler` with LINEAR/EXPONENTIAL/FIXED backoff; `PipelineValidator` returning `ValidationResult`; retry loop fixed |-| **Graph Backends** | Apache AGE (SQL injection fixed), AWS Neptune, FalkorDB, PgVector (HNSW/IVFFlat indexing) |-| **Tests** | **886+ passing, 0 failures** β 335 context, ~430 KG, 70 semantic extraction, 85 real-world E2E |--See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the full per-contributor breakdown and [CHANGELOG](CHANGELOG.md) for the complete diff.+### π Temporal Intelligence Stack----+Everything you need to reason about *when* β not just *what*.++- **Temporal GraphRAG** β retrieve knowledge as it existed at any point in the past. Natural-language queries like *"what did we know before the 2024 merger?"* are automatically parsed for temporal intent, with zero LLM calls.+- **Allen Interval Algebra** β 13 deterministic interval relations (before, meets, overlaps, during, starts, finishes, equals, and their converses). Find gaps, measure coverage, detect cycles β all without touching an LLM.+- **Point-in-time Query Engine** β reconstruct a self-consistent graph snapshot at any timestamp. Comes with a consistency validator that catches 5 classes of temporal errors: inverted intervals, dangling edges, overlapping relations, temporal gaps, and missing entities.+- **Temporal Metadata Extraction** β ask the LLM to annotate each extracted relation with `valid_from`, `valid_until`, and a calibrated confidence score (0β1 scale with baked-in anchors, so the model doesn't cluster near 1.0).+- **TemporalNormalizer** β converts ISO 8601, partial dates, relative phrases ("last year", "Q1 2024"), and 13 domain-specific phrase maps (Healthcare, Finance, Cybersecurity, Supply Chain, Energyβ¦) into UTC datetime pairs. Zero LLM calls.+- **Bi-temporal Provenance** β every provenance record is automatically stamped with transaction time. Full revision history and audit log export in JSON or CSV. Temporal relationships export as OWL-Time RDF triples.+- **Decision validity windows** β decisions now carry `valid_from` / `valid_until`. Superseded decisions stay in the graph β history is immutable. Point-in-time causal chain reconstruction included.+- **Named checkpoints** β snapshot the full agent context at any moment and diff two snapshots to see exactly what changed.+β [Temporal docs](docs/reference/) Β· [Temporal examples](cookbook/)+ ## Unreleased / Coming Next++ | Area | Highlights |+ |------|-----------|+ | **SHACL Constraints** | `OntologyEngine.to_shacl()` auto-derives SHACL shapes from any OWL ontology; `validate_graph()` returns structured `SHACLValidationReport` with plain-English violation explanations; three quality tiers (`"basic"`, `"standard"`, `"strict"`); three output formats (Turtle, JSON-LD, N-Triples); 3-level inheritance propagation |++ ---++ ## Features++ ### Context & Decision Intelligence+ - **Context Graphs** β structured graph of entities, relationships, and decisions; queryable, causal, persistent+ - **Decision tracking** β record, link, and analyze every agent decision with `add_decision()`, `record_decision()`+ - **Causal chains** β link decisions with `add_causal_relationship()`, trace lineage with `trace_decision_chain()`+ - **Precedent search** β hybrid similarity search over past decisions with `find_similar_decisions()`+ - **Influence analysis** β `analyze_decision_impact()`, `analyze_decision_influence()` β understand downstream effects+ - **Policy engine** β enforce business rules with `check_decision_rules()`; automated compliance validation+ - **Agent memory** β `AgentMemory` with short/long-term storage, conversation history, and statistics+ - **Cross-system context capture** β `capture_cross_system_inputs()` for multi-agent pipelines++ ### Knowledge Graphs+ - **Knowledge graph construction** β entities, relationships, properties, typed edges+ - **Graph algorithms** β PageRank, betweenness centrality, clustering coefficient, community detection+ - **Node embeddings** β Node2Vec embeddings via `NodeEmbedder`+ - **Similarity** β cosine similarity via `SimilarityCalculator`+ - **Link prediction** β score potential new edges via `LinkPredictor`+ - **Temporal graphs** β time-aware nodes and edges+ - **Incremental / delta processing** β update graphs without full recompute++ ### Semantic Extraction+ - **Entity extraction** β named entity recognition, normalization, classification+ - **Relation extraction** β triplet generation from raw text using LLMs or rule-based methods+ - **LLM-typed extraction** β extraction with typed relation metadata+ - **Deduplication v1** β Jaro-Winkler similarity, basic blocking+ - **Deduplication v2** β `blocking_v2`, `hybrid_v2`, `semantic_v2` strategies with `max_candidates_per_entity`+ - **Triplet deduplication** β `dedup_triplets()` for removing duplicate (subject, predicate, object) triples++ ### Reasoning Engines+ - **Forward chaining** β `Reasoner` with IF/THEN string rules and dict facts+ - **Rete network** β `ReteEngine` for high-throughput production rule matching+ - **Deductive reasoning** β `DeductiveReasoner` for classical inference+ - **Abductive reasoning** β `AbductiveReasoner` for hypothesis generation from observations+ - **SPARQL reasoning** β `SPARQLReasoner` for query-based inference over RDF graphs++ ### Provenance & Auditability+ - **Entity provenance** β `ProvenanceTracker.track_entity(id, source_url, metadata)`+ - **Algorithm provenance** β `AlgorithmTrackerWithProvenance` tracks computation lineage+ - **Graph builder provenance** β `GraphBuilderWithProvenance` records entity source lineage from URLs+ - **W3C PROV-O compliant** β lineage tracking across all modules+ - **Change management** β version control with checksums, audit trails, compliance support++ ### Vector Store+ - **Backends** β FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory+ - **Semantic search** β top-k retrieval by embedding similarity+ - **Hybrid search** β vector + keyword with configurable weights+ - **Filtered search** β metadata-based filtering on any field+ - **Custom similarity weights** β tune retrieval per use case++ ### π Graph Database Support+ - **AWS Neptune** β Amazon Neptune graph database with IAM authentication+ - **Apache AGE** β PostgreSQL graph extension with openCypher via SQL+ - **FalkorDB** β native support; `DecisionQuery` and `CausalChainAnalyzer` work directly with FalkorDB row/header shapes++ ### Data Ingestion+ - **File formats** β PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives+ - **Web crawl** β `WebIngestor` with configurable depth+ - **Databases** β `DBIngestor` with SQL query support+ - **Snowflake** β `SnowflakeIngestor` with table/query ingestion, pagination, and key-pair/OAuth auth+ - **Docling** β advanced document parsing with table and layout extraction (PDF, DOCX, PPTX, XLSX)+ - **Media** β image OCR, audio/video metadata extraction++ ### Export Formats+ - **RDF** β Turtle (`.ttl`), JSON-LD, N-Triples (`.nt`), XML via `RDFExporter`+ - **Parquet** β `ParquetExporter` for entities, relationships, and full KG export+ - **ArangoDB AQL** β ready-to-run INSERT statements via `ArangoAQLExporter`+ - **OWL ontologies** β export generated ontologies in Turtle or RDF/XML+ - **SHACL shapes** β export auto-derived constraint shapes via `RDFExporter.export_shacl()` (`.ttl`, `.jsonld`, `.nt`, `.shacl`)++ ### Pipeline & Production+ - **Pipeline builder** β `PipelineBuilder` with stage chaining and parallel workers+ - **Validation** β `PipelineValidator` returns `ValidationResult(valid, errors, warnings)` before execution+ - **Failure handling** β `FailureHandler` with `RetryPolicy` and `RetryStrategy` (exponential backoff, fixed, etc.)+ - **Parallel processing** β configurable worker count per pipeline stage+ - **LLM providers** β 100+ models via LiteLLM (OpenAI, Anthropic, Cohere, Mistral, Ollama, and more)++ ### Ontology+ - **Auto-generation** β derive OWL ontologies from knowledge graphs via `OntologyGenerator`+ - **Import** β load existing OWL, RDF, Turtle, JSON-LD ontologies via `OntologyImporter`+ - **Validation** β HermiT/Pellet compatible consistency checking+ - **SHACL shape generation** β `OntologyEngine.to_shacl()` auto-derives SHACL node and property shapes from any Semantica ontology dict; zero hand-authoring; deterministic (same ontology β same shapes)+ - **SHACL validation** β `OntologyEngine.validate_graph()` runs shapes against a data graph and returns a `SHACLValidationReport` with machine-readable violations and plain-English explanations+ - **Quality tiers** β `"basic"` (structure + cardinality), `"standard"` (+ enumerations, inheritance), `"strict"` (+ `sh:closed` rejects undeclared properties)+ - **Inheritance propagation** β child shapes automatically include all ancestor property shapes (up to 3+ levels), cycle-safe+ - **Three output formats** β Turtle (`.ttl`), JSON-LD, N-Triples; file export via `export_shacl()`----+### π SKOS Vocabulary Management+Build and query controlled vocabularies inside your knowledge graph.+ ## Modules++ | Module | What it provides |+ |---|---|+ | `semantica.context` | Context graphs, agent memory, decision tracking, causal analysis, precedent search, policy engine |+ | `semantica.kg` | Knowledge graph construction, graph algorithms, centrality, community detection, embeddings, link prediction, provenance |+ | `semantica.semantic_extract` | NER, relation extraction, event extraction, coreference, triplet generation, LLM-enhanced extraction |+ | `semantica.reasoning` | Forward chaining, Rete network, deductive, abductive, SPARQL reasoning, explanation generation |+ | `semantica.vector_store` | FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory; hybrid & filtered search |+ | `semantica.export` | RDF (Turtle/JSON-LD/N-Triples/XML), Parquet, ArangoDB AQL, CSV, YAML, OWL, graph formats |+ | `semantica.ingest` | Files (PDF, DOCX, CSV, HTML), web crawl, feeds, databases, Snowflake, MCP, email, repositories |+ | `semantica.ontology` | Auto-generation (6-stage pipeline), OWL/RDF export, import (OWL/RDF/Turtle/JSON-LD), validation, versioning, **SHACL shape generation & validation** |+ | `semantica.pipeline` | Pipeline DSL, parallel workers, validation, retry policies, failure handling, resource scheduling |+ | `semantica.graph_store` | Graph database backends β Neo4j, FalkorDB, Apache AGE, Amazon Neptune; Cypher queries |+ | `semantica.embeddings` | Text embedding generation β Sentence-Transformers, FastEmbed, OpenAI, BGE; similarity calculation |+ | `semantica.deduplication` | Entity deduplication, similarity scoring, merging, clustering; blocking and semantic strategies |+ | `semantica.provenance` | W3C PROV-O compliant end-to-end lineage tracking, source attribution, audit trails |+ | `semantica.parse` | Document parsing β PDF, DOCX, PPTX, HTML, code, email, structured data, media with OCR |+ | `semantica.split` | Document chunking β recursive, semantic, entity-aware, relation-aware, graph-based, ontology-aware |+ | `semantica.normalize` | Data normalization for text, entities, dates, numbers, quantities, languages, encodings |+ | `semantica.conflicts` | Multi-source conflict detection (value, type, relationship, temporal, logical) with resolution strategies |+ | `semantica.change_management` | Version storage, change tracking, checksums, audit trails, compliance support for KGs and ontologies |+ | `semantica.triplet_store` | RDF triplet store integration β Blazegraph, Jena, RDF4J; SPARQL queries and bulk loading |+ | `semantica.visualization` | Interactive and static visualization of KGs, ontologies, embeddings, analytics, and temporal graphs |+ | `semantica.seed` | Seed data management for initial KG construction from CSV, JSON, databases, and APIs |+ | `semantica.core` | Framework orchestration, configuration management, knowledge base construction, plugin system |+ | `semantica.llms` | LLM provider integrations β Groq, OpenAI, Novita AI, HuggingFace, LiteLLM |+ | `semantica.utils` | Shared utilities β logging, validation, exception handling, constants, types, progress tracking |----+- Add SKOS concepts with labels, alt-labels, broader/narrower hierarchy, and definitions β all required triples assembled automatically.+- Query and search vocabularies with SPARQL-backed APIs (injection-sanitized).+- REST API for the Explorer: list schemes, fetch full hierarchy trees (cycle-safe), and import `.ttl` / `.rdf` / `.owl` files.-## β‘ Quick Start+β [SKOS docs](docs/reference/ontology.md)-```python-import semantica-from semantica.context import AgentContext, ContextGraph-from semantica.vector_store import VectorStore+### π· SHACL Constraints-# Build an agent with structured context-context = AgentContext(- vector_store=VectorStore(backend="faiss", dimension=768),- knowledge_graph=ContextGraph(advanced_analytics=True),- decision_tracking=True,- kg_algorithms=True,-)+Turn ontologies into executable data contracts β no hand-authoring.-# Store memory-memory_id = context.store(- "GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%",- conversation_id="research_session_1",-)+- Auto-derive SHACL node and property shapes from any Semantica ontology. Deterministic: same ontology always produces the same shapes.+- Three strictness tiers: `"basic"` (structure + cardinality), `"standard"` (+ enumerations and inheritance), `"strict"` (closes shapes β rejects undeclared properties).+- Validate any RDF graph and get back a report with plain-English violation explanations ready to feed into an LLM or pipeline.+- Use in CI to catch breaking ontology changes before they reach production.-# Record a decision with full context-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,- entities=["gpt4", "gpt35", "reasoning_pipeline"],-)+β `pip install semantica[shacl]`-# Find similar decisions from history-precedents = context.find_precedents("model selection reasoning", limit=5)+### π§ Infrastructure & Fixes-# Analyze downstream influence of this decision-influence = context.analyze_decision_influence(decision_id)-```+- **ContextGraph pagination** β memory complexity dropped from O(N) to O(limit). A 50k-node graph no longer allocates 2.5M dicts per paginated request.+- **Named graph support** β full config-flag enforcement, duplicate clause prevention, backward-compat URI alias, and safe URI encoding in SPARQL pruning.+- **Ollama remote support** β `OllamaProvider` now correctly connects to remote Ollama servers instead of silently falling back to `localhost`.+- **Security** β API key logging removed from extractors; CI workflows locked to least-privilege `contents: read`.-**[π Full Quick Start](#-quick-start)** β’ **[π³ Cookbook Examples](#-semantica-cookbook)** β’ **[π¬ Join Discord](https://discord.gg/sV34vps5hH)** β’ **[β Star Us](https://github.com/Hawksight-AI/semantica)**+β [Full changelog](CHANGELOG.md) Β· [Release notes](RELEASE_NOTES.md)---@@@ -257,119 -346,127 +379,128 @@@ similar = graph.find_similar_decisiochain = graph.trace_decision_chain(loan_id)impact = graph.analyze_decision_impact(loan_id)compliance = graph.check_decision_rules({"category": "loan_approval", "confidence": 0.95})-insights = graph.get_decision_insights()```+β [Full decision tracking guide](docs/reference/) Β· [Cookbook examples](cookbook/)++### Temporal GraphRAG+```python+from semantica.kg import TemporalQueryRewriter, TemporalNormalizer+from semantica.context import TemporalGraphRetriever+from datetime import datetime, timezone++# Parse temporal intent from natural language β zero LLM calls+rewriter = TemporalQueryRewriter()+result = rewriter.rewrite("What decisions were made before the 2024 merger?")+# result.temporal_intent β "before"+# result.at_time β datetime(2024, ..., tzinfo=UTC)++# Filter any retriever to a point in time+retriever = TemporalGraphRetriever(+ base_retriever=your_retriever,+ at_time=datetime(2024, 3, 1, tzinfo=timezone.utc),+ from semantica.context import AgentContext, AgentMemory+ from semantica.vector_store import VectorStore++ context = AgentContext(+ vector_store=VectorStore(backend="inmemory"),+ knowledge_graph=ContextGraph(advanced_analytics=True),+ decision_tracking=True,+ graph_expansion=True,+ kg_algorithms=True,)+ctx = retriever.retrieve("supplier approval decisions")-context.store("Regulation EU 2024/1689 requires explainability for high-risk AI", conversation_id="compliance_review")-context.store("Our fraud model flags 0.3% of transactions", conversation_id="compliance_review")--results = context.retrieve("AI regulation explainability requirements", limit=3)-history = context.get_conversation_history("compliance_review")-stats = context.get_statistics()+# Normalize any date expression to UTC+normalizer = TemporalNormalizer()+start, end = normalizer.normalize("Q1 2024")+# β (datetime(2024, 1, 1, UTC), datetime(2024, 3, 31, UTC))```----+β [Temporal GraphRAG docs](docs/reference/) Β· [Temporal cookbook](cookbook/)-## Knowledge Graphs+### Point-in-Time Graph Snapshots```python-from semantica.kg import KnowledgeGraph, Entity, Relationship-from semantica.kg import CentralityAnalyzer, NodeEmbedder, LinkPredictor+from semantica.context import ContextGraph, AgentContext+from datetime import datetime, timezone-kg = KnowledgeGraph()--kg.add_entity(Entity(id="transformer", label="Transformer", type="Architecture",- properties={"year": 2017, "paper": "Attention Is All You Need"}))-kg.add_entity(Entity(id="bert", label="BERT", type="Model",- properties={"year": 2018, "parameters": "340M"}))-kg.add_entity(Entity(id="gpt4", label="GPT-4", type="Model", properties={"year": 2023}))+graph = ContextGraph()-kg.add_relationship(Relationship(source="bert", target="transformer", type="based_on"))-kg.add_relationship(Relationship(source="gpt4", target="transformer", type="based_on"))--# Graph algorithms-analyzer = CentralityAnalyzer(kg)-centrality = analyzer.compute_pagerank()-betweenness = analyzer.compute_betweenness()--# Node embeddings (Node2Vec)-embedder = NodeEmbedder()-embeddings = embedder.compute_embeddings(kg, node_labels=["Model"], relationship_types=["based_on"])+# Decisions carry explicit validity windows+graph.add_decision(+ category="policy",+ scenario="Approve supplier A",+ outcome="approved",+ confidence=0.9,+ valid_from=datetime(2024, 1, 1, tzinfo=timezone.utc),+ valid_until=datetime(2024, 6, 30, tzinfo=timezone.utc),+)-# Link prediction-predictor = LinkPredictor()-score = predictor.score_link(kg, "gpt4", "bert", method="common_neighbors")+# Reconstruct the graph exactly as it was on any date+# The source graph is never mutated+snapshot = graph.state_at(datetime(2024, 3, 15, tzinfo=timezone.utc))-models = kg.find_nodes(type="Model")-descendants = kg.get_neighbors("transformer", direction="incoming")+# Named checkpoints β snapshot context, then diff what changed+context.checkpoint("before_merge")+# ... make changes ...+diff = context.diff_checkpoints("before_merge", "after_merge")+# β {"decisions_added": [...], "relationships_added": [...], ...}```------## Semantic Extraction+### Semantic Extraction with Temporal Bounds```python-from semantica.semantic_extract import extract_entities, extract_relations, extract_triplets--text = """-OpenAI released GPT-4 in March 2023. Microsoft integrated GPT-4 into Azure OpenAI Service.-Anthropic, founded by former OpenAI researchers, released Claude as a competing model.-"""+from semantica.semantic_extract import extract_relations_llm-entities = extract_entities(text)-# β [Entity(label="OpenAI", type="Organization"), Entity(label="GPT-4", type="Model"), ...]+text = "The partnership was effective from January 2022 until the merger in Q3 2024."-relations = extract_relations(text)-# β [Relation(source="OpenAI", type="released", target="GPT-4"), ...]+# LLM extracts relations AND annotates each one with temporal validity+relations = extract_relations_llm(text, extract_temporal_bounds=True)-triplets = extract_triplets(text)+for rel in relations:+ print(f"{rel.source} β {rel.target}")+ print(f" valid: {rel.metadata['valid_from']} β {rel.metadata['valid_until']}")+ print(f" confidence: {rel.metadata['temporal_confidence']}")```-```python-from semantica.deduplication import DuplicateDetector+β [Extraction docs](docs/reference/)-entities = [- {"id": "e1", "name": "OpenAI Inc.", "type": "Organization"},- {"id": "e2", "name": "Open AI", "type": "Organization"},- {"id": "e3", "name": "Anthropic", "type": "Organization"},-]+### Knowledge Graphs & Algorithms++```python+from semantica.kg import KnowledgeGraph, Entity, Relationship+from semantica.kg import CentralityAnalyzer, NodeEmbedder, LinkPredictor-detector = DuplicateDetector()-duplicates = detector.detect_duplicates(entities, threshold=0.85)-# β [("e1", "e2")]+kg = KnowledgeGraph()+kg.add_entity(Entity(id="bert", label="BERT", type="Model"))+kg.add_entity(Entity(id="transformer", label="Transformer", type="Architecture"))+kg.add_relationship(Relationship(source="bert", target="transformer", type="based_on"))-duplicates_v2 = detector.detect_duplicates(entities, threshold=0.85, strategy="semantic_v2")+# Graph algorithms+centrality = CentralityAnalyzer(kg).compute_pagerank()+embeddings = NodeEmbedder().compute_embeddings(kg, node_labels=["Model"], relationship_types=["based_on"])+link_score = LinkPredictor().score_link(kg, "gpt4", "bert", method="common_neighbors")```----+β [KG algorithm docs](docs/reference/) Β· [KG cookbook](cookbook/)-## Reasoning Engines+### Reasoning```python-from semantica.reasoning import Reasoner+from semantica.reasoning import Reasoner, ReteEngine+# Forward chaining β derive new facts from rulesreasoner = Reasoner()reasoner.add_rule("IF Person(?x) THEN Mortal(?x)")-reasoner.add_rule("IF Employee(?x) AND WorksAt(?x, ?y) THEN HasEmployer(?x, ?y)")--results = reasoner.infer_facts([- "Person(Socrates)",- "Employee(Alice)",- {"source_name": "Alice", "target_name": "OpenAI", "type": "WorksAt"},-])-# β ["Mortal(Socrates)", "HasEmployer(Alice, OpenAI)"]-```--```python-from semantica.reasoning import ReteEngine+results = reasoner.infer_facts(["Person(Socrates)"])+# β ["Mortal(Socrates)"]+# Rete network β real-time production rule matchingrete = ReteEngine()rete.add_rule({- "name": "flag_high_risk_transaction",+ "name": "flag_high_risk","conditions": [{"field": "amount", "operator": ">", "value": 10000},{"field": "country", "operator": "in", "value": ["IR", "KP", "SY"]},@@@ -429,78 -640,155 +560,157 @@@ pipeline =.with_parallel_workers(4))-validator = PipelineValidator()-result = validator.validate(builder)+# Validate before running β catches config errors early+result = PipelineValidator().validate(pipeline)if result.valid:- pipeline = builder.build()- pipeline.run(input_path="./documents/")--retry_policy = RetryPolicy(strategy=RetryStrategy.EXPONENTIAL_BACKOFF, max_retries=3)-handler = FailureHandler()-handler.handle_failure(error=last_error, policy=retry_policy, retry_count=1)+ pipeline.build().run(input_path="./documents/")```------## Ontology+β [Pipeline docs](docs/reference/)-```python-from semantica.ontology import OntologyGenerator, OntologyImporter+----generator = OntologyGenerator()-ontology = generator.generate(kg)-generator.export(ontology, path="domain_ontology.owl", format="turtle")--importer = OntologyImporter()-ontology = importer.load("existing_ontology.owl")-ontology = importer.load("schema.ttl", format="turtle")-ontology = importer.load("context.jsonld")-```+## π¦ Modules++- **`semantica.context`** β context graphs, decisions, causal chains, precedent search, policy engine, checkpoints+- **`semantica.kg`** β KG construction, graph algorithms, embeddings, link prediction, temporal query engine, Allen algebra, `TemporalNormalizer`, provenance+- **`semantica.semantic_extract`** β NER, relation extraction, triplet generation, LLM extraction with temporal bounds, deduplication+- **`semantica.reasoning`** β forward chaining, Rete, deductive, abductive, SPARQL, temporal algebra+- **`semantica.vector_store`** β FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory; hybrid & filtered search+- **`semantica.export`** β RDF (Turtle/JSON-LD/N-Triples/XML), OWL-Time, Parquet, ArangoDB AQL, OWL, SHACL+- **`semantica.ingest`** β files, web crawl, databases, Snowflake, email, repositories+- **`semantica.ontology`** β OWL generation & import, SHACL generation & validation, SKOS vocabulary management+- **`semantica.pipeline`** β stage chaining, parallel workers, validation, retry policies, failure handling+- **`semantica.graph_store`** β Neo4j, FalkorDB, Apache AGE, Amazon Neptune; Cypher queries+- **`semantica.embeddings`** β Sentence-Transformers, FastEmbed, OpenAI, BGE; similarity+- **`semantica.deduplication`** β entity dedup, similarity scoring, blocking and semantic strategies+- **`semantica.provenance`** β W3C PROV-O lineage, revision history, audit log export+- **`semantica.parse`** β PDF, DOCX, PPTX, HTML, code, email, media with OCR+- **`semantica.split`** β recursive, semantic, entity-aware, graph-based, ontology-aware chunking+- **`semantica.conflicts`** β multi-source conflict detection with resolution strategies+- **`semantica.change_management`** β version storage, checksums, audit trails, compliance support+- **`semantica.triplet_store`** β Blazegraph, Jena, RDF4J; SPARQL, bulk loading, SKOS helpers+- **`semantica.visualization`** β KG, ontology, embedding, and temporal graph visualization+- **`semantica.llms`** β Groq, OpenAI, Novita AI, HuggingFace, LiteLLM+ ### SHACL Shape Generation & Validation++ Semantica turns ontologies into executable data contracts. The constraints layer completes a hybrid reasoning system β symbolic constraints (SHACL) alongside semantic retrieval (embeddings).++ **Phase 1 β Generate shapes from any ontology dict:**++ ```python+ from semantica.ontology import OntologyEngine++ engine = OntologyEngine()+ ontology = engine.from_data(data) # or engine.from_text(...) / engine.to_owl(...)++ # Generate SHACL shapes β zero hand-authoring+ shacl_ttl = engine.to_shacl(ontology) # Turtle string (default)+ shacl_jld = engine.to_shacl(ontology, format="json-ld") # JSON-LD string+ shacl_nt = engine.to_shacl(ontology, format="n-triples") # N-Triples string++ # Write to file+ engine.export_shacl(ontology, path="shapes/domain.ttl")+ ```++ **Quality tiers β control constraint strictness:**++ ```python+ # "basic" β node shapes, property paths, datatypes, cardinality+ # "standard" β + enumerations (sh:in), patterns, inheritance propagation [DEFAULT]+ # "strict" β + sh:closed true on all shapes (rejects undeclared properties)++ shacl = engine.to_shacl(ontology, quality_tier="strict")+ ```++ **Phase 2 β Validate a graph against the shapes:**++ ```python+ import pathlib++ report = engine.validate_graph(+ data_graph=pathlib.Path("data/graph.ttl").read_text(),+ ontology=ontology, # auto-generates SHACL before validating+ explain=True, # populate plain-English explanations on each violation+ )++ print(report.summary())+ # β "Graph does NOT conform: 2 violation(s)."++ for v in report.violations:+ print(v.explanation)+ # β "Node <https://example.com/john> is missing required property <ex:name>. At least 1 value(s) are required."+ # β "Node <https://example.com/acme> has value '999' for <ex:employeeCount> but the expected datatype is xsd:string."++ import json+ print(json.dumps(report.to_dict(), indent=2)) # machine-readable β feed to LLM or pipeline+ ```++ **Or validate against a pre-built SHACL file:**++ ```python+ report = engine.validate_graph(+ data_graph=graph_turtle_string,+ shacl="shapes/domain.ttl", # path or SHACL string+ )+ ```++ **Regenerate shapes in CI to detect breaking ontology changes:**++ ```bash+ python -c "+ from semantica.ontology import OntologyEngine+ import json, pathlib+ engine = OntologyEngine()+ onto = engine.from_data(json.loads(pathlib.Path('ontology.json').read_text()))+ engine.export_shacl(onto, 'shapes/shapes.ttl')+ "+ git diff shapes/shapes.ttl # detects breaking ontology changes+ ```++ > **Requires pyshacl for `validate_graph()`:** `pip install semantica[shacl]`+ > Shape generation (`to_shacl`, `export_shacl`) works without any optional dependencies.+----## Integrations--**Graph Databases**-- AWS Neptune β Amazon Neptune with IAM authentication-- Apache AGE β PostgreSQL + openCypher via SQL-- FalkorDB β native support for decision queries and causal analysis+## π Integrations-**Vector Databases**-- FAISS β high-performance dense vector search-- Pinecone β serverless and pod-based managed vector database (`pip install semantica[vectorstore-pinecone]`)-- Weaviate β GraphQL-based vector store with rich schema management (`pip install semantica[vectorstore-weaviate]`)-- Qdrant β collection-based store with payload filtering (`pip install semantica[vectorstore-qdrant]`)-- Milvus β scalable store with partition support and multiple index types (`pip install semantica[vectorstore-milvus]`)-- PgVector β PostgreSQL pgvector extension with JSONB metadata (`pip install semantica[vectorstore-pgvector]`)-- In-memory β lightweight, zero-dependency store for development and testing+### Graph Databases+- **AWS Neptune** β Amazon Neptune with IAM authentication+- **Apache AGE** β PostgreSQL + openCypher via SQL+- **FalkorDB** β native support for decision queries and causal analysis-**Data Sources**-- Snowflake β `SnowflakeIngestor` for table/query ingestion, schema introspection, pagination, and multiple auth methods (password, key-pair, OAuth, SSO) (`pip install semantica[db-snowflake]`)+### Vector Databases+- **FAISS** β built-in, zero extra dependencies+- **Pinecone** β `pip install semantica[vectorstore-pinecone]`+- **Weaviate** β `pip install semantica[vectorstore-weaviate]`+- **Qdrant** β `pip install semantica[vectorstore-qdrant]`+- **Milvus** β `pip install semantica[vectorstore-milvus]`+- **PgVector** β `pip install semantica[vectorstore-pgvector]`-**Document Parsing**-- Docling β PDF, DOCX, PPTX, XLSX with table and layout extraction+### Data Sources+- **Files** β PDF, DOCX, HTML, JSON, CSV, Excel, PPTX, archives+- **Web** β configurable-depth crawler+- **Databases** β SQL via `DBIngestor`+- **Snowflake** β table/query ingestion, pagination, password/key-pair/OAuth/SSO auth Β· `pip install semantica[db-snowflake]`+- **Docling** β advanced table and layout extraction (PDF, DOCX, PPTX, XLSX)-**LLM Providers**-- 100+ models via LiteLLM β OpenAI, Anthropic, Cohere, Mistral, Ollama, Azure, AWS Bedrock, and more-- Novita AI β OpenAI-compatible provider (`deepseek/deepseek-v3.2` and more); configure via `NOVITA_API_KEY`+### LLM Providers+- **LiteLLM** β 100+ models: OpenAI, Anthropic, Cohere, Mistral, Ollama, Azure, AWS Bedrock, and more+- **Novita AI** β OpenAI-compatible (`deepseek/deepseek-v3.2` and more) Β· set `NOVITA_API_KEY`-**Agentic Frameworks**-- Complements LangChain, LlamaIndex, AutoGen, CrewAI, Google ADK, and more+### Agentic Frameworks+Semantica complements β not replaces β LangChain, LlamaIndex, AutoGen, CrewAI, Google ADK, and more.-> **Agno β First-Class Integration** `pip install semantica[agno]`+> **Agno β First-Class Integration** Β· `pip install semantica[agno]`>-> Semantica ships a dedicated Agno integration with five ready-to-use components:-> - **`AgnoContextStore`** β graph-backed agent memory-> - **`AgnoKnowledgeGraph`** β multi-hop GraphRAG knowledge base-> - **`AgnoDecisionKit`** β 6 decision-intelligence tools-> - **`AgnoKGToolkit`** β 7 knowledge-graph pipeline tools-> - **`AgnoSharedContext`** β shared context graph for multi-agent teams--**Export**-- RDF: Turtle, JSON-LD, N-Triples, XML Β· Parquet Β· ArangoDB AQL+> Five ready-to-use Agno components:+> - `AgnoContextStore` β graph-backed agent memory+> - `AgnoKnowledgeGraph` β multi-hop GraphRAG knowledge base+> - `AgnoDecisionKit` β 6 decision-intelligence tools+> - `AgnoKGToolkit` β 7 KG pipeline tools+> - `AgnoSharedContext` β shared context graph for multi-agent teams---@@@ -519,10 -807,13 +729,16 @@@ pip install semantica[vectorstore-weavipip install semantica[vectorstore-qdrant]pip install semantica[vectorstore-milvus]pip install semantica[vectorstore-pgvector]+pip install semantica[shacl] # SHACL validation+pip install semantica[db-snowflake] # Snowflake ingestion+pip install semantica[agno] # Agno integration+ # SHACL validation (validate_graph)+ pip install semantica[shacl]++ # Snowflake ingestion+ pip install semantica[db-snowflake]+# From sourcegit clone https://github.com/Hawksight-AI/semantica.gitcd semanticadiff --cc docs/getting-started.mdindex dcec03a9,deb69915..06c4443b--- a/docs/getting-started.md+++ b/docs/getting-started.md@@@ -44,7 -44,7 +44,8 @@@ from semantica.context import AgentContfrom semantica.vector_store import VectorStorecontext = AgentContext(+ vector_store=VectorStore(backend="faiss", dimension=768),+ vector_store=VectorStore(backend="inmemory"),knowledge_graph=ContextGraph(advanced_analytics=True),decision_tracking=True,)diff --cc docs/index.mdindex 63a0ecf7,42a2255b..932da0ab--- a/docs/index.md+++ b/docs/index.md@@@ -65,7 -65,7 +65,8 @@@ from semantica.context import AgentContfrom semantica.vector_store import VectorStorecontext = AgentContext(+ vector_store=VectorStore(backend="faiss", dimension=768),+ vector_store=VectorStore(backend="inmemory"),knowledge_graph=ContextGraph(advanced_analytics=True),decision_tracking=True,)