Community Chinese fork (semantica-cn) of Semantica — Graph-Native Infrastructure for Context and Accountable AI Systems: context graphs, decision intelligence, full provenance tracking, and explainable reasoning engines — every AI decision traceable, every output auditable.
pip install semantica-cn==0.7.0 Copy PIP instructions
Fork notice — this is the community Chinese fork OntologyAgent/semantica-cn. It publishes the semantica-cn PyPI package built from the same code and versioned with upstream (pip install semantica-cn — choose it or the official semantica, not both). Upstream project: semantica-agi/semantica.
Ingest your enterprise data, extract what matters, build a Context Graph and knowledge graph (KG), and run graph analytics and causal reasoning over all of it, with full decision provenance baked in. Explainable, traceable, and trustworthy by design.
Context Management · Knowledge Modeling · Deterministic Reasoning · Ontology Management · Decision Intelligence · End-to-End Traceability
Polyglot Graph Storage · RDF & LPG Support · W3C Standards · Interoperable
pip install semantica English · Deutsch · Français · Español · Italiano · Português · العربية · اردو · हिन्दी · 中文 · 日本語 · 한국어
Knowledge Explorer · Context Graphs · Reasoning Engine · Decision Intelligence · Ontology Hub
Most AI agents run on embeddings, not meaning: similarity scores with no structure, no relationships, and no way to explain why a result came back.
Semantica is the semantic/context layer underneath your LLM, vector store, and agent framework: deterministic infrastructure (no LLM required for graph construction, reasoning, or provenance; where an LLM is used, it's optional and vendor-neutral, every major provider supported, OpenAI, Anthropic, Gemini, and more, via semantica.llms) that turns fragmented enterprise data into a structured, queryable Context Graph and knowledge graph that carries the business context, not just the data structure. Ontologies and controlled vocabularies (OWL, SHACL, SKOS) make what an entity means to your business, its definitions, relationships, and rules, as explicit as the data itself, not just its embedding.
Decision provenance and audit trails aren't the product. They fall out of that structure for free, and in domains a regulator can question, the same structure that makes your agent smarter also gives you a straight answer to "why."
Quick Start · Architecture · What You Get · Why Semantica · Decision Intelligence · Context Graphs · Recipe: Audit Trail · Module Reference · Integrations · CLI · Performance · Install
Semantica complements your existing stack rather than replacing it. Keep your LLM, vector store, and agent framework exactly as they are; Semantica adds the decision records, causal reasoning, provenance, ontology governance, conflict detection, and audit trails on top. The reasoning engines, KG construction, and provenance layer are fully deterministic; no LLM is required to use them.
pip install semantica from semantica.context import ContextGraph graph = ContextGraph(advanced_analytics=True) # Every agent decision becomes a queryable, auditable knowledge node decision_id = graph.record_decision( category="vendor_selection", scenario="Choose cloud provider for HIPAA workload", reasoning="AWS offers BAA, mature HIPAA tooling, and existing team expertise", outcome="selected_aws", confidence=0.93, ) # Ask "why did this happen?" and get a real, structured answer chain = graph.trace_decision_chain(decision_id) # full causal ancestry similar = graph.find_similar_decisions("cloud vendor", max_results=5) # precedents impact = graph.analyze_decision_impact(decision_id) # downstream influence map compliant = graph.check_decision_rules({"category": "vendor_selection"}) # policy gate Verify your install in 5 seconds:
semantica doctor Running in a script or CI? Progress bars are written only when stdout is an interactive terminal (or a Jupyter notebook), so piping and redirecting stay clean by default. Override with SEMANTICA_DISABLE_PROGRESS=1 to silence progress everywhere, or SEMANTICA_FORCE_PROGRESS=1 to keep it when stdout is redirected. SEMANTICA_DISABLE_PROGRESS takes precedence.
If Semantica solves a real problem for you, a star helps others find it.
Semantica is a real end-to-end pipeline, not a single library with a marketing name. Every stage below is a shipping module, independently importable:
Sources → Ingest → Parse → Normalize → Split → Extract → Conflict Detection → Deduplication → Knowledge Graph → [ Ontology · Reasoning · Provenance · Decisions ] → Enriched KG → Vector Store + Polyglot Graph Store (RDF & LPG) → Export / Visualize / REST · MCP · CLI Ingest: files, web, databases, enterprise data platforms (Databricks, Snowflake, SAP), cloud (Google Drive, Elasticsearch), streams (Kafka, Kinesis), Git, email, MCP Parse → Normalize → Split: document parsing, text/entity/date normalization, GraphRAG-native entity-aware chunking Extract → Conflict Detection → Deduplication: NER, relations, events, triplets; conflicting facts flagged and resolved before they merge Knowledge Graph: GraphBuilder constructs the graph; bi-temporal facts and full graph analytics (centrality, communities, link prediction) run on top of it Ontology · Reasoning · Provenance · Decisions: the intelligence layer sitting on the KG, with SHACL/OWL governance, Rete/Datalog/SPARQL inference, W3C PROV-O lineage, and first-class decision records Storage: polyglot by design, with RDF triple stores (embedded Oxigraph, Blazegraph, Apache Jena, Eclipse RDF4J), Labeled Property Graphs (Neo4j, FalkorDB, Apache AGE, AWS Neptune), and vector stores, all swappable without touching your code Outputs: export (RDF, OWL, Parquet, Cypher, JSON-LD), interactive visualization, and access via REST API, MCP server, or CLI → Full Mermaid diagrams for the pipeline and the decision intelligence lifecycle
Decision Intelligence turns every AI choice from an ephemeral inference into a permanent, auditable, queryable record. It answers "what did your AI decide, why, and what happened next?": the question regulators and enterprise risk teams ask with increasing urgency.
In Semantica, a decision is not a log line. It is a first-class graph node with a full lifecycle. In regulated domains, every AI decision must be traceable to a source and defensible to an auditor: record_decision() creates a permanent, structured record exportable as W3C PROV-O, the format most compliance frameworks accept for regulator submission.
record_decision() → stored as a graph node with full structured context add_causal_relationship() → linked to upstream causes and downstream effects find_similar_decisions() → semantic precedent search across all past decisions trace_decision_chain() → full causal ancestry back to root causes analyze_decision_impact() → downstream influence map - everything this decision affected check_decision_rules() → policy compliance gate against configurable rule sets export / audit trail → W3C PROV-O, CSV, or JSON for regulator submission from semantica.context import ContextGraph graph = ContextGraph(advanced_analytics=True) # Record decisions with full structured context app_id = graph.record_decision( category="credit_application", scenario="Personal loan, $85k income, 31% DTI, 3yr employment", reasoning="Income meets threshold; employment stable; no adverse credit events", outcome="proceed_to_underwriting", confidence=0.88, metadata={"applicant_id": "A-7291"}, ) uw_id = graph.record_decision( category="loan_underwriting", scenario="Underwriting review for A-7291", reasoning="DTI within policy; clean 36-month credit history", outcome="approved", confidence=0.94, ) rate_id = graph.record_decision( category="interest_rate", scenario="Rate assignment for approved loan A-7291", outcome="rate_set_8.9pct", reasoning="Prime + 2.4% based on risk tier B2", confidence=0.99, ) # Build the auditable causal chain - relationship_type must be one of # CAUSED, INFLUENCED, or PRECEDENT_FOR graph.add_causal_relationship(app_id, uw_id, relationship_type="CAUSED") graph.add_causal_relationship(uw_id, rate_id, relationship_type="INFLUENCED") # Query the intelligence chain = graph.trace_decision_chain(rate_id) similar = graph.find_similar_decisions("personal loan approval, 31% DTI", max_results=5) impact = graph.analyze_decision_impact(uw_id) compliant = graph.check_decision_rules({"category": "loan_underwriting", "confidence": 0.94}) insights = graph.get_decision_insights() Context Graphs A Context Graph is the structured memory layer that traditional RAG is missing. Instead of flat embeddings that answer "what is similar?", a Context Graph answers "what is connected, why, and how?" Every entity, relationship, decision, and fact is a first-class node, queryable by graph traversal. Entities link to source documents, decisions link to evidence and consequences, facts carry full provenance, and conflicts are detected, not silently overwritten.
from semantica.context import ContextGraph, AgentContext from semantica.vector_store import VectorStore graph = ContextGraph(advanced_analytics=True) # Add nodes with typed properties graph.add_node("acme_corp", "Organization", name="Acme Corp", industry="SaaS") graph.add_node("alice_chen", "Person", name="Alice Chen", role="CTO") graph.add_node("contract_001", "Contract", value=2_400_000, currency="USD") # Add typed, weighted edges (extra kwargs become edge metadata) graph.add_edge("alice_chen", "acme_corp", edge_type="works_for", since="2019-03-01") graph.add_edge("acme_corp", "contract_001", edge_type="party_to", signed="2024-01-15") # BFS traversal - hop through the graph from any node neighbors = graph.get_neighbors("acme_corp", hops=2) # Point-in-time snapshot - the graph as it existed on any past date snapshot = graph.state_at("2024-01-01") # AgentContext - high-level API for agent memory workflows vs = VectorStore(backend="faiss") ctx = AgentContext(vector_store=vs, knowledge_graph=graph) ctx.store("Alice approved the Acme renewal in Q1 2024", conversation_id="conv_001") retrieved = ctx.retrieve("who approved the Acme contract?") Why graph over embeddings: traversal finds connections embeddings miss (a person 3 hops from a contract); every node carries provenance so you can always ask "where did this come from?"; conflicts are flagged before they corrupt your knowledge base; point-in-time snapshots let you replay history without reprocessing.
One pattern built on the same Context Graph: record a causally-linked decision chain, attach provenance to every entity, and export a regulator-ready audit trail.
Every module below is independently importable, with working code samples verified against the current source tree; use one or all of them.
↓ Expand Module Reference below for every module's working example, or jump to More Recipes, the full Integrations matrix, MCP tool list, and REST endpoints.
Expand any module below for its runnable example.
Ingest from files, web, databases, APIs, streams, email, Git repos, Parquet, Databricks, Snowflake, SAP, or MCP servers, all through a unified interface.
from semantica.ingest import FileIngestor, WebIngestor, ParquetIngestor, DBIngestor # Ingest an entire directory of contracts (PDF, DOCX, HTML, TXT) docs = FileIngestor().ingest_directory("./contracts/", recursive=True) # Ingest live web content with robots.txt compliance pages = WebIngestor().ingest_url("https://example.com/reports/annual-2024.html") # Ingest structured data from Parquet with Snappy compression records = ParquetIngestor().ingest("./data/transactions.parquet") # Ingest from a SQL database - specify which tables to pull rows = DBIngestor().ingest_database( connection_string="postgresql://user:pass@localhost/mydb", include_tables=["customer_events"], max_rows_per_table=50_000, ) # Enterprise data platforms - pull tables straight out of your lakehouse # or warehouse, with lineage, instead of exporting to CSV first from semantica.ingest import DatabricksIngestor, SnowflakeIngestor # pip install "semantica[db-databricks]" databricks = DatabricksIngestor( host="https://adb-xxx.azuredatabricks.net", token="dapi-xxxxxxxx", # or client_id/client_secret for OAuth M2M http_path="/sql/1.0/warehouses/xxxxxxxx", catalog="main", ) customers = databricks.ingest_table("customers", limit=10_000) sales = databricks.ingest_query("SELECT * FROM sales WHERE region = 'EMEA'") table_lineage = databricks.get_table_lineage("customers", catalog="main", schema="default") # Unity Catalog lineage # pip install semantica[db-snowflake] snowflake = SnowflakeIngestor( account="myaccount", user="myuser", password="mypassword", # or private_key=... for key-pair; use authenticator="oauth", token=... for OAuth warehouse="COMPUTE_WH", database="MYDB", ) orders = snowflake.ingest_table("ORDERS", limit=10_000) Security Note: Never hardcode credentials (token, password, private_key) in production code; pass them via environment variables (e.g., DATABRICKS_TOKEN, SNOWFLAKE_PASSWORD) or a secrets manager.
Supported sources: Local files (PDF, DOCX, PPTX, HTML, TXT, CSV, JSON, YAML, Excel, XML) · Web pages · RSS/Atom feeds · REST APIs · Databases (PostgreSQL, MySQL, SQLite, Oracle, SQL Server) · Parquet datasets · Databricks (Unity Catalog + Delta Lake) · Snowflake · SAP (OData v2/v4) · Git repositories · Email (IMAP/POP3) · Message streams (Kafka, RabbitMQ, Kinesis, Pulsar) · MCP resources · Apache Arrow/Feather/IPC (ArrowIngestor)
DuckDB, Elasticsearch, Google Drive, HuggingFace, MongoDB, and Pandas ingestion also ship (DuckDBIngestor, ElasticIngestor, GDriveIngestor, HuggingFaceIngestor, MongoIngestor, PandasIngestor) but aren't re-exported from the top-level semantica.ingest namespace yet — import them directly: from semantica.ingest.duckdb_ingestor import DuckDBIngestor.
Extract structured knowledge from raw text in one pass.
from semantica.semantic_extract import ( NamedEntityRecognizer, RelationExtractor, EventDetector, TripletExtractor, ) text = """ Anthropic CEO Dario Amodei announced a $7.3B Series E funding round in partnership with Google and Spark Capital, valuing the company at $61.5B as of Q4 2024. """ # Named entity recognition with confidence thresholding ner = NamedEntityRecognizer(confidence_threshold=0.7) entities = ner.extract_entities(text) # → [Entity(name="Dario Amodei", type="PERSON"), Entity(name="Anthropic", type="ORG"), # Entity(name="Google", type="ORG"), Entity(name="$7.3B", type="MONEY"), ...] # Relationship extraction - bidirectional support rel_extractor = RelationExtractor(confidence_threshold=0.6, bidirectional=True) relations = rel_extractor.extract_relations(text, entities=entities) # → [Relation(subject="Dario Amodei", predicate="ceo_of", object="Anthropic"), # Relation(subject="Anthropic", predicate="raised", object="$7.3B Series E"), ...] # Event detection with temporal processing events = EventDetector(extract_participants=True, extract_time=True).detect_events(text) # → [Event(type="FUNDING", participants=["Anthropic","Google","Spark Capital"], # amount="$7.3B", date="Q4 2024")] # RDF triplets with optional provenance metadata triplets = TripletExtractor(include_temporal=True, include_provenance=True).extract_triplets(text) # → [("Anthropic", "valuation", "$61.5B"), ("Dario Amodei", "is_ceo_of", "Anthropic"), ...] Batch processing across many documents uses ner.process_batch([...]), not a per-call extract_entities_batch on the facade class.
Build a production knowledge graph from documents and run graph algorithms over it.
from semantica.reasoning import ReteEngine, Rule, Fact, RuleType rete = ReteEngine() rete.build_network([ Rule( rule_id="aml_flag", name="Flag high-risk transactions", conditions=[ {"field": "amount", "operator": ">", "value": 10_000}, {"field": "country", "operator": "in", "value": ["IR", "KP", "SY"]}, ], conclusion="flag_for_compliance_review", rule_type=RuleType.IMPLICATION, ), Rule( rule_id="velocity_check", name="Flag rapid sequential transfers", conditions=[ {"field": "transfers_in_1h", "operator": ">", "value": 5}, {"field": "total_amount", "operator": ">", "value": 50_000}, ], conclusion="flag_velocity_breach", rule_type=RuleType.IMPLICATION, ), ]) rete.add_fact(Fact("tx_001", "transaction", [{"amount": 15_000, "country": "IR"}])) flagged = rete.match_patterns() # → [{"rule": "aml_flag", "matched_facts": ["tx_001"], "conclusion": "flag_for_compliance_review"}] Current limitation: ReteEngine's alpha-node condition matcher is intentionally simple in this release — validate match_patterns() output against your actual rule set before wiring it into a production compliance gate; more selective condition evaluation is on the roadmap.
# Recursive Datalog - natural language for graph queries from semantica.reasoning import DatalogReasoner engine = DatalogReasoner() engine.add_fact("parent(tom, bob)") engine.add_fact("parent(bob, ann)") engine.add_fact("parent(ann, pat)") engine.add_rule("ancestor(X, Y) :- parent(X, Y).") engine.add_rule("ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z).") ancestors = engine.query("ancestor(tom, ?X)") # → [{"X": "bob"}, {"X": "ann"}, {"X": "pat"}] # Explainable reasoning - trace the path, not just the answer from semantica.reasoning import ExplanationGenerator, Reasoner reasoner = Reasoner() reasoner.add_fact("parent(tom, bob)") reasoner.add_rule("ancestor(X, Y) :- parent(X, Y)") result = reasoner.forward_chain() explainer = ExplanationGenerator() explanation = explainer.generate_explanation(result) # → Explanation(conclusion="...", steps=[ReasoningStep(...)], justification=Justification(...)) semantica.vector_store: Hybrid & Filtered Semantic Search Drop-in vector store with multiple backends, hybrid search, and decision-aware retrieval.
from semantica.vector_store import VectorStore, HybridSearch # In-memory backend shown here: HybridSearch and explain_decision() work out of the box. # Swap backend="qdrant" / "weaviate" / "milvus" / "pinecone" / "pgvector" / "faiss" once you # scale past a single process — search() and store_decision() work identically on all of them. vs = VectorStore(backend="inmemory", dimension=1536) # Store a decision with scenario description and outcome vs.store_decision( scenario="Personal loan A-7291, $85k income, 31% DTI, 3yr employment", outcome="approved", confidence=0.94, category="loan_underwriting", ) # Semantic similarity search results = vs.search( query="personal loan approval with low DTI", limit=10, ) # Hybrid search - dense + sparse retrieval in one pass with RRF fusion hs = HybridSearch(vector_store=vs) hits = hs.search("high-risk transactions 2024") # Explain why a decision was retrieved explanation = vs.explain_decision(results[0]["id"]) Backends: faiss · qdrant · weaviate · milvus · pinecone · pgvector · sqlite · inmemory
KG-aware splitting that preserves entity boundaries, relation triplets, and ontology concepts, essential for GraphRAG pipelines.
from semantica.split import TextSplitter, EntityAwareChunker, RelationAwareChunker text = open("contracts/master_agreement.txt").read() # Standard recursive chunking chunks = TextSplitter(method="recursive", chunk_size=1000, chunk_overlap=200).split(text) # Entity-aware chunking - never splits a named entity across chunks (GraphRAG) chunks = TextSplitter(method="entity_aware", ner_method="llm", chunk_size=1000).split(text) # Relation-aware chunking - preserves (subject, predicate, object) triplets intact chunks = RelationAwareChunker(chunk_size=1000, preserve_triplets=True).chunk(text) # Graph-based chunking - uses centrality to find natural community boundaries chunks = TextSplitter(method="graph_based", chunk_size=1000).split(text) # Hierarchical chunking - multi-level (section → paragraph → sentence) chunks = TextSplitter(method="hierarchical", levels=["section", "paragraph"]).split(text) Supported methods: recursive · token · sentence · paragraph · semantic_transformer · entity_aware · relation_aware · graph_based · ontology_aware · hierarchical · community_detection · centrality_based · llm
Every fact is linked to its source. No black boxes, no mystery outputs.
from semantica.provenance import ProvenanceManager prov = ProvenanceManager(storage_path="./provenance.db") # Track where every entity came from prov.track_entity( entity_id="acme_corp", source="contracts/acme_master_agreement_2024.pdf", metadata={"page": 1, "confidence": 0.97, "extractor": "NamedEntityRecognizer"}, ) # Track a relationship's provenance - entity linkage travels in metadata prov.track_relationship( relationship_id="alice_works_for_acme", source="hr_records/employees_q1_2024.csv", metadata={"source_entity_id": "alice_chen", "target_entity_id": "acme_corp"}, ) # Answer "where did this come from?" lineage = prov.get_lineage("acme_corp") trail = prov.trace_lineage("alice_chen") # full ancestor chain entry = prov.get_provenance("acme_corp") semantica.ontology: OWL Generation, SHACL Validation Generate ontologies from data, validate shapes, and manage your vocabulary.
from semantica.ontology import OntologyGenerator, OntologyValidator data = { "entities": [ {"id": "acme_corp", "type": "Organization", "industry": "SaaS", "founded": 2012}, {"id": "alice_chen", "type": "Person", "role": "CTO", "since": 2019}, ], "relationships": [ {"source": "alice_chen", "target": "acme_corp", "type": "works_for"}, ], } gen = OntologyGenerator(base_uri="https://semantica.dev/ontology/") ontology = gen.generate_ontology(data) classes = gen.infer_classes(data) props = gen.infer_properties(data, classes) optimized = gen.optimize_ontology(ontology) # Validate against SHACL shapes validator = OntologyValidator() report = validator.validate(ontology) # → ValidationResult(valid=True, consistent=True, satisfiable=True, errors=[], warnings=[]) semantica.conflicts: Conflict Detection & Resolution Detect and resolve conflicting facts from multiple sources before they corrupt your knowledge base.
from semantica.conflicts import ConflictDetector, ConflictResolver, SourceTracker entities_from_source_a = [ {"id": "alice_chen", "role": "CTO", "salary": 250_000, "start_date": "2019-03-01"}, ] entities_from_source_b = [ {"id": "alice_chen", "role": "VP Eng", "salary": 275_000, "start_date": "2019-03-01"}, ] # Detect all conflict types: value, type, relationship, temporal, logical detector = ConflictDetector() conflicts = detector.detect_conflicts(entities_from_source_a + entities_from_source_b) # → [Conflict(entity="alice_chen", field="role", values=["CTO","VP Eng"], severity="HIGH"), # Conflict(entity="alice_chen", field="salary", values=[250000,275000], severity="MEDIUM")] # Resolve using multiple strategies resolver = ConflictResolver() resolved = resolver.resolve_conflicts(conflicts, strategy="credibility_weighted") # weighted by source trust resolved = resolver.resolve_conflicts(conflicts, strategy="most_recent") # prefer most recent resolved = resolver.resolve_conflicts(conflicts, strategy="voting") # majority wins # Track source credibility over time tracker = SourceTracker() tracker.register_source("source_a", source_type="document", credibility_score=0.85) tracker.register_source("source_b", source_type="document", credibility_score=0.72) semantica.deduplication: Entity Resolution at Scale Block, cluster, and merge duplicates with semantic similarity.
from semantica.deduplication import DuplicateDetector, EntityMerger entities = [ {"id": "e1", "name": "Acme Corporation", "domain": "acme.com"}, {"id": "e2", "name": "Acme Corp.", "domain": "acme.com"}, {"id": "e3", "name": "ACME Corp", "domain": "acme.co"}, {"id": "e4", "name": "Globex Industries", "domain": "globex.com"}, ] detector = DuplicateDetector(similarity_threshold=0.75, use_clustering=True) candidates = detector.detect_duplicates(entities) groups = detector.detect_duplicate_groups(entities) # → DuplicateGroup(entities=["e1","e2","e3"], confidence=0.91, strategy="semantic+blocking") merger = EntityMerger(preserve_provenance=True) ops = merger.merge_duplicates(entities, strategy="keep_most_complete") history = merger.get_merge_history() semantica.normalize: Data Normalization & Cleaning Standardize text, entities, dates, numbers, and encodings before building your knowledge graph.
from semantica.normalize import ( TextNormalizer, EntityNormalizer, DateNormalizer, NumberNormalizer, DataCleaner, ) # Unicode, whitespace, casing, HTML tags, smart quotes text = TextNormalizer().normalize(" Acme Corp.'s Q4 report... ") # → "Acme Corp.'s Q4 report..." # Alias resolution + entity disambiguation with confidence scores canonical = EntityNormalizer().normalize_entity("ACME Corp.") # → NormalizedEntity(canonical="Acme Corporation", type="Organization", confidence=0.91) # Natural language date parsing with timezone conversion dt = DateNormalizer().normalize_date("3 weeks ago") # → datetime(2026, 7, 1, tzinfo=UTC) # Unit conversion and currency normalization price = NumberNormalizer().normalize_number("$1.25M USD") # → NormalizedNumber(value=1_250_000, currency="USD") # Deduplicate, validate, and impute missing values across a dataset clean = DataCleaner().clean_data(records, remove_duplicates=True, handle_missing=True) semantica.pipeline: Pipeline DSL Compose ingestion, extraction, and graph-building into a declarative, parallel pipeline.
from semantica.pipeline import PipelineBuilder, ExecutionEngine builder = PipelineBuilder() # add_step() returns the created PipelineStep, not the builder, so these don't chain builder.add_step("ingest", step_type="ingest", source="./contracts/", recursive=True) builder.add_step("extract", step_type="ner_extract") builder.add_step("relations", step_type="relation_extract") builder.add_step("build_kg", step_type="kg_build", merge_entities=True) builder.add_step("deduplicate", step_type="deduplicate", threshold=0.75) builder.add_step("export", step_type="export", format="turtle", output="kg.ttl") # connect_steps() and set_parallelism() return the builder, so these do chain pipeline = ( builder .connect_steps("ingest", "extract") .connect_steps("extract", "relations") .connect_steps("relations", "build_kg") .connect_steps("build_kg", "deduplicate") .connect_steps("deduplicate", "export") .set_parallelism(4) .build(name="contracts_pipeline") ) engine = ExecutionEngine() result = engine.execute_pipeline(pipeline) status = engine.get_pipeline_status(pipeline.name) progress = engine.get_progress(pipeline.name) Temporal Intelligence: Bi-Temporal Graphs & Time Travel Track when facts were true in the world vs. when they were recorded, and query either axis.
from semantica.export import ( RDFExporter, JSONExporter, ParquetExporter, LPGExporter, ReportGenerator, ) kg = {"entities": [...], "relationships": [...]} rdf = RDFExporter() turtle_str = rdf.export_to_rdf(kg, format="turtle") # returns string jsonld_str = rdf.export_to_rdf(kg, format="json-ld") rdf.export(kg, "kg_audit.ttl", format="turtle") rdf.export(kg, "kg_audit.jsonld", format="json-ld") rdf.export(kg, "kg_audit.nt", format="n-triples") # Columnar analytics - Snappy-compressed Parquet (writes kg_snapshot_entities.parquet # and kg_snapshot_relationships.parquet) ParquetExporter(compression="snappy").export_knowledge_graph(kg, "kg_snapshot") # JSON knowledge graph JSONExporter().export_knowledge_graph(kg, "kg.json") # Neo4j / Memgraph Cypher statements for graph database import LPGExporter().export(kg, "kg_import.cypher") # Human-readable HTML report ReportGenerator().generate_report( {"title": "KG Audit Report", "summary": "Weekly ingestion summary", "metrics": {"entities": len(kg["entities"])}}, file_path="audit_report.html", format="html", ) semantica.visualization: Interactive Graph Workbench Render force-directed graphs, community maps, ontology hierarchies, and temporal dashboards.
from semantica.visualization import ( KGVisualizer, OntologyVisualizer, EmbeddingVisualizer, TemporalVisualizer, ) import numpy as np kg = {"entities": [...], "relationships": [...]} # Interactive force-directed graph (opens in browser) viz = KGVisualizer(layout="force", color_scheme="default") viz.visualize_network(kg, output="interactive", file_path="kg.html") viz.visualize_communities(kg, communities, output="interactive") viz.visualize_centrality(kg, centrality, centrality_type="degree") viz.visualize_entity_types(kg, output="html", file_path="entity_types.html") # Ontology class hierarchy OntologyVisualizer().visualize_hierarchy(ontology, output="interactive") # 2D embedding projection (UMAP / t-SNE / PCA) EmbeddingVisualizer().visualize_2d_projection( embeddings=np.array([...]), labels=["entity_a", "entity_b"], method="umap", ) # Timeline scrubber - watch the graph evolve TemporalVisualizer().visualize_timeline(kg, output="interactive") Multi-Agent Shared Context with Agno One shared intelligence layer. All agents read and write to the same context graph.
# pip install semantica[agno] from agno.agent import Agent from agno.team import Team from agno.models.anthropic import Claude from semantica.context import ContextGraph from semantica.vector_store import VectorStore from integrations.agno import AgnoSharedContext, AgnoDecisionKit, AgnoKGToolkit shared = AgnoSharedContext( vector_store=VectorStore(backend="faiss"), knowledge_graph=ContextGraph(advanced_analytics=True), decision_tracking=True, ) researcher = Agent( name="Researcher", model=Claude(id="claude-sonnet-4-5"), memory=shared.bind_agent("researcher"), tools=[AgnoKGToolkit(context=shared)], ) analyst = Agent( name="Analyst", model=Claude(id="claude-sonnet-4-5"), memory=shared.bind_agent("analyst"), tools=[AgnoDecisionKit(context=shared)], ) team = Team(agents=[researcher, analyst], mode="coordinate") # Researcher's findings are instantly available to the Analyst - no copy, no sync → runnable notebooks in the cookbook, each self-contained and runnable in under 5 minutes
The audit-trail recipe is above. Here are three more common patterns.
Measured on a 118,000-node production graph (AMD EPYC, 64 GB RAM); the deduplication/candidate-generation figures are historical measurements recorded in CHANGELOG.md rather than an automated tests/ assertion. Results vary by hardware, dataset topology, and backend selection — run pytest tests/vector_store/test_performance_benchmarks.py -s to measure your own data.
Every capability is available from the terminal. The CLI ships with the package, no separate install required.
pip install semantica semantica # startup dashboard semantica doctor # health check semantica --help # full grouped command reference Start with semantica, verify with doctor, build a graph, and explore the command groups from one terminal.
Command groups: ingest · parse · extract · kg · reason · decision · temporal · provenance · ontology · embed · deduplicate · validate · export · visualize · pipeline · server · explorer · mcp · doctor · shell · init · watch
Native plugin bundles for Claude Code, Cursor, Codex, Windsurf, Cline, Continue, VS Code, OpenClaw, and pi; a full-featured MCP server for any MCP-compatible client; a comprehensive REST API; and first-class Agno, CrewAI, and LangChain support for agentic frameworks. Every major LLM provider is already supported via semantica.llms and LiteLLM: OpenAI, Anthropic, Gemini, Mistral, Llama, Groq, Cohere, Azure, Bedrock, Ollama, DeepSeek, HuggingFace, and more.
MCP setup takes 30 seconds — see MCP Server below.
Fork additions beyond upstream semantica-agi/semantica: the MinerU PDF parser — MinerUParser for scanned, formula-heavy, and CJK documents (LaTeX formula recovery, strong OCR; pip install "semantica[parse-mineru]", integration guide, includes a measured benchmark against DoclingParser) — plus a full Chinese documentation set (docs_zh/) with a frozen EN↔ZH glossary. Everything else tracks upstream.
Connect any MCP-compatible client (Claude Desktop, Windsurf, Cline, VS Code) in 30 seconds:
python -m semantica.mcp_server # or via the installed entry point semantica-mcp { "mcpServers": { "semantica": { "command": "python", "args": ["-m", "semantica.mcp_server"] } } } Tools exposed over MCP:
# Start the backend python -m semantica.server # port 8000 # Extract entities & relations via REST curl -X POST http://localhost:8000/api/enrich/extract \ -H "Content-Type: application/json" \ -d '{"text": "Apple CEO Tim Cook announced record earnings."}' # List recorded decisions curl "http://localhost:8000/api/decisions?category=vendor_selection" # Query the knowledge graph curl "http://localhost:8000/api/graph/node/acme_corp/neighbors?depth=2" REST endpoints span: enrich (extract) · graph · decisions · reasoning · provenance · ontology · embeddings · search · export · pipeline · temporal · deduplication
Domain skills: extract · ingest · query · ontology · validate · deduplicate · embed · reason · decision · causal · temporal · provenance · policy · explain · export · change · visualize
Specialized agents: kg-assistant · decision-advisor · explainability
Bundles for Claude Code, Cursor, Codex, pi, Windsurf, Cline, Continue, VS Code, and OpenClaw in plugins/.
A browser-based graph workbench. Pan and zoom live graphs, scrub the timeline, review every decision's causal chain, resolve duplicates, and author your ontology visually. Built on React 19 + Sigma.js.
pip install "semantica[explorer]" semantica-explorer --graph my_graph.json # Dashboard opens at http://127.0.0.1:8000 For contributor / dev-server setup: explorer/README.md: Local Setup Guide
The CLI exposes the loaded ContextGraph. To also browse and edit an existing AgentMemory, create the ASGI app programmatically with both live objects:
from semantica.context import AgentMemory, ContextGraph from semantica.explorer.app import create_app from semantica.explorer.session import GraphSession graph = ContextGraph() memory = AgentMemory() app = create_app(session=GraphSession(graph), agent_memory=memory) The Memories workspace is shown only when agent_memory is provided. Apply updates the supplied runtime object; it does not add disk persistence.
Core install just got 4x lighter. Direct dependencies dropped from 44 to 22 packages — heavy ML/NLP, visualization, document-parsing, and ingestion libraries (torch, spacy, sentence-transformers, matplotlib, faiss-cpu, python-docx, and more) moved into granular optional extras. pip install "semantica[all]" keeps the old fully-bundled behavior. This is also the first release requiring Python 3.10+ (3.8/3.9 support dropped; 3.14 not yet supported), with a committed uv.lock for reproducible dev installs:
Breaking changes: Entity.confidence is now Optional[float] (was float = 1.0) so unmeasured confidence is no longer indistinguishable from a perfect score; PolicyEngine.check_compliance now raises ProcessingError (previously returned False) for rules it cannot evaluate; the dev extra is gone in favor of a PEP 735 dependency group; semantica[crewai] no longer installs crewai automatically.
Also fixes 40+ correctness bugs (in-memory vector-ID reuse corrupting live vectors, FAISS/Qdrant/Milvus vector-store gaps, Explorer temporal-scrubber and ontology-linking bugs, CLI commands calling nonexistent APIs, and more) and a large batch of documentation corrections across the site.
pip install semantica # lightweight core (22 essential dependencies) pip install "semantica[all]" # full bundled behavior with all extras Note: Heavy machine learning, NLP, visualization, and document dependencies live in optional extras to keep core installation lightweight and fast. If you want the previous bundled installation, install with pip install "semantica[all]".
# Granular Extras pip install "semantica[documents]" # Document parsing (docx, openpyxl, lxml, beautifulsoup4) pip install "semantica[parse-pdf]" # Default PDF parsing (pdfplumber) pip install "semantica[parse-docling]" # DoclingParser: complex layouts, tables, OCR pip install "semantica[parse-mineru]" # MinerUParser: scanned/formula-heavy/CJK PDFs (fork addition) pip install "semantica[embeddings-local]" # Local embeddings (sentence-transformers, fastembed, onnxruntime) pip install "semantica[models-huggingface]" # HuggingFace models (transformers, torch) pip install "semantica[nlp-spacy]" # spaCy NLP pipelines (spacy) pip install "semantica[viz]" # Visualization (matplotlib, seaborn, plotly, pyvis, graphviz) pip install "semantica[media]" # Audio & computer vision (librosa, opencv-python) pip install "semantica[graph-embeddings]" # Knowledge graph embeddings (gensim / Node2Vec) pip install "semantica[ingest-git]" # Git repository ingestor (GitPython) pip install "semantica[vectorstore-faiss]" # FAISS vector store pip install "semantica[vectorstore-all]" # All vector stores (Qdrant, Pinecone, Weaviate, FAISS, PgVector, SQLite) pip install "semantica[agno]" # Agno multi-agent integration pip install "crewai>=0.80.0" # CrewAI integration (no semantica extra — see integrations/crewai/README.md) pip install "semantica[langchain]" # LangChain / LangGraph integration pip install "semantica[llm-all]" # All LLM provider clients pip install "semantica[graph-neo4j]" # Neo4j graph store (LPG) pip install "semantica[graph-falkordb]" # FalkorDB graph store (LPG) pip install "semantica[graph-apache-age]" # Apache AGE graph store (LPG) pip install "semantica[graph-amazon-neptune]" # AWS Neptune graph store (LPG) pip install "semantica[tripletstore-oxigraph]" # Embedded in-memory/on-disk RDF store # RDF triple stores (Blazegraph, Apache Jena, Eclipse RDF4J) need no extra: # semantica.triplet_store talks SPARQL over HTTP using the core `requests` dependency pip install "semantica[db-snowflake]" # Snowflake pip install "semantica[db-databricks]" # Databricks (SDK + SQL connector) pip install "semantica[ingest-sap]" # SAP OData pip install "semantica[ingest-servicenow]" # ServiceNow Table API pip install "semantica[ingest-parquet]" # Parquet / PyArrow pip install "semantica[ingest-arrow]" # Apache Arrow, Feather, IPC pip install "semantica[watch]" # Directory file watcher pip install "semantica[explorer]" # Knowledge Explorer dashboard For production deployments, use Docker or Kubernetes rather than a local pip install. Set SEMANTICA_API_KEY, configure a persistent LPG graph store (Neo4j / FalkorDB / Apache AGE / AWS Neptune) and/or RDF triple store (Blazegraph / Apache Jena / Eclipse RDF4J), and point the vector store at a hosted backend (Qdrant / Pinecone). See ARCHITECTURE.md for the full deployment topology.
# From source git clone https://github.com/semantica-agi/semantica.git cd semantica && pip install -e . --group dev && pytest tests/ CI & Deployment Wiring semantica into your own CI is a two-minute job. On GitHub Actions, use the reusable composite action:
- uses: semantica-agi/semantica/.github/actions/setup-semantica@main with: python-version: '3.11' Copy-paste starting templates for GitHub Actions, GitLab CI, and CircleCI live in examples/ci/. The published package itself is verified installable across Ubuntu/macOS/Windows and Python 3.10-3.13 every week by the Install Matrix workflow.
Ready-made deployment configs for AWS, GCP, Azure, Fly.io, Railway, Render, Kubernetes, and Helm are in deploy/.
On-premises deployment · Private cloud · Custom domain implementations · SLA-backed support · Professional services for regulated industries (finance, healthcare, legal, government).
getsemantica.ai for enterprise solutions and pricing.
All contributions are welcome: bug fixes, features, tests, and documentation.
If you use Semantica in your research or production systems, please cite it as:
@software{semantica2026, title = {Semantica: Graph-Native Infrastructure for Context and Accountable AI Systems}, author = {Mohammad Kaif}, year = {2026}, url = {https://github.com/semantica-agi/semantica} } All citation formats (APA, MLA, Chicago, IEEE) live on the Citation page — every format attributes authorship to Semantica, not individual contributors.
GitHub · Discord · Twitter/X · Website · Docs · PyPI
If this project helps you build better AI, a star means a lot.
English · Deutsch · Français · Español · Italiano · Português · العربية · اردو · हिन्दी · 中文 · 日本語 · 한국어
llm-openai llm-groq llm-gemini llm-anthropic llm-ollama llm-deepseek llm-novita llm-litellm llm-instructor llm-typesafe llm-all documents parse-docling parse-mineru parse-pdf shacl db-snowflake db-databricks db-arrow db-salesforce db-redshift db-cassandra db-bigquery ingest-looker ingest-parquet ingest-arrow ingest-sap ingest-servicenow ingest-airflow ingest-git db-all models-huggingface embeddings-local nlp-spacy graph-neo4j graph-falkordb graph-amazon-neptune graph-apache-age graph-embeddings graph-all tripletstore-oxigraph vectorstore-faiss vectorstore-qdrant vectorstore-weaviate vectorstore-pinecone vectorstore-milvus vectorstore-pgvector vectorstore-sqlite vectorstore-all infra cloud monitoring viz media gpu agno langchain google-adk open-ontologies watch split-tiktoken split-community split-topic split-all explorer explorer-lite all
knowledge-graph context-graph ai-agents llm decision-intelligence provenance explainability reasoning-engine entity-extraction relation-extraction graph-rag knowledge-intelligence semantic-layer nlp embeddings ontology rdf triplet-extraction agentic-ai knowledge-base entity-resolution w3c-prov audit-trail
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 28, 2026.




