5 分钟把文档库变成可查询知识图谱:Semantica 入门完整指南
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
Semantica 是一个 Python 知识图谱框架,把非结构化文档转成可查询、可溯源、可推理的图结构,给 LLM 应用和 Agent 提供图原生的上下文层。环境门槛只有一个:Python ≥ 3.10,本文所有示例零配置跑通,不需要任何 LLM API Key。
准备工作:一条命令装好 Semantica 依赖
基础包只带核心依赖,三条命令完成安装和验证:
pip install semantica python -c "import semantica; print(semantica.__version__)" # 0.7.0 pip install 'semantica[viz]' # 可选:可视化需要 Plotlyextras 按需补装,定义在 pyproject.toml 的optional-dependencies段。只处理数据、不做图展示的,[viz]这步可以直接跳过。
冒烟示例:一句话跑通 Semantica 知识图谱抽取
装完先别急着建库,用最短的文本验证抽取链路是否通:
from semantica.semantic_extract import NERExtractor, RelationExtractor text = "Apple Inc. was founded by Steve Jobs in 1976." entities = NERExtractor(method="pattern").extract(text) rels = RelationExtractor(method="pattern").extract(text, entities=entities) for e in entities: print(e.text, e.label, e.confidence)跑完会看到Apple Inc. ORG 0.9、Steve Jobs PERSON ...这样的实体行和founded_by之类的关系对象。关键开关是method="pattern":走内置正则规则,零模型零配置,所以不需要 Key。不传method时NERExtractor默认"ml"(spaCy,需en_core_web_sm),RelationExtractor默认就是"pattern",内置founded_by、works_for、born_in等句式模板(见 relation_extractor.py);精度不够再换method="llm"并传provider,两者返回结构一致,可无缝替换。
能力拆解:装完 Semantica 后值得动手的四件事
批量入图:把重复实体合成同一个节点
解决什么问题:几十份报告合成一张图时,同一个公司在不同文档里叫 "Apple"、"Apple Inc."、"AAPL"。不归并,图里就出现一堆重复节点,后续的统计和查询全部失真。
怎么调用:链路是FileIngestor收文件 →DocumentParser出纯文本 → 抽取 →GraphBuilder建图。
from semantica.ingest import FileIngestor from semantica.parse import DocumentParser from semantica.semantic_extract import NERExtractor, RelationExtractor from semantica.kg import GraphBuilder sources = FileIngestor().ingest("data/reports/") parser = DocumentParser() ner = NERExtractor(method="pattern") rel = RelationExtractor(method="pattern") ents, rels = [], [] for src in sources: text = parser.parse(src.path)["full_text"] ents.extend(ner.extract(text)) rels.extend(rel.extract(text, entities=ner.extract(text))) graph = GraphBuilder(merge_entities=True).build( {"entities": ents, "relationships": rels} ) print(len(graph["entities"]), "nodes,", len(graph["relationships"]), "edges")ingest()是统一入口:传文件走ingest_file,传目录走ingest_directory且默认递归(见 file_ingestor.py);DocumentParser.parse()恒返回full_text与metadata两个键。
哪个参数真正起作用:merge_entities=True。开启后构建期实例化EntityResolver,用默认的fuzzy策略把 "Apple" / "Apple Inc." / "AAPL" 归并成同一节点;冲突检测resolve_conflicts默认True,不用额外配置(参数定义见 graph_builder.py)。
容易踩的坑:漏掉这个参数,重复节点会一路留到导出阶段。归并逻辑在 entity_resolver.py,策略想更保守时再单独调。
可视化与多格式导出:从交互 HTML 到语义网格式
解决什么问题:图建好后要肉眼检查质量,还要喂给下游——BI 工具要 Parquet,语义网生态要 RDF,一个图两种需求都要满足。
怎么调用:
from semantica.visualization import KGVisualizer from semantica.export import RDFExporter, ParquetExporter KGVisualizer().visualize_network( graph, output="html", file_path="graph.html", node_color_by="type" ) rdf = RDFExporter() rdf.export(graph, file_path="graph.ttl", format="turtle") ParquetExporter().export(graph, file_path="output/graph")浏览器打开graph.html就能缩放、点节点,node_color_by="type"让不同实体类型显示为不同颜色,底层是 Plotly。
哪个参数真正起作用:format。RDFExporter只认turtle、rdfxml、jsonld三种(见 rdf_exporter.py);ParquetExporter会把 dict 按 key 拆成graph_entities.parquet/graph_relationships.parquet两个文件,可直接喂 Spark。CSV、JSON、YAML、OWL、Arrow 等其余导出器都在 semantica/export/ 下。
容易踩的坑:没装[viz]extra 时可视化会直接提示安装命令,不会静默失败——按提示装 Plotly 即可。RDFExporter传不支持的格式字符串会报错,支持列表就上面那三种。
时序查询:问知识图谱「这条边 2020 年还成立吗」
解决什么问题:图里的知识会过期。员工的职务、合作关系、合规条款都有起止时间,不给边加时间戳,图谱永远只能回答"现在"。
怎么调用:给每条边附上valid_from/valid_until,再按时间点回放:
from semantica.kg import GraphBuilder, TemporalGraphQuery kg = GraphBuilder().build({ "entities": [ {"id": "alice", "type": "Person"}, {"id": "acme", "type": "Organization"}, ], "relationships": [ {"source": "alice", "target": "acme", "type": "ceo_of", "valid_from": "2018-01-01", "valid_until": "2022-06-01"}, {"source": "alice", "target": "acme", "type": "advisor_of", "valid_from": "2022-07-01"}, ], }) tq = TemporalGraphQuery(temporal_granularity="day") print(tq.query_at_time(kg, query="", at_time="2020-06-15")["num_relationships"]) # 1 print(tq.query_at_time(kg, query="", at_time="2023-01-01")["num_relationships"]) # 1两次查询各返回 1:2020 年有效的边是ceo_of,2023 年只剩advisor_of。query_at_time的实现就是按时间区间过滤边(源码见 temporal_query.py)。
哪个参数真正起作用:temporal_granularity。如果整条管道都要时序能力,构建侧直接传GraphBuilder(enable_temporal=True, temporal_granularity="month"),granularity支持second到year七档。
容易踩的坑:只给边写了时间戳但没建时序感知的图谱,查询侧靠valid_from/valid_until也能过滤,但涉及时间归一化、时序推理等完整能力时,记得构建侧开enable_temporal=True。
Agent 记忆:给 Agent 一个决策上下文
解决什么问题:多 Agent 或长程任务最怕前后矛盾。AgentContext把事实、图谱记忆和决策记录放在同一层,后续决策可以检索历史先例,而不是每次都从零开始。
怎么调用:
from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore ctx = AgentContext( vector_store=VectorStore(backend="faiss", dimension=768), knowledge_graph=ContextGraph(), decision_tracking=True, ) ctx.store("GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%") did = ctx.record_decision( category="model_selection", scenario="Choose LLM for production reasoning pipeline", reasoning="Benchmark advantage justifies 3x cost", outcome="selected_gpt4", confidence=0.91, ) print(ctx.find_precedents("model selection", limit=5)) print(ctx.analyze_decision_influence(did))哪个参数真正起作用:decision_tracking=True。record_decision必须先开它,且决策后端依赖传入的knowledge_graph(或 graph_store 后端),否则调用报RuntimeError(完整参数见 agent_context.py)。
容易踩的坑:vector_store是必传参数,漏传直接抛ValueError。默认值retention_days=30天、max_memories=10000、hybrid_alpha=0.5(0 偏向量检索、1 偏图遍历),按记忆规模调。find_precedents返回相关历史决策列表,analyze_decision_influence输出该决策的因果影响链——决策在这里是一等对象,不是日志。
避坑清单:Semantica 知识图谱上线前对照检查
| 现象 | 原因 | 对策 |
|---|---|---|
| PDF 解析后抽不到任何实体 | 扫描件只有图片层、没有机器可读文本,DocumentParser检测到无文本层时会打警告 | 换带 OCR 的DoclingParser(需pip install semantica[parse-docling]) |
| 同一实体在图中出现多个节点 | 构建时没开实体消解,或消解策略偏严 | GraphBuilder(merge_entities=True);默认entity_resolution_strategy="fuzzy",想更保守改"exact" |
| 大图构建内存溢出 | 默认图只存在进程内存(NetworkX),进程退出即丢 | 把持久化后端传给GraphBuilder(graph_store=...),当前支持neo4j/falkordb后端,其余配置以 kwargs 透传(见 graph_store.py) |
| 大目录全量 ingest 慢且占内存 | ingest()一次性把目录下所有文件读进来 | 改用scan_directory()只取文件元信息,逐文档处理,每次只加载一个文件 |
涉及代码的两条对策,最小写法如下:
from semantica.parse import DoclingParser parsed = DoclingParser().parse("data/scan.pdf")from semantica.ingest import FileIngestor from semantica.graph_store import GraphStore store = GraphStore(backend="neo4j", uri="bolt://localhost:7687", user="neo4j", password="password") graph = GraphBuilder(merge_entities=True, graph_store=store).build(payload) for info in FileIngestor().scan_directory("data/reports/", recursive=True): text = parser.parse(info["path"])["full_text"]延伸入口:装完 Semantica 之后读什么
- 入门文档:docs/getting-started.md 和 docs/quickstart.md,卡住时先翻这两篇;概念与模块全貌在 docs/concepts.md、docs/modules.md。
- API 参考:docs/reference/ 按模块逐篇组织,查参数默认值最快的地方。
- 教程 Notebook:cookbook/introduction/ 有 26 篇入门课,从数据摄入讲到语义层;时序图谱与 Datalog 推理在 cookbook/advanced/。
- 存储后端:docs/storage-backends.md 讲 Neo4j、FalkorDB 等后端的选型,数据量大到内存放不下时看这篇。
- 框架集成:integrations/ 提供 LangChain、CrewAI、Agno、Google ADK 的现成封装,接入已有 Agent 栈不用从零写工具函数。
- MCP 服务端:semantica_mcp/ 把图谱能力暴露成 MCP 工具,接进支持 MCP 的客户端即可。
- LLM 抽取 provider:semantica/llms/ 封装了 OpenAI、Anthropic、Gemini、Groq、Ollama 等,精度不够换
method="llm"时从这里选。
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考