专为具备上下文感知能力且可追溯的 AI 系统打造的原生图计算基础设施
面向 AI 智能体的开源 Palantir
您可以导入企业数据,提取关键信息,构建上下文图与知识图谱(KG),并对所有数据执行图分析及因果推理,同时完整记录决策的来源。该方案从设计之初就注重可解释性、可追溯性与可靠性。
决策智能 · 上下文管理 · 确定性推理 · 本体管理 · 知识建模 · 端到端可追溯性
开源 · 可自行托管 · 可审计 · 受到规范约束 · 无供应商锁定风险
多格式图存储 · 支持 RDF 与 LPG · 遵循 W3C 标准 · 具备互操作性
专为高风险、受监管领域打造
pip install semantica
大多数 AI 智能体在运行时不会留下任何痕迹。它们存储的是嵌入向量而非实际含义:这样的上下文无法被解释,做出的决策也无法被审计。在贷款业务中,这种缺陷并非仅仅是不便,更是合规风险——审核人员几个月后仍需能够解释智能体的审批决策。
Semantica 作为一层确定性的基础设施,位于您的 LLM、向量存储库及智能体框架之下:构建图结构、执行推理或追踪决策来源时均无需依赖 LLM。
适用对象:
- AI/ML 平台团队:那些需要基于零散的原始数据构建结构化、可查询的上下文以做出关键决策的团队,他们需要的不仅仅是向量索引。
- 使用 Databricks 或 Snowflake 的数据平台团队:他们需要将已存储在 Unity Catalog 或 Snowflake 仓库中的表格转换为受管控、具有完整溯源信息的知识图谱,而无需先将该数据导出到第三方 SaaS 平台。
- 合规、风控与审计团队:他们需要以监管机构能够接受的格式,获得“AI 为何会如此操作?”的明确答案。
- 受监管的企业(金融、医疗、法律、政府、国防领域):这类企业无法使用黑盒系统,也无法将数据发送到其他人的 SaaS 平台来获取此类功能。
- 平台与基础设施工程师:他们希望知识图谱、推理及溯源相关功能能够自主托管且可更换,而不受限于某一家供应商的后端系统。
- 数据与知识工程师:他们需要从杂乱的多源数据中构建知识图谱:能够提取实体与关系,对冲突或矛盾的事实进行标记而非默默覆盖,同时在冗余数据演变成噪声之前将其合并。
快速入门 · 架构 · 您将获得什么 · 为何选择 Semantica · 决策智能 · 上下文图谱 · 审计追踪方案 · 模块参考 · 集成方案 · CLI 工具 · 性能表现 · 安装指南
Semantica 能为您带来什么
- 上下文图谱: 一个结构化且可查询的图谱,涵盖了智能体所知晓、做出的决策以及推理过程中的所有内容
- 决策智能: 每一项决策都被视为一级对象:可追溯、可通过先例检索,并且存在因果关联
- AI 治理与本体管理: 支持 SHACL 约束、冲突检测、合规规则、OWL 生成,同时还提供带有可视化编辑器的 SKOS 词汇表管理功能
- 完全的可审计性: 每个事实都遵循 W3C PROV-O 标准进行溯源,审计轨迹可导出为 JSON、CSV 或 RDF 格式
- 确定性推理: 支持前向链接、Rete 网络、Datalog 以及 SPARQL,所有推理路径均可完全解释,而非黑箱操作
- 知识处理流程: 支持多源数据整合、基于实体的分块处理、命名实体识别/关系/事件提取以及知识图谱构建,整个流程还包含语义去重和保留溯源信息的合并功能
- 企业级数据平台: 提供针对 Databricks(Unity Catalog + Delta Lake、PAT/OAuth M2M 认证、目录/模式/表/血缘关系查询)以及 Snowflake(仓库/数据库/模式、密钥对及 OAuth 认证)的原生连接器,这样存储在湖仓或仓库中的表即可直接成为带有溯源信息的图节点,无需再进行额外的导出/导入操作
- 图分析功能: 可针对刚刚构建的图谱执行中心性分析、社区检测、链接预测以及最短路径查询
- 多格式图存储支持: 支持原生 RDF 格式(通过 SPARQL 连接 Oxigraph、Blazegraph、Apache Jena、Eclipse RDF4J)以及带标签的属性图格式(Neo4j、FalkorDB、Apache AGE、通过 Cypher 连接的 AWS Neptune),同时还支持向量存储,所有这些格式均可在不修改代码的情况下相互切换
- 可视化功能: 可在交互式浏览器工作台中查看任意图谱、本体或时间线
- 即插即用式集成: 支持原生 Agno 功能,配有功能完备的 MCP 服务器、功能全面的命令行界面、REST API,同时还为各类主流编辑器提供了插件支持
| Vector DB + RAG | 普通 LLM 内存 | Semantica | |
|---|---|---|---|
| 召回方法 | 嵌入相似度 | 令牌窗口 | 图遍历 + 语义搜索 |
| 决策历史 | 不存储 | 不存储 | 一级可查询对象 |
| 来源追溯 | 无 | 无 | W3C PROV-O,源链接 |
| 推理能力 | 无 | 黑盒 | 前向链、Rete、Datalog、SPARQL |
| 冲突检测 | 静默覆盖 | 静默覆盖 | 检测、标记并解决 |
| 时间回溯 | 不支持 | 不支持 | 点态图快照 |
| 合规性导出 | 无 | 无 | PROV-O、SHACL、OWL、RDF |
| 策略执行 | 无 | 无 | 内置规则引擎 + SHACL |
| 实体解析 | 不支持 | 不支持 | 阻止机制 + 语义去重 |
| 多智能体上下文 | 每个智能体独立处理 | 每个智能体独立处理 | 单一共享智能层 |
Semantica 是对您现有技术栈的补充,而非替代品。您可以保持现有的 LLM、向量存储和智能体框架不变;Semantica 会在其之上添加决策记录、因果推理、来源追溯、本体治理、冲突检测以及审计追踪功能。其推理引擎、知识图谱构建和来源追溯层均为完全确定性的;使用它们无需依赖 LLM。
快速入门
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
5 秒内验证您的安装情况:
semantica doctor
# Python 3.11.9 pass
# semantica 0.6.0 pass
# faiss vector store pass
# Config file pass ~/.semantica/config.yaml
如果 Semantica 能为您解决实际问题,给它点个星吧,这样其他人也能找到它。
架构
Semantica 是一个真正的端到端流程,而非仅带有营销名称的单一库。下方的每个阶段都是可独立导入的正式发布模块:
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
- 摄取: 文件、网页、数据库、企业数据平台(Databricks、Snowflake)、云服务(Google Drive、Elasticsearch)、数据流(Kafka、Kinesis)、Git、电子邮件、MCP
- 解析 → 规范化 → 分割: 文档解析、文本/实体/日期规范化、基于 GraphRAG 的具备实体感知能力的分块处理
- 提取 → 冲突检测 → 去重: 名词实体识别、关系识别、事件识别、三元组识别;在信息合并之前识别并解决冲突事实
- 知识图谱:
GraphBuilder负责构建图结构;在此基础之上可进行双时间维度的事实分析以及完整的图分析(中心性分析、社区检测、链接预测) - 本体论 · 推理 · 起源追踪 · 决策: 作为位于知识图谱之上的智能层,具备 SHACL/OWL 管理机制、Rete/Datalog/SPARQL 推理功能、W3C PROV-O 起源追踪机制,以及一流的决策记录功能
- 存储: 采用多格式存储设计,包括 RDF 三元组存储(嵌入式 Oxigraph、Blazegraph、Apache Jena、Eclipse RDF4J)、带标签的属性图存储(Neo4j、FalkorDB、Apache AGE、AWS Neptune)以及向量存储,所有存储方式均可更换而无需修改代码
- 输出结果: 导出数据(RDF、OWL、Parquet、Cypher、JSON-LD)、交互式可视化展示,以及通过 REST API、MCP 服务器或 CLI 进行访问
→ 完整的 Mermaid 图表,展示处理流程及决策智能生命周期
决策智能
决策智能将每一次 AI 决策从临时的推理结果转化为永久的、可审计的、可查询的记录。它能够回答“AI 做出了什么决策、为何如此决策,以及随后发生了什么?”——这是监管机构和企业风险团队日益迫切想要了解的问题。
在 Semantica 中,一个决策并非简单的日志行,而是一个拥有完整生命周期的一流图节点。在受监管的行业领域,每一个 AI 决策都必须可追溯至源头,并能经得起审计人员的核查:record_decision() 会生成可导出为 W3C PROV-O 格式的永久性结构化记录,而该格式正是大多数合规框架要求用于向监管机构提交信息的格式。
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()
上下文图谱
上下文图谱是传统 RAG 所缺乏的结构化记忆层。与只能回答“什么内容相似?”的扁平嵌入模型不同,上下文图谱能够回答“什么内容相互关联、为何关联以及如何关联?”。每一个实体、关系、决策和事实都是一流节点,可通过图遍历方式被查询。实体会与源文档相连,决策会与证据及后果相连,事实会附带完整的来源信息,同时冲突会被检测出来,而不会被悄悄覆盖。
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?")
为何要在嵌入向量之上构建图结构: 遍历能够发现嵌入向量所遗漏的关联关系(例如,与某份合同相距三步的人);每个节点都带有来源信息,因此你可以随时询问“这是从哪里来的?”;在冲突破坏知识库之前就能将其标记出来;基于时间点的快照让你无需重新处理即可回放历史记录。
方案:受监管决策的审计追踪
核心模式:记录具有因果关联的决策链,为每个实体附加来源信息,并导出符合监管要求的审计追踪记录。
from semantica.context import ContextGraph
from semantica.provenance import ProvenanceManager
from semantica.export import RDFExporter
graph = ContextGraph(advanced_analytics=True)
prov = ProvenanceManager(storage_path="./audit.db")
# Record the decision chain
d1 = graph.record_decision(
category="drug_interaction_check", scenario="Patient P-4821: warfarin + amiodarone co-prescribed",
reasoning="Amiodarone potentiates warfarin's anticoagulant effect", outcome="flag_for_review", confidence=0.91,
)
d2 = graph.record_decision(
category="dosage_adjustment", scenario="INR monitoring plan for P-4821",
reasoning="Reduce warfarin dose per interaction severity; recheck INR in 5 days", outcome="dose_reduced_30pct", confidence=0.87,
)
# relationship_type must be one of CAUSED, INFLUENCED, or PRECEDENT_FOR
graph.add_causal_relationship(d1, d2, relationship_type="CAUSED")
# Track provenance for every entity
prov.track_entity("patient_P4821", source="ehr/medication_orders_2024.json",
metadata={"extractor": "NamedEntityRecognizer"})
# Export W3C PROV-O for regulator submission - RDFExporter expects
# {"entities": [...], "relationships": [...]}, so map ContextGraph.to_dict()'s
# {"nodes": [...], "edges": [...]} shape onto it first
graph_dict = graph.to_dict()
kg = {
"entities": [{"id": n["id"], "type": n["type"], "text": n["content"]} for n in graph_dict["nodes"]],
"relationships": [
{"source_id": e["source"], "target_id": e["target"], "type": e["type"]}
for e in graph_dict["edges"]
],
}
RDFExporter().export(kg, "audit_trail.ttl", format="turtle")
更多方案(GraphRAG 流水线、反洗钱规则引擎、一次性完成本体到知识图谱的转换)详见下方的 更多方案。
探索该平台
下方的每个模块均可独立导入,且都配有经过当前源代码树验证的可用代码示例;你可以选择使用其中一个或全部模块。
| 模块 | 功能说明 |
|---|---|
semantica.ingest | 文件、网页、数据库、API、数据流、电子邮件、Git、Parquet、Databricks、Snowflake、MCP |
semantica.semantic_extract | 名词实体识别、关系抽取、事件检测、三元组生成 |
semantica.kg | 图结构构建、中心性分析、社区检测、链接预测 |
semantica.reasoning | 正向链式推理、Rete 算法、Datalog 逻辑、SPARQL 查询、完全可解释性 |
semantica.vector_store | FAISS、Qdrant、Weaviate、Milvus、Pinecone、PgVector、混合搜索 |
semantica.split | 为 GraphRAG 提供具备实体感知、关系感知及本体感知的文本分块功能 |
semantica.provenance | 为每个事实提供 W3C PROV-O 来源追踪信息 |
semantica.ontology | OWL 本体生成、SHACL 验证、SKOS 词汇表处理 |
semantica.conflicts | 检测并解决来自不同来源的冲突事实 |
semantica.deduplication | 大规模实体解析 |
semantica.normalize | 文本、实体、日期及数字的标准化处理;数据集清洗 |
semantica.pipeline | 用于数据导入 → 提取 → 构建 → 导出的声明式并行流水线 DSL |
semantica.export | RDF、OWL、Parquet、Cypher、JSON-LD 格式支持 |
semantica.visualization | 强导向图、本体层次结构、时间序列仪表板 |
| 时间智能 | 双时间维度事实、Allen 区间代数、时间旅行分析 |
| 多智能体(Agno) | 团队中每个智能体共享同一个上下文图 |
↓ 点击下方的 模块参考 查看每个模块的可用示例,或跳转至 更多方案、完整的 集成方案 表格、MCP 工具列表 以及 REST 接口。**
模块参考
点击下方任意模块即可查看其可运行的示例。
semantica.ingest:多源数据导入
可通过统一接口,从文件、网页、数据库、API、数据流、电子邮件、Git 仓库、Parquet 格式数据、Databricks 平台、Snowflake 服务或 MCP 服务器中导入数据。
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)
安全提示: 绝不要在生产代码中硬编码凭证(
token、password、private_key);应通过环境变量(例如DATABRICKS_TOKEN、SNOWFLAKE_PASSWORD)或密钥管理工具来传递这些凭证。
支持的来源: 本地文件(PDF、DOCX、PPTX、HTML、TXT、CSV、JSON、YAML、Excel、XML)· 网页 · RSS/Atom 订阅源 · REST API · 数据库(PostgreSQL、MySQL、SQLite、Oracle、SQL Server)· Parquet 数据集 · Databricks(Unity Catalog + Delta Lake)· Snowflake · Git 仓库 · 电子邮件(IMAP/POP3)· 消息流(Kafka、RabbitMQ、Kinesis、Pulsar)· MCP 资源 · Apache Arrow/Feather/IPC(ArrowIngestor)
DuckDB、Elasticsearch、Google Drive、HuggingFace、MongoDB 以及 Pandas 数据的导入功能也已实现(DuckDBIngestor、ElasticIngestor、GDriveIngestor、HuggingFaceIngestor、MongoIngestor、PandasIngestor),但目前还无法从顶层semantica.ingest命名空间中重新导出这些数据——可直接导入:from semantica.ingest.duckdb_ingestor import DuckDBIngestor。
semantica.semantic_extract:命名实体识别、关系提取、事件识别、三元组提取
仅需一次处理即可从原始文本中提取结构化知识。
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"), ...]
针对多份文档的批量处理会使用ner.process_batch([...]),而非在接口类中为每次调用单独执行extract_entities_batch操作。
semantica.kg:知识图谱构建与分析
可从文档中构建可用于实际应用的知识图谱,并在其上运行图算法。
from semantica.ingest import FileIngestor
from semantica.kg import (
GraphBuilder,
GraphAnalyzer,
CentralityCalculator,
CommunityDetector,
PathFinder,
LinkPredictor,
BiTemporalFact,
)
from datetime import datetime
# Build KG - merge duplicate entities, track temporal edges
sources = FileIngestor().ingest_directory("./contracts/", recursive=True)
kg = GraphBuilder(merge_entities=True, enable_temporal=True).build(sources)
# Graph analytics
analyzer = GraphAnalyzer()
analysis = analyzer.analyze_graph(kg) # full graph metrics
centrality = CentralityCalculator()
degree = centrality.calculate_degree_centrality(kg) # most-connected entities
betweenness = centrality.calculate_betweenness_centrality(kg)
communities = CommunityDetector().detect_communities(kg, method="louvain") # natural clusters
path = PathFinder().find_shortest_path(kg, "alice_chen", "contract_001")
predictions = LinkPredictor().predict_links(kg, top_k=10) # relationship predictions
# Bi-temporal facts - track valid time vs. recorded time independently
fact = BiTemporalFact(
valid_from=datetime(2024, 3, 1),
valid_until=datetime(2025, 1, 1),
recorded_at=datetime(2024, 3, 5),
)
semantica.reasoning:前向链式推理、Rete 推理、Datalog 逻辑、SPARQL 查询
可执行可解释的基于规则的推理,而非依赖黑箱机制。
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"}]
当前限制: 在本版本中,
ReteEngine的 alpha-node 条件匹配器被刻意设计得较为简单——在将其接入生产环境合规检查环节之前,请先根据实际的规则集验证match_patterns()的输出;更具选择性的条件评估功能正在规划中。
# 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:混合式与过滤型语义搜索
这是一款即插即用的向量存储解决方案,支持多种后端、混合搜索模式以及基于决策的检索功能。
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"])
支持的后端: faiss · qdrant · weaviate · milvus · pinecone · pgvector · sqlite · inmemory
semantica.split:专为 GraphRAG 设计的文档分块功能
该功能会考虑知识图谱结构,从而保留实体边界、关系三元组以及本体概念,这对于 GraphRAG 工作流而言至关重要。
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)
支持的方法: recursive · token · sentence · paragraph · semantic_transformer · entity_aware · relation_aware · graph_based · ontology_aware · hierarchical · community_detection · centrality_based · llm
semantica.provenance:W3C PROV-O Lineage
每个事实都会与其来源相关联。没有黑箱,也没有难以理解的输出结果。
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 生成、SHACL 验证
从数据中生成本体,验证结构,并管理词汇表。
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:冲突检测与解决
在冲突事实破坏知识库之前,检测并解决来自多个来源的冲突。
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:大规模实体解析
利用语义相似度来阻止、聚类并合并重复项。
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:数据规范化与清洗
在构建知识图谱之前,对文本、实体、日期、数字及编码进行标准化处理。
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:管道 DSL
将数据摄取、提取及图构建功能组合成一个声明式的并行管道。
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:双时间图与时间旅行
追踪事实在“现实世界”中为真的时间点与被“记录”下来的时间点,并可对任一维度进行查询。
from semantica.context import ContextGraph
from semantica.kg import (
BiTemporalFact,
TemporalGraphQuery,
TemporalNormalizer,
)
from datetime import datetime
graph = ContextGraph(advanced_analytics=True)
graph.add_node("alice_chen", "Person", role="VP Engineering")
graph.add_node("acme_corp", "Organization", valuation=1_200_000_000)
# A temporally-bounded edge - valid_from/valid_until define when it held true
graph.add_edge(
"alice_chen", "acme_corp", edge_type="works_for",
valid_from="2024-03-01T00:00:00", valid_until="2025-01-01T00:00:00",
)
# Point-in-time snapshots - replay history without reprocessing
snapshot_2023 = graph.state_at("2023-06-01")
snapshot_2024 = graph.state_at("2024-01-01")
# Bi-temporal facts - valid_time is when true in the world;
# recorded_at is when you learned about it
fact = BiTemporalFact(
valid_from=datetime(2024, 3, 1),
valid_until=datetime(2025, 1, 1),
recorded_at=datetime(2024, 3, 5),
)
# Query facts valid within a time window - query_time_range() expects
# {"relationships": [...]} with source_id/target_id keys, which differs from
# ContextGraph.to_dict()'s {"nodes", "edges"} shape, so map it first
graph_dict = graph.to_dict()
kg_relationships = {
"relationships": [
{**e, "source_id": e["source"], "target_id": e["target"]}
for e in graph_dict["edges"]
]
}
tq = TemporalGraphQuery()
facts_in_window = tq.query_time_range(
kg_relationships, query="valid_facts", start_time="2024-01-01", end_time="2024-12-31"
)
# Normalize natural language temporal expressions - returns a (start, end) range
norm = TemporalNormalizer()
start, end = norm.normalize("last quarter")
semantica.export:RDF、OWL、Parquet、Cypher、JSON-LD
可导出为监管机构、图数据库或下游系统所要求的任何格式。
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:交互式图工作台
可渲染力导向图、社区映射、本体层次结构以及时间仪表板。
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")
带 Agno 的多智能体共享上下文
一个共享的智能层。所有智能体均可读取和写入同一个上下文图。
# 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
→ cookbook 中的可运行笔记本,每个都独立完整,可在 5 分钟内运行完毕
更多示例
核心的审计追踪示例见上文。以下是另外三种常见的模式。
端到端 GraphRAG 管道
from semantica.ingest import FileIngestor
from semantica.split import TextSplitter
from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor
from semantica.kg import GraphBuilder
from semantica.vector_store import VectorStore, HybridSearch
from semantica.context import AgentContext
# 1. Ingest
docs = FileIngestor().ingest_directory("./docs/", recursive=True)
# 2. Entity-aware chunking - never splits an entity across a chunk boundary
splitter = TextSplitter(method="entity_aware", chunk_size=1000)
chunks = [splitter.split(doc["text"]) for doc in docs]
# 3. Extract entities and relations
ner = NamedEntityRecognizer(confidence_threshold=0.7)
rel_ext = RelationExtractor(confidence_threshold=0.6)
entities = [ner.extract_entities(chunk) for chunk_group in chunks for chunk in chunk_group]
# 4. Build KG
kg = GraphBuilder(merge_entities=True, enable_temporal=True).build(docs)
# 5. Hybrid retrieval
vs = VectorStore(backend="inmemory")
ctx = AgentContext(vector_store=vs, knowledge_graph=kg)
ctx.store("Alice approved the Acme renewal in Q1 2024", conversation_id="c1")
results = HybridSearch(vector_store=vs).search("who approved the renewal?")
AML 规则引擎
from semantica.reasoning import ReteEngine, Rule, Fact, RuleType
rete = ReteEngine()
rete.build_network([
Rule(
rule_id="sanctions_check",
name="Flag sanctioned-country transactions",
conditions=[
{"field": "amount", "operator": ">", "value": 10_000},
{"field": "country", "operator": "in", "value": ["IR", "KP", "SY", "CU"]},
],
conclusion="flag_for_compliance_review",
rule_type=RuleType.IMPLICATION,
),
])
# Run the rule across a batch of incoming transactions, not just one
for tx in [
Fact("tx_101", "transaction", [{"amount": 25_000, "country": "IR"}]),
Fact("tx_102", "transaction", [{"amount": 4_500, "country": "DE"}]),
Fact("tx_103", "transaction", [{"amount": 60_000, "country": "KP"}]),
]:
rete.add_fact(tx)
flagged = rete.match_patterns()
与上文相同的条件匹配注意事项仍然适用——在实际使用前需根据自身的规则集进行验证。
一次遍历实现本体到知识图谱的转换
from semantica.ingest import FileIngestor
from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor
from semantica.kg import GraphBuilder
from semantica.ontology import OntologyGenerator, OntologyValidator
from semantica.export import RDFExporter
sources = FileIngestor().ingest_directory("./contracts/")
ner = NamedEntityRecognizer(confidence_threshold=0.7)
entities = ner.process_batch([s["text"] for s in sources])
kg = GraphBuilder(merge_entities=True).build(sources)
gen = OntologyGenerator(base_uri="https://myco.dev/ontology/")
ont = gen.generate_ontology({"entities": entities[0], "relationships": []})
report = OntologyValidator().validate(ont)
if report.valid:
RDFExporter().export({"entities": entities[0]}, "ontology.ttl", format="turtle")
主要功能概览
| 功能 | 特点 |
|---|---|
| 上下文图谱 | 可查询的实体、决策、关系图谱;因果关联;跨图谱导航 |
| 决策智能 | record_decision · trace_decision_chain · find_similar_decisions · analyze_decision_impact · check_decision_rules |
| 时间智能 | 瞬时快照 · Allen区间代数(13种关系)· TemporalNormalizer · 双时间线溯源 |
| 距离智能 | N×N语义距离矩阵 · 以自我为中心的可视化展示 · 距离区间 · 嵌入式缓存 |
| 语义提取 | 名词实体识别 · 关系提取 · 事件检测 · 三元组生成 · 共指识别 |
| 推理引擎 | 前向链接推理 · Rete推理 · 演绎推理 · 归纳推理 · SPARQL查询 · 具有可解释输出的结果的Datalog |
| GraphRAG分块 | 考虑实体特征 · 考虑关系特征 · 基于图谱的分块 · 考虑本体特征 · 基于社区检测的分块 |
| 冲突检测 | 值冲突 / 类型冲突 / 关系冲突 / 时间冲突 / 逻辑冲突 · 多种解决策略 |
| 溯源功能 | W3C PROV-O标准 · 每个事实均可追溯到来源 · 审计日志以JSON/CSV/RDF格式导出 |
| 本体中心平台 | SHACL Studio工具 · 可视化编辑器 · 跨本体对齐功能 · 健康状况监控面板 |
| 向量存储 | FAISS · Pinecone · Weaviate · Qdrant · Milvus · PgVector · 混合搜索与过滤搜索 |
| 图数据库(LPG) | Neo4j · FalkorDB · Apache AGE · AWS Neptune |
| 三元组存储(RDF) | Oxigraph(嵌入式)· Blazegraph · Apache Jena · Eclipse RDF4J · 统一的TripletStore接口 · SPARQL查询与批量导入功能 |
| 企业级数据平台 | Databricks(DatabricksIngestor:Unity Catalog + Delta Lake,PAT/OAuth M2M功能,表/查询导入功能,以及对目录/模式/表/数据血缘关系的查询功能)· Snowflake(SnowflakeIngestor:数据仓库/数据库/模式管理,密码/密钥对/OAuth认证功能) |
| 大语言模型提供商 | 目前全部已支持: OpenAI(GPT-4o, o1, o3)· Anthropic(Claude)· Google Gemini · Mistral · Meta Llama · Groq · Cohere · Azure OpenAI · AWS Bedrock · Ollama · DeepSeek · Perplexity · Together AI · Fireworks AI · Replicate · HuggingFace,可通过semantica.llms及LiteLLM进行调用 |
性能表现
基于v0.5.0在包含118,000个节点的实际生产环境图谱上进行的基准测试结果:
| 操作 | 之前 | 之后 | 提升幅度 |
|---|---|---|---|
| 节点搜索(118k 个节点) | 24 ms | 0.004 ms | 快 6,000 倍 |
| 嵌入缓存命中率 | 冷加载模式 | 基于版本号的缓存机制 | 吞吐量 提升 10 倍 |
| 语义去重 | 基准值 | 优化后的候选项生成方式 | 快 6.98 倍 |
| 候选项生成 | 基准值 | 阻塞策略 | 快 63.6% |
测试环境为包含 118,000 个节点的实际生产级图结构(AMD EPYC 处理器,64 GB 内存);去重/候选项生成的相关数据取自 CHANGELOG.md 中的历史测试记录,而非自动生成的 tests/ 结果。实际性能会因硬件、数据集结构及后端选择的不同而有所差异——请运行 pytest tests/vector_store/test_performance_benchmarks.py -s 命令来测试您自己的数据。
CLI
所有功能均可通过终端使用。该 CLI 已随软件包一同提供,无需单独安装。
pip install semantica
semantica # startup dashboard
semantica doctor # health check
semantica --help # full grouped command reference
只需通过 semantica 启动,用 doctor 验证,即可构建图结构,并在同一个终端中查看各类命令组。
命令组: ingest · parse · extract · kg · reason · decision · temporal · provenance · ontology · embed · deduplicate · validate · export · visualize · pipeline · server · explorer · mcp · doctor · shell · init · watch
集成功能
为 Claude Code、Cursor、Codex、Windsurf、Cline、Continue、VS Code 以及 OpenClaw 提供了原生插件包;为所有支持 MCP 的客户端提供了功能完备的 MCP 服务器;同时还具备完善的 REST API;此外还支持一流的 Agno 机制,可实现多智能体之间的上下文共享。目前通过 semantica.llms 和 LiteLLM,所有主流的 LLM 提供商都已得到支持,包括 OpenAI、Anthropic、Gemini、Mistral、Llama、Groq、Cohere、Azure、Bedrock、Ollama、DeepSeek、HuggingFace 等。
MCP 的配置仅需 30 秒——详情请参见下文的 MCP 服务器。
完整的集成功能矩阵(编辑器、MCP 客户端、REST 客户端、智能体框架)
| 原生插件包 | MCP服务器 + 插件 | ||||||
|---|---|---|---|---|---|---|---|
|
Claude Code 技能 · 代理 · 钩子 |
Cursor 技能 · 代理 |
Codex CLI 技能 · 代理 |
Windsurf 插件 |
Cline 插件 |
继续 插件 |
VS Code 插件 |
OpenClaw MCP + 插件 |
| MCP服务器 | REST API | ||||||
|
Claude Desktop MCP服务器 |
GitHub Copilot REST API |
Roo Code REST API |
Goose REST API |
Kilo Code REST API |
Aider REST API |
Amazon Q REST API |
Zed REST API |
代理框架
MCP 服务器
30 秒内即可连接任何兼容 MCP 的客户端(Claude Desktop、Windsurf、Cline、VS Code):
python -m semantica.mcp_server
# or via the installed entry point
semantica-mcp
{
"mcpServers": {
"semantica": { "command": "python", "args": ["-m", "semantica.mcp_server"] }
}
}
通过 MCP 提供的工具:
| 工具 | 功能说明 |
|---|---|
extract_entities | 对任意文本进行命名实体识别 |
extract_relations | 关系抽取 |
record_decision | 保存决策节点 |
query_decisions | 搜索决策历史记录 |
find_precedents | 查找语义上的先例 |
get_causal_chain | 获取完整的因果溯源信息 |
add_entity | 添加知识图谱节点 |
add_relationship | 添加知识图谱边 |
run_reasoning | 执行规则集 |
get_graph_analytics | 计算中心性、社区结构 |
export_graph | 导出为 RDF/JSON/Parquet 格式 |
get_graph_summary | 图表统计信息 |
REST API
# 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 接口范围包括: enrich(提取)· graph · decisions · reasoning · provenance · ontology · embeddings · search · export · pipeline · temporal · deduplication
插件包
领域技能: extract · ingest · query · ontology · validate · deduplicate · embed · reason · decision · causal · temporal · provenance · policy · explain · export · change · visualize
专用智能体: kg-assistant · decision-advisor · explainability
适用于 Claude Code、Cursor、Codex、Windsurf、Cline、Continue、VS Code 以及 OpenClaw 的插件包可在 plugins/ 中找到。
知识探索器
一款基于浏览器的图谱工作台。您可以平移和缩放实时图谱,拖动时间轴,查看每个决策的因果链,消除重复项,并以可视化方式构建本体。该工具基于 React 19 + Sigma.js 开发。
| 工作区 | 可实现的功能 |
|---|---|
| 知识图谱 | 支持 ForceAtlas2 布局、自我中心模式及语义距离热图的实时 Sigma.js 画布 |
| 时间轴 | 拖动时间轴查看时间序列事件,并观察图谱的演变过程 |
| 决策记录 | 浏览每个已记录决策背后的因果链 |
| 注册表 | 实时记录所有图谱变更的审计日志 |
| 实体消重 | 审核并合并重复的实体 |
| 本体中心 | 提供 SHACL Studio、可视化编辑器、跨本体对齐功能以及 SKOS 浏览器 |
| 溯源信息 | 为任意实体提供 W3C PROV-O 格式的溯源可视化展示 |
最快捷的启动方式(无需 Node.js):
pip install "semantica[explorer]"
semantica-explorer --graph my_graph.json
# Dashboard opens at http://127.0.0.1:8000
如需进行贡献者/开发服务器配置:explorer/README.md: 本地安装指南
v0.6.0 的新功能
JenaStore的命名图谱支持:已迁移至rdflib.Dataset(default_union=False),实现了 Blazegraph、RDF4J 和 Jena 之间跨后端的命名图谱功能一致性;add_triplets()现新增了graph=选项- SPARQL CONSTRUCT 查询模板:提供了参数化且防注入攻击的
CONSTRUCT模板,其功能已从仅支持 Blazegraph 扩展到 RDF4J 和 Jena,同时还可通过construct_template步骤类型实现流程集成 - Databricks 连接器:支持 Unity Catalog + Delta Lake 的数据导入,具备 PAT/OAuth M2M 认证功能,可导入表格/查询数据,还能查看目录/模式/表格/溯源信息。可通过
pip install "semantica[db-databricks]"进行安装 - SQLite 向量存储后端:即
SQLiteVecStore,这是一种基于磁盘的本地向量存储方案,运行在sqlite-vec的vec0虚拟表之上,支持余弦/欧几里得距离度量、元数据过滤以及 WAL 模式。可通过pip install semantica[vectorstore-sqlite]进行安装
为高要求领域打造
Semantica 专为那些要求人工智能输出结果具备可解释性、可审计性且可辩护性,同时数据本身不得离开自身基础设施的环境而设计。它支持自主托管,不存在任何供应商锁定问题,既适合处理机密或保密数据的机构,也适合需要保留审计追踪的受监管行业。
- 金融领域:贷款审批审计追踪、欺诈检测、反洗钱合规性管理、监管风险知识图谱
- 医疗保健领域:临床决策支持、药物相互作用图谱以及患者安全审计追踪
- 法律领域:基于证据的研究、合同分析、判例法推理以及保密信息追踪
- 政府与国防领域:政策决策记录、机密信息管理以及监管报告功能,完全自主托管,数据不会流出您的安全边界
- 执法领域:案件关联分析、证据来源追溯,以及能够承受法律审查的调查知识图谱
- 网络安全领域:威胁溯源、事件响应时间线以及 IOC 来源追踪
- 自主系统领域:决策日志、安全性验证,以及用于认证的可解释人工智能技术
安装
pip install semantica # core
pip install semantica[all] # everything
pip install semantica[agno] # Agno multi-agent integration
pip install semantica[llm-litellm] # OpenAI, Anthropic, Gemini, Mistral, Llama, Groq, Cohere, Bedrock, Ollama, DeepSeek, and more
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[vectorstore-qdrant] # Qdrant vector store
pip install semantica[vectorstore-pinecone] # Pinecone vector store
pip install semantica[db-snowflake] # Snowflake
pip install semantica[db-databricks] # Databricks (SDK + SQL connector)
pip install semantica[ingest-parquet] # Parquet / PyArrow
pip install semantica[ingest-arrow] # Apache Arrow, Feather, IPC
pip install semantica[viz] # HTML interactive visualization
pip install semantica[watch] # Directory file watcher
pip install semantica[explorer] # Knowledge Explorer dashboard
对于生产环境部署,建议使用 Docker 或 Kubernetes,而非本地 pip install。需设置 SEMANTICA_SECRET_KEY,配置持久化的 LPG 图数据库(Neo4j / FalkorDB / Apache AGE / AWS Neptune)和/或 RDF 三元组存储库(Blazegraph / Apache Jena / Eclipse RDF4J),同时将向量存储指向托管的后端服务(Qdrant / Pinecone)。完整的部署拓扑结构请参阅 ARCHITECTURE.md。
# From source
git clone https://github.com/semantica-agi/semantica.git
cd semantica && pip install -e ".[dev]" && pytest tests/
企业版服务
本地部署 · 私有云部署 · 定制域名部署 · 基于 SLA 的支持服务 · 面向受监管行业(金融、医疗、法律、政府)的专业服务。
如需了解企业级解决方案及定价信息,请访问 getsemantica.ai。
社区与支持
| Discord | discord.gg/sV34vps5hH:实时帮助、产品展示及公告发布】 |
| GitHub Discussions | 问答与功能需求提交 |
| GitHub Issues | 错误报告提交 |
| 文档 | docs.getsemantica.ai |
| 操作指南 | 可运行的 Jupyter 笔记本 |
| 版本变更记录 | CHANGELOG.md · 发布说明 |
星标历史记录
贡献者
参与贡献
我们欢迎任何形式的贡献:错误修复、新功能开发、测试以及文档完善。
- 复制仓库并创建一个分支
pip install -e ".[dev]"- 在进行代码修改的同时编写测试用例(
pytest tests/) - 提交 Pull Request 并标记
@KaifAhmad1以便他人审阅
更多详细指南请参阅 CONTRIBUTING.md。