Semantica 快速上手:5 分钟从零构建你的第一张知识图谱
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
Semantica 是面向上下文与可问责 AI 系统的图原生底座(Graph-Native Infrastructure):它把你手里的文档和零散文本,变成一张可查询、可持久化、可追溯来源的知识图谱。全程不需要 LLM API Key——规则式的实体关系抽取开箱即用。这篇教程带你从零跑通:先 5 分钟在浏览器里看到第一张图,再谈怎么把它接进 Neo4j、时序语义和 Agent 的决策回路。
30 秒装好它
装 Semantica 有三条路,按你的场景挑一条就行:
| 方式 | 命令 | 适用场景 |
|---|---|---|
| 基础安装 | pip install semantica | 覆盖本文全部用法,推荐 |
| 装全部可选依赖 | pip install semantica[all] | 需要向量库、各家 LLM provider 等 |
| 源码安装 | git clone https://gitcode.com/GitHub_Trending/sema/semantica后进入目录执行pip install -e ".[dev]" | 要读源码、调试或贡献代码 |
装完跑一行确认版本,顺手看看 CLI 长什么样:
pip install semantica python -c "import semantica; print(semantica.__version__)" # 0.6.8当前仓库对应 v0.6.8,这一版主要带来密码学签名发布(SLSA 溯源 + Sigstore)、FAISS / Qdrant / Weaviate / Milvus 的真实向量存储枚举,以及 Anthropic、Gemini、Ollama、DeepSeek、Novita 等 LLM provider 的一等封装。改动明细可翻 CHANGELOG.md 和 RELEASE_NOTES.md。
5 分钟看到第一张图
不等文件、不等配置:拿一句现成文本,直接走「抽取 → 构图 → 可视化」,你会得到节点、边的数量和一个可交互的graph.html。
from semantica.semantic_extract import NERExtractor, RelationExtractor from semantica.kg import GraphBuilder from semantica.visualization import KGVisualizer text = "Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976 in Cupertino, California." entities = NERExtractor(method="pattern").extract(text) relationships = RelationExtractor(method="pattern").extract(text, entities=entities) graph = GraphBuilder(merge_entities=True).build( {"entities": entities, "relationships": relationships}) print(f"{len(graph['entities'])} nodes, {len(graph['relationships'])} edges") viz = KGVisualizer(layout="force") viz.visualize_network(graph, output="html", file_path="graph.html", node_color_by="type")用浏览器打开graph.html,可以平移、缩放、点节点看详情,还能按实体类型过滤。两件事说明一下:
method="pattern"走内置规则模板,零配置零 Key,所以上面整段直接能跑。merge_entities=True让GraphBuilder按语义相似度自动合并 "Apple"、"Apple Inc."、"AAPL" 这类重复引用,省掉手工去重。
可视化用的KGVisualizer基于 Plotly,layout可选force/hierarchical/circular,output支持html/interactive/png/svg,还能配node_color_by、hover_data和highlight_path路径高亮。没装 Plotly 的话执行pip install 'semantica[viz]'即可。
从文件到完整流水线:每个环节解决什么问题
真实数据不在字符串里,在磁盘的 PDF、Word、HTML 里。下面四个问题对应流水线的四段,读完你就有了完整链路。
怎么把磁盘上的 PDF 变成代码里的文本?
FileIngestor负责"收",DocumentParser负责"读"。前者把文件或目录变成统一的FileObject列表(目录默认递归扫子目录),并把文件类型检测、单文件 100MB 上限校验、进度输出都包好了;后者把文档统一解析成结构化文本。
from semantica.ingest import FileIngestor from semantica.parse import DocumentParser sources = FileIngestor().ingest("data/report.pdf") # 传目录也行,支持 .docx/.html/.csv/.xlsx/.pptx/.parquet/.xml parsed = DocumentParser().parse(sources[0].path) print(parsed["full_text"][:200]) # 提取出的正文 print(parsed["metadata"]) # 文档属性,字段随格式而异parse()返回 dict:full_text和metadata每个格式都有,其余键看解析器——PDF 带pages,DOCX 带tables和paragraphs。文档里表格图表多、多栏排版时,换DoclingParser(先pip install semantica[parse-docling]),它会做版面分析并额外返回结构化的tables。
实体关系抽取:模式匹配还是 LLM?
这是流水线的核心,两条路按需选:
# 模式匹配:快、零 Key,适合先跑通 ner = NERExtractor(method="pattern") entities = ner.extract(text) # -> [Entity(text="Apple Inc.", label="ORG", confidence=0.7), ...] rel = RelationExtractor(method="pattern") relationships = rel.extract(text, entities=entities) # -> [Relation(subject=..., predicate="founded_by", object=..., confidence=0.7), ...] # LLM 抽取:精度更高,从环境变量读 GROQ_API_KEY ner = NERExtractor(method="llm", provider="groq", llm_model="llama-3.3-70b-versatile") entities = ner.extract(text)两个抽取器都支持传入文本列表做批量处理,常用旋钮列一下:
NERExtractor:method支持pattern/regex/rules/ml(默认,spaCy)/huggingface/llm,也能传方法列表组成回退链;entity_types限定目标类型(如["PERSON", "ORG"]);min_confidence默认 0.5;merge_strategy可选fallback/union/consensus,配min_votes(默认 2)做多方法投票;LLM 路径可用provider、llm_model选后端,设base_url可对接任意 OpenAI 兼容网关(会自动切到 JSON 模式,适配 Qwen、LLaMA 网关这类不实现 function calling 的服务)。RelationExtractor:method支持pattern(默认)/regex/cooccurrence/dependency/huggingface/llm;relation_types限定关系类型;confidence_threshold默认 0.6;max_distance控制两个实体间最大 token 距离(默认 50);bidirectional控制是否抽双向关系。内置模板覆盖founded_by、located_in、works_for、born_in等常见句式。
多份文档怎么增量构图、避免重复节点?
逐份解析、逐份抽取,但实体和关系先攒着,最后一次性交给GraphBuilder——这样跨文档的重复引用会在构图时统一消解,不会出现同一实体两个节点:
from semantica.ingest import FileIngestor from semantica.parse import DocumentParser from semantica.semantic_extract import NERExtractor, RelationExtractor from semantica.kg import GraphBuilder parser, ner = DocumentParser(), NERExtractor(method="pattern") rel, builder = RelationExtractor(method="pattern"), GraphBuilder(merge_entities=True) all_entities, all_rels = [], [] for source in FileIngestor().ingest("data/reports/"): text = parser.parse(source.path)["full_text"] ents = ner.extract(text) all_entities.extend(ents) all_rels.extend(rel.extract(text, entities=ents)) graph = builder.build({"entities": all_entities, "relationships": all_rels})GraphBuilder值得记的几个开关:entity_resolution_strategy选实体消解策略(fuzzy默认 /exact/ml-based);resolve_conflicts默认开启,构建期顺带做冲突检测与消解;enable_temporal/temporal_granularity开启时序图谱(后文细说);graph_store直接挂持久化后端(也是后文的事)。
图建好了,怎么交给下游?
semantica.export下每个格式一个导出器,最常见的三个:
from semantica.export import RDFExporter, ParquetExporter, ArangoAQLExporter RDFExporter().export(graph, file_path="graph.ttl", format="turtle") # 还有 "json-ld"、"nt" ParquetExporter().export(graph, file_path="output/graph") # dict 输入时每个 key 一个文件,可直接进 Spark / BigQuery ArangoAQLExporter().export(graph, file_path="graph.aql") # 生成可直接执行的 AQL INSERT 语句RDF 导出有个细节设计:confidence 统一规范化成xsd:decimal数据类型,保证 Turtle、N-Triples、RDF/XML、JSON-LD 四种序列化产物里的值完全一致,能被标准 RDF 解析器正确读回。除这三个外,仓库还提供 CSV、JSON、YAML、GraphML、OWL、Neo4j CSV、Arrow、LPG 等导出器,目录在 semantica/export/。
让它跑在生产里
内存里的图,进程一关就没了。等你要把图谱当长期资产用,三件事必须做:落盘、带时间、留证据。
持久化图存储怎么选
把默认的后端从内存 NetworkX 换成真实图数据库,只需给GraphBuilder多传一个graph_store:
from semantica.graph_store import GraphStore from semantica.kg import GraphBuilder store = GraphStore(backend="neo4j", uri="bolt://localhost:7687", user="neo4j", password="password") builder = GraphBuilder(merge_entities=True, graph_store=store) graph = builder.build({"entities": entities, "relationships": relationships}) # 图已写入 Neo4j:进程重启后依然存在backend可切neo4j/falkordb/age(Apache AGE)等,对应实现在 neo4j_store.py、falkordb_store.py、age_store.py;仓库还有 Amazon Neptune 和 Triplet Store(RDF4J、Blazegraph、Oxigraph、Jena、Anzo),清单见 docs/storage-backends.md。
时序图谱:回答"某个时间点,事实是什么"
给边加上valid_from/valid_until,同一张图就能回答不同年份的问题——比如 alice 先当 acme 的 CEO、后跳槽 beta:
from semantica.kg import GraphBuilder, TemporalGraphQuery kg = GraphBuilder().build({ "entities": [ {"id": "alice", "type": "Person"}, {"id": "acme_corp", "type": "Organization"}, {"id": "beta_ltd", "type": "Organization"}, ], "relationships": [ {"source": "alice", "target": "acme_corp", "type": "ceo_of", "valid_from": "2018-01-01", "valid_until": "2022-06-01"}, {"source": "alice", "target": "beta_ltd", "type": "ceo_of", "valid_from": "2022-06-01"}, ], }) tq = TemporalGraphQuery(temporal_granularity="day") r2020 = tq.query_at_time(kg, query="", at_time="2020-06-15") r2023 = tq.query_at_time(kg, query="", at_time="2023-01-01") print(r2020["num_relationships"], r2023["num_relationships"]) # 各自返回该时间点仍生效的边query_at_time只返回指定时刻"仍然有效"的关系,temporal_granularity支持 second 到 year。底层实现在 temporal_model.py 与 temporal_query.py。
溯源(Provenance):每条数据从哪来、可信度多高
可问责 AI 的底线是:图里任何一个断言,你都能说清出处。ProvenanceManager按 W3C PROV-O 模型记录这件事:
from semantica.provenance import ProvenanceManager prov = ProvenanceManager() prov.track_entity("Apple Inc.", "data/report.pdf", metadata={"confidence": 0.98}) sources = prov.get_all_sources("Apple Inc.") print(sources[0]) # {"source": "data/report.pdf", "location": None, "timestamp": "...", # "confidence": 1.0, "metadata": {"confidence": 0.98}}核心在 semantica/provenance/manager.py 与 schemas.py,并且各模块都带自己的*_provenance.py(比如 kg_provenance.py),溯源是贯穿整个库的能力,不是事后补丁。
图建起来之后,还可以用仓库自带的浏览器端探索器(Knowledge Explorer)交互式地查图、看实体面板与时间轴:
把图谱接进决策
图谱不只是查数,还能给 AI Agent 的每次决策加上"上下文 + 因果链 + 证据"。AgentContext一次 import 就能做到:存带溯源的事实、记录决策、检索历史先例防止前后矛盾。
from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore context = AgentContext( vector_store=VectorStore(backend="faiss", dimension=768), # vector_store 是必填项 knowledge_graph=ContextGraph(advanced_analytics=True), decision_tracking=True, ) context.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%") # 带溯源存一条事实 decision_id = context.record_decision( category="model_selection", scenario="Choose LLM for production reasoning pipeline", reasoning="GPT-4 benchmark advantage justifies 3x cost increase", outcome="selected_gpt4", confidence=0.91, ) precedents = context.find_precedents("model selection reasoning", limit=5) # 相似历史决策 influence = context.analyze_decision_influence(decision_id) # 该决策的下游影响几个默认值心里有数即可(实现见 agent_context.py、agent_memory.py):
retention_days=30:记忆保留天数,None表示永久;max_memories=10000:记忆条数上限;hybrid_alpha=0.5:向量检索与图检索的平衡系数,0 偏向量、1 偏图;graph_expansion=True+max_expansion_hops(默认 2 跳):命中记忆后沿图扩展取证。
同一套机制也支撑 GraphRAG 和多 Agent 共享上下文,集成示例见 docs/guides/decision-intelligence.md 与 integrations/。
排错速查
| 症状 | 大概率原因 | 一步解决 |
|---|---|---|
| 一个实体都抽不出来 | 扫描件 PDF 没有文本层(DocumentParser会警告) | 换DoclingParser(enable_ocr=True),先pip install semantica[parse-docling] |
| 大语料处理太慢 | 全量载入内存 + CPU 推理 | pip install semantica[gpu]上 CUDA;或先用scan_directory只扫路径,再逐文档解析、边抽边写持久化后端 |
| 大图内存溢出 | 默认图存在内存(NetworkX)里 | 切持久化后端,如FalkorDBStore(host="localhost", port=6379)或直接 Neo4j |
| 企业网关后 NER 回退到 pattern 模式 | v0.5.0 已修复的老问题 | pip install --upgrade semantica |
大语料场景还有一个进阶编排思路:FileIngestor().scan_directory(path, recursive=True)只返回文件元信息、不读内容,你拿它循环,每次只加载一个文档,抽完立刻builder.build(...)写进图数据库——内存峰值从"整个语料"降到"一个文档"。多步并行编排可看 docs/guides/pipeline.md,实现在 semantica/pipeline/。
接下来读什么
建议按由浅入深的路径走:先读 docs/concepts.md 建立心智模型(知识图谱、本体、推理引擎是什么关系);再看 docs/modules.md 熟悉每个模块的关键类与常用调用链;需要查参数时进 docs/reference/ 翻 API 文档;想动手练,cookbook/ 里有 40 多个基于真实数据集的 Notebook——入门篇从数据摄取(02)讲到构图(07/08)、本体(14)、导出(15)、可视化(16)、去重(18)、溯源(22)、推理(23),进阶篇(cookbook/advanced/)覆盖时序图谱、多源集成与 Datalog 风格推理。
下一步不用贪多:拿一份你自己的文档,把开头那个五分钟最小闭环跑一遍,再顺手给GraphBuilder挂一个graph_store——第一张"重启不丢"的图,就到手了。
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考