Graph-Native Infrastructure for Context and Accountable AI Systems
| Files | Last commit | Last update |
|---|---|---|
| 4 months ago | ||
| 3 days ago | ||
| 10 days ago | ||
| 1 month ago | ||
| 4 days ago | ||
| 13 days ago | ||
| 2 days ago | ||
| 4 days ago | ||
| 11 days ago | ||
| 2 days ago | ||
| 4 days ago | ||
| 2 days ago | ||
| 1 month ago | ||
| 5 days ago | ||
| 3 months ago | ||
| 4 days ago | ||
| 7 months ago | ||
| 2 months ago | ||
| 4 days ago | ||
| 5 days ago | ||
| 19 days ago | ||
| 27 days ago | ||
| 19 days ago | ||
| 3 days ago | ||
| 13 days ago | ||
| 19 days ago | ||
| 24 days ago | ||
| 2 days ago | ||
| 4 months ago | ||
| 10 days ago | ||
| 1 month ago | ||
| 3 months ago | ||
| 1 month ago | ||
| 1 month ago | ||
| 6 days ago | ||
| 3 days ago | ||
| 18 days ago | ||
| 4 days ago | ||
| 4 days ago |
面向上下文与可问责 AI 系统的图原生基础设施
开发者优先的 AI 知识基础设施,替代昂贵的企业级平台。
导入企业数据,提炼关键信息,构建上下文图与知识图谱(KG),并对全部内容运行图分析与因果推理,同时内建完整决策溯源。设计上即可解释、可追溯、可信赖。
上下文管理 · 知识建模 · 确定性推理 · 本体管理 · 决策智能 · 端到端可追溯性
开源 · 可治理 · 零供应商锁定
多模型图存储 · 支持 RDF 与 LPG · W3C 标准 · 可互操作
面向高风险、强监管领域
pip install semantica
大多数 AI 智能体运行在向量嵌入之上,而不是语义之上:只有相似性分数,没有结构、没有关系,也无法解释某个结果为何会被返回。
Semantica 是位于你的 LLM、向量存储和智能体框架之下的语义/上下文层:一套确定性基础设施(图谱构建、推理和溯源均不依赖 LLM;即便使用 LLM,它也是可选且厂商中立的,支持 OpenAI、Anthropic、Gemini 等主要供应商,还可通过 semantica.llms 接入更多服务),将碎片化的企业数据转化为结构化、可查询的上下文图谱和知识图谱,使其承载业务上下文,而不仅仅是数据结构。本体与受控词汇表(OWL、SHACL、SKOS)使实体在业务中的含义——包括其定义、关系和规则——像数据本身一样明确,而不仅仅是其向量嵌入。
决策溯源与审计轨迹并不是产品本身。它们无需额外成本即可从该结构中自然获得;在监管机构可以质询的领域,让智能体更聪明的同一套结构,也能直接回答“为什么”。
Note
系统级可解释性,而非基础模型可解释性。 Semantica 不会暴露或重建 LLM 内部发生的事情:它的内部推理保持不透明,与任何外部系统一样。Semantica 解释的是模型外部的内容:输入上下文、生成的决策、其溯源、相关关系、已应用的策略以及完整执行轨迹。
适用对象:
- AI/ML 平台团队:交付会做出重要决策的智能体,需要结构化、可查询的上下文,而不只是向量索引
- 基于 Databricks、Snowflake 或 SAP 的企业数据团队:将湖仓或数据仓库中已有的表转化为受治理、具备血缘追踪能力的知识图谱,而无需导出到第三方 SaaS
- 合规、风险与审计团队:需要以监管机构可接受的格式,直接回答“AI 为什么这么做?”
- 受监管企业(金融、医疗、法律、政府、国防):无法上线黑盒系统,也不能把数据交给第三方 SaaS 来获得这样的系统
- 平台与基础设施工程师:希望 KG、推理与溯源技术栈可自托管、可替换,而不是被锁定在单一厂商后端
- 数据与知识工程师:基于杂乱且多源的数据构建 KG,让冲突事实被标记、重复项被合并,而不是被静默覆盖
快速开始 · 架构 · 你将获得什么 · 为什么选择 Semantica · 决策智能 · 上下文图谱 · 实践示例:审计轨迹 · 模块参考 · 集成 · CLI · 性能 · 安装
Semantica 能为您带来什么
- 上下文图谱: 对您的智能体所知、所决策、所推理的全部内容进行结构化、可查询的图谱化表示
- 决策智能: 每个决策都是一等对象:可追溯、可按先例检索,并具有因果关联
- AI 治理与本体: SHACL 约束、冲突检测、合规规则、OWL 生成和 SKOS 词表,全部支持可视化编辑器
- 完整可审计性: 每个事实均带有 W3C PROV-O 溯源信息,并可导出为 JSON、CSV 或 RDF
- 确定性推理: 前向链、Rete 网络、Datalog 和 SPARQL,提供完全可解释的推理路径,而非黑盒
- 知识流水线: 多源接入、实体感知分块、NER/关系/事件抽取以及图谱构建,内置语义去重和保留溯源信息的合并
- 企业数据平台: 原生支持 Databricks(Unity Catalog + Delta Lake)、Snowflake 和 SAP OData 连接器,使您数据湖仓或数据仓库中已有的数据直接成为带溯源信息的图节点,无需导出/导入中转
- 图分析: 对您刚构建的图执行中心性、社区发现、链路预测和最短路径查询
- 多类型图存储: 支持 RDF(Oxigraph、Blazegraph、Jena、RDF4J)和带标签属性图(Neo4j、FalkorDB、AGE、Neptune),以及向量库,均可在不改动代码的情况下切换
- 可视化: 在交互式浏览器工作台内浏览任意图谱、本体或时间线
- 即插即用集成: 支持 Agno、CrewAI 和 LangChain,并提供完整的 MCP 服务器、CLI、REST API,以及面向主流编辑器的插件
为什么选择 Semantica
| 向量数据库 + RAG | 普通 LLM 记忆 | Semantica | |
|---|---|---|---|
| 召回方式 | 向量相似度 | Token 窗口 | 图遍历 + 语义搜索 |
| 决策历史 | 不存储 | 不存储 | 一等可查询对象 |
| 溯源 | 无 | 无 | W3C PROV-O,来源关联 |
| 推理 | 无 | 黑盒 | 前向链、Rete、Datalog、SPARQL |
| 冲突检测 | 静默覆盖 | 静默覆盖 | 检测、标记并解决 |
| 时间回溯 | 否 | 否 | 任意时间点图快照 |
| 合规导出 | 无 | 无 | PROV-O、SHACL、OWL、RDF |
| 策略管控 | 无 | 无 | 内置规则引擎 + SHACL |
| 实体消解 | 否 | 否 | 分块 + 语义去重 |
| 多智能体上下文 | 各智能体独立 | 各智能体独立 | 单一共享智能层 |
Semantica 旨在补充现有技术栈,而非替代它。您可以继续保留现有的 LLM、向量库和智能体框架;Semantica 会在其上增加决策记录、因果推理、溯源、本体治理、冲突检测以及审计追踪。推理引擎、KG 构建与溯源层均为确定性组件,无需依赖 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
在脚本或 CI 中运行? 进度条仅在 stdout 为交互式终端(或 Jupyter notebook)时显示,因此默认情况下,管道和重定向输出会保持整洁。可通过 SEMANTICA_DISABLE_PROGRESS=1 在所有位置关闭进度显示,或通过 SEMANTICA_FORCE_PROGRESS=1 在 stdout 被重定向时保留进度显示。SEMANTICA_DISABLE_PROGRESS 的优先级更高。
如果 Semantica 真正解决了你的问题,点亮一颗 Star 能让更多人发现它。
架构
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、SAP)、云资源(Google Drive、Elasticsearch)、数据流(Kafka、Kinesis)、Git、邮件、MCP
- 解析 → 归一化 → 切分: 文档解析,文本 / 实体 / 日期归一化,以及 GraphRAG 原生的实体感知分块
- 抽取 → 冲突检测 → 去重: NER、关系、事件、三元组;冲突事实会在合并前被标记并消解
- 知识图谱:
GraphBuilder构建图谱;双时态事实与完整图谱分析(中心性、社区、链路预测)构建于其上 - 本体 · 推理 · 溯源 · 决策: 位于 KG 之上的智能层,具备 SHACL/OWL 治理、Rete/Datalog/SPARQL 推理、W3C PROV-O 血缘,以及一等决策记录
- 存储: 设计上支持多存储模型,提供 RDF 三元组存储(嵌入式 Oxigraph、Blazegraph、Apache Jena、Eclipse RDF4J)、Labeled Property Graphs(Neo4j、FalkorDB、Apache AGE、AWS Neptune)以及向量存储,全部无需改动代码即可替换
- 输出: 导出(RDF、OWL、Parquet、Cypher、JSON-LD)、交互式可视化,并通过 REST API、MCP server 或 CLI 访问
决策智能
决策智能将每一次 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()
Context Graphs
Context Graph 是传统 RAG 缺失的结构化记忆层。扁平嵌入向量只能回答 "什么相似?",而 Context Graph 回答的是 "什么与什么相连、为什么相连,以及如何相连?"。每个实体、关系、决策和事实都是一等节点,可通过图遍历进行查询。实体会链接到源文档,决策会链接到证据与后果,事实会保留完整溯源,冲突会被检测出来,而不是被静默覆盖。
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?")
为何选择图谱而非嵌入: 遍历能够发现嵌入容易遗漏的关联(某个人距离某份合同有三跳);每个节点都携带溯源信息,因此你随时可以追问*“它来自哪里?”*;冲突会在污染你的知识库之前被标记;时间点快照让你无需重新处理即可重放历史。
模板:受监管决策的审计轨迹
一种基于同一 Context Graph 的模式:记录因果关联的决策链,为每个实体附加溯源信息,并导出满足监管要求的审计轨迹。
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 - to_kg_dict() is the official
# adapter that emits the {"entities": [...], "relationships": [...]} /
# source_id shape RDFExporter expects, so no manual field mapping is needed
kg = graph.to_kg_dict()
RDFExporter().export(kg, "audit_trail.ttl", format="turtle")
更多示例方案(GraphRAG 管道、AML 规则引擎、本体到 KG 的单步转换)见下方 更多示例方案。
探索平台
下方每个模块均可独立导入,并配有经过当前源码树验证的可运行代码示例;可任选其一,也可全部使用。
| 模块 | 功能说明 |
|---|---|
semantica.ingest |
文件、网页、数据库、API、数据流、邮件、Git、Parquet、Databricks、Snowflake、SAP、MCP |
semantica.semantic_extract |
NER、关系抽取、事件检测、三元组生成 |
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、SAP 或 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 · SAP(OData v2/v4) · 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:NER、关系、事件、三元组
一次处理即可从原始文本中提取结构化知识。
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: Forward Chaining, 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 节点条件匹配器在本次发布中有意保持简单——在将其接入生产环境合规关口之前,请结合实际规则集验证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 文档分块
KG 感知的分块,能够保留实体边界、关系三元组与本体概念,是 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 数据谱系
每条事实都与其来源相关联。没有黑箱,没有神秘输出。
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: 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)
时间智能:双时间图与时间回溯
追踪事实 在现实世界中 何时为真与何时 被记录,并可沿任一时间轴进行查询。
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 - to_kg_dict() is the official
# adapter that emits {"entities", "relationships"} with source_id/target_id
# keys, the shape query_time_range() expects (no manual mapping required)
kg = graph.to_kg_dict()
tq = TemporalGraphQuery()
facts_in_window = tq.query_time_range(
kg, 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 中可运行的 Notebook, 每个均自包含,并可在 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 Rules Engine
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 语义距离矩阵 · ego-mode 可视化 · 距离区间 · 嵌入缓存 |
| 语义抽取 | NER · 关系抽取 · 事件检测 · 三元组生成 · 共指 |
| 推理引擎 | 前向链接 · 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 认证) · SAP(SAPIngestor:OData v2/v4、OAuth2/Basic 认证、业务伙伴/销售订单) |
| LLM 提供商 | 目前已全部支持: 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、CrewAI 和 LangChain 支持。所有主流 LLM 提供商都可以通过 semantica.llms 和 LiteLLM 使用: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 插件 |
Continue 插件 |
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 Server
在 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 |
对任意文本执行 NER |
extract_relations |
关系抽取 |
record_decision |
持久化决策节点 |
query_decisions |
检索决策历史 |
find_precedents |
语义先例查询 |
get_causal_chain |
完整因果溯源 |
add_entity |
添加 KG 节点 |
add_relationship |
添加 KG 边 |
run_reasoning |
执行规则集 |
get_graph_analytics |
中心性、社区 |
export_graph |
导出为 RDF/JSON/Parquet |
get_graph_summary |
图统计 |
query_graph |
获取节点、遍历邻居、关键词检索 |
update_node |
将属性合并到节点 |
delete_node |
归档(软删除)节点 |
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(extract) · 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/。
Knowledge Explorer
基于浏览器的图工作台。可平移和缩放实时图,拖动时间轴,查看每项决策的因果链,处理重复项,并以可视化方式构建本体。基于 React 19 + Sigma.js 构建。
| 工作区 | 可执行操作 |
|---|---|
| Knowledge Graph | 支持 ForceAtlas2 布局、Ego Mode 和语义距离热图的实时 Sigma.js 画布 |
| Timeline | 沿时间事件拖动,观察图谱随时间演变 |
| Decisions | 浏览每条已记录决策背后的因果链 |
| Registry | 所有图变更的实时审计日志 |
| Entity Resolution | 审查并合并重复项 |
| Ontology Hub | SHACL Studio、可视化编辑器、跨本体对齐和 SKOS 浏览器 |
| Lineage | 为任意实体提供 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:本地配置指南
CLI 会暴露已加载的 ContextGraph。如果还需要浏览和编辑已有的
AgentMemory,请使用这两个实时对象以编程方式创建 ASGI 应用:
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)
Memories 工作区仅在提供 agent_memory 时显示。Apply
会更新所传入的运行时对象;它不会新增磁盘持久化。
v0.6.8 新增内容
从此开始,每个版本都会经过加密签名 —— 构建流程现在会执行 SLSA build-provenance attestation 和 Sigstore 签名,并且每次 GitHub Release 都会随 wheel/sdist 一同发布 .sigstore.json 文件包,补齐 OpenSSF Scorecard Signed-Releases 缺口。除此之外,这是一个大规模的修复与加固版本,同时新增了一批 Vector store 和 LLM provider 支持:
- Vector store 支持真正的枚举:
scan_vectors()/iter_vectors()已覆盖 FAISS、SQLiteVec、PgVector、Qdrant、Weaviate 和 Milvus(各自通过其 API 实际支持的分页原语),使semantica store migrate首次能够在不同后端之间运行;Weaviate 还新增了delete_vectors()以支持ErasureCoordinator semantica.llms新增对Anthropic、Gemini、Ollama、DeepSeek和Novita的一等 provider wrapper 支持,与现有Groq/OpenAI模式保持一致- Ontology 包为本体和知识图谱新增确定性、CI 友好的质量门禁,并新增一等 Google ADK 集成和一个 Salesforce 摄入器
- Explorer 的只读 Markdown 查看器已升级为完整编辑器,可编辑实时
ContextGraph节点以及宿主提供的AgentMemory条目 ErasureCoordinator补全了此前仅由purge_node()启动的擦除工作流,因此被清除的实体不会再以原文形式残留在AgentMemory中,也不会再作为 embedding 残留- 安全:12 个 Dependabot
aiohttp告警、5 个 HIGH 级别 Trivy 容器检测发现以及 2 个 npm 安全公告均已解决
同时还修复了 35 个正确性缺陷(Python 3.9 安装失败、FAISS 保存/加载时元数据丢失、semantica ingest 对已配置图存储的静默无操作、MCP 持久化、Explorer 图渲染、本体属性冲突处理,以及其他问题),并修正了全站大量文档错误。
安装
pip install semantica # lightweight core (22 essential dependencies)
pip install "semantica[all]" # full bundled behavior with all extras
Note: 较重的机器学习、NLP、可视化与文档依赖项被放入可选 extras 中,以保持核心安装轻量且快速。如果你希望使用之前的打包安装方式,请使用
pip install "semantica[all]"安装。
# Granular Extras
pip install "semantica[documents]" # Document parsing (docx, openpyxl, lxml, beautifulsoup4)
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 "semantica[crewai]" # CrewAI integration
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-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
对于生产部署,请使用 Docker 或 Kubernetes,而不是本地 pip install。设置 SEMANTICA_API_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/
CI 与部署
将 semantica 接入你的 CI 只需两分钟。在 GitHub Actions 中,使用可复用的组合 Action:
- uses: semantica-agi/semantica/.github/actions/setup-semantica@main
with:
python-version: '3.11'
可直接复制粘贴的 GitHub Actions、GitLab CI 和 CircleCI 入门模板位于 examples/ci/。已发布的包本身会每周通过 Install Matrix workflow 验证,确保可在 Ubuntu/macOS/Windows 以及 Python 3.9-3.12 上安装。
面向 AWS、GCP、Azure、Fly.io、Railway、Render、Kubernetes 和 Helm 的现成部署配置位于 deploy/。
企业
本地部署 · 私有云 · 自定义域名实现 · SLA 保障支持 · 面向受监管行业(金融、医疗、法律、政府)的专业服务。
企业解决方案与定价,请访问 getsemantica.ai。
社区与支持
| Discord | discord.gg/sV34vps5hH:实时帮助、案例展示与公告 |
| GitHub Discussions | 问答与功能请求 |
| GitHub Issues | 问题反馈 |
| 文档 | docs.getsemantica.ai |
| 实践手册 | 可运行的 Jupyter Notebook |
| 更新日志 | CHANGELOG.md · 发布说明 |
星标历史
贡献者
贡献
欢迎所有贡献:缺陷修复、新功能、测试和文档。
- Fork 仓库并创建分支
pip install -e ".[dev]"- 随变更编写测试(
pytest tests/) - 创建 PR 并标记
@KaifAhmad1进行审查
完整指南请参阅 CONTRIBUTING.md。
引用我们
如果你在研究或生产系统中使用 Semantica,请引用为:
@software{semantica2026,
title = {Semantica: Graph-Native Infrastructure for Context and Accountable AI Systems},
author = {Semantica},
year = {2026},
url = {https://github.com/semantica-agi/semantica}
}
所有引用格式(APA、MLA、Chicago、IEEE)均位于 引用 页面——每种格式都将作者署名归属于 Semantica,而非个人贡献者。
Introduction
Semantica🧠:开源语义层与知识工程框架,用于构建可解释、可审计且值得信赖的人工智能系统 — 超越文本相似度【此简介由AI生成】