Semantica 零配置实战:一次跑通从散落文档到可查询知识图谱的完整链路
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
Semantica 是一套图原生的基础设施(Graph-Native Infrastructure),面向需要上下文与可问责能力的 AI 系统。这篇文章带你不用任何 LLM API Key,把一堆原始文档一路喂成能交互、能持久化、能带溯源查询的知识图谱。整条链路只有一条数据流在走:
Ingest → Parse → Extract → Build → Visualize → Export
装好、验好
三条安装路径,按需挑一条:
pip install semantica # 基础安装,本文内容全部覆盖 pip install semantica[all] # 全量 extras:向量库、LLM provider、可视化等 # 开发者模式:git clone https://gitcode.com/GitHub_Trending/sema/semantica 后 cd semantica && pip install -e ".[dev]"装完跑一行验证:
python -c "import semantica; print(semantica.__version__)" # 0.7.0当前 0.7.0 把核心依赖瘦身为 22 个基础包,重依赖全部拆进可选 extras;再往前一版(0.6.8)则带来了 SLSA 密码学签名发布、FAISS/Qdrant/Weaviate/Milvus 的真实向量库枚举,以及 Anthropic、Gemini、Ollama、DeepSeek、Novita 等 LLM provider 的一等封装,细节可翻 CHANGELOG.md。
📊 从一段文本到一张图
数据进来
文件侧的入口在semantica/ingest/。FileIngestor().ingest()既能收单个文件也能收目录(目录默认递归),.pdf、.docx、.html、.json、.csv、.xlsx、.parquet、.xml全都能吃;内部按 扩展名 → MIME → 魔数 三级策略识别真实文件类型,单文件默认 100MB 上限。解析侧的DocumentParser把文档统一成带full_text和metadata的结构化输出:
from semantica.ingest import FileIngestor from semantica.parse import DocumentParser sources = FileIngestor().ingest("data/report.pdf") # 文件或目录皆可 parser = DocumentParser() parsed = parser.parse(sources[0].path) print(parsed["full_text"][:200], parsed["metadata"])遇到多栏、带表格图表的复杂版式 PDF,换DoclingParser更稳,它会把tables一并抽出来,还能开 OCR 救扫描件:pip install semantica[parse-docling]后DoclingParser(enable_ocr=True)即可。
语义出来
数据到手,真正的技术密度在这里。Semantica 给实体与关系抽取(semantica/semantic_extract/)留了两条路:pattern 模式匹配零配置、零 Key,开箱就能跑;llm 抽取精度更高,但需要后端 Key。
NERExtractor的method可取pattern、regex、rules、ml(spaCy,默认)、huggingface、llm,还支持传方法列表组成回退链,配合merge_strategy(fallback/union/consensus)与min_votes做多方法投票集成;entity_types限定目标类型,min_confidence默认 0.5。RelationExtractor的method则是pattern(默认)、regex、cooccurrence、dependency、huggingface、llm,confidence_threshold默认 0.6、max_distance默认 50 token,内置founded_by、located_in、works_for、born_in等关系模板。
from semantica.semantic_extract import NERExtractor, RelationExtractor text = parsed["full_text"] entities = NERExtractor(method="pattern").extract(text) # 零配置零 Key rels = RelationExtractor(method="pattern").extract(text, entities=entities)# LLM 路径:读环境变量 GROQ_API_KEY,provider/llm_model 换后端 ner = NERExtractor(method="llm", provider="groq", llm_model="llama-3.3-70b-versatile") entities = ner.extract(text) rel = RelationExtractor(method="llm", provider="groq", llm_model="llama-3.3-70b-versatile") rels = rel.extract(text, entities=entities)LLM 路径还能传base_url对接 OpenAI 兼容网关(如 Qwen、LLaMA 自建网关),此时自动切 JSON 模式,不用实现完整 function-calling 协议。
图成型
拿到实体和关系,semantica/kg/里的GraphBuilder负责把它们焊成图。强烈建议开merge_entities=True——"Apple"、"Apple Inc."、"AAPL" 这类重复引用会被EntityResolver(fuzzy/exact/ml-based策略)消解成同一个节点,跨文档汇聚时尤其省手动去重。
图建好之后直接进浏览器看。KGVisualizer基于 Plotly,layout支持force、hierarchical、circular三种布局,visualize_network可输出html/interactive/png/svg,支持node_color_by="type"按类型着色、highlight_path按跳数高亮路径;缺 Plotly 时提示pip install 'semantica[viz]'。导出侧在semantica/export/,RDF 系(turtle / json-ld / nt)、Parquet(可直喂 Spark、BigQuery、Databricks)、ArangoDB AQL 都是一行调用,另有 CSV、JSON、YAML、GraphML、OWL、Neo4j CSV、Arrow、LPG:
from semantica.kg import GraphBuilder from semantica.visualization import KGVisualizer from semantica.export import RDFExporter graph = GraphBuilder(merge_entities=True).build({"entities": entities, "relationships": rels}) print(f"Graph: {len(graph['entities'])} nodes, {len(graph['relationships'])} edges") KGVisualizer(layout="force").visualize_network(graph, output="html", file_path="graph.html") RDFExporter().export(graph, file_path="graph.ttl", format="turtle") # 另支持 json-ld/nt进阶场景速查
最小闭环跑通后,剩下的高频需求基本都能在这张表里对上号:
| 场景 | 一句话说明 | 核心类 / 方法 | 代码片段 |
|---|---|---|---|
| 时序图谱 | 边带valid_from/valid_until,定点查"当时有效"的关系 | TemporalGraphQuery.query_at_time | tq = TemporalGraphQuery(temporal_granularity="day")r = tq.query_at_time(kg, "", at_time="2020-06-15") |
| Neo4j 持久化图谱 | 图存进程外,重启不丢,生产落盘首选 | GraphStore(neo4j/falkordb/age) | store = GraphStore(backend="neo4j", uri="bolt://localhost:7687", user="neo4j", password="...")GraphBuilder(merge_entities=True, graph_store=store) |
| W3C PROV-O 溯源 | 记录每个实体"从哪来、置信度多少",可问责审计 | ProvenanceManager | prov = ProvenanceManager()prov.track_entity("Apple Inc.", "report.pdf")prov.get_all_sources("Apple Inc.") |
| 决策智能 | 上下文 + 决策留痕 + 相似先例检索,防前后矛盾 | AgentContext | context.record_decision(category="model_selection", ...)context.find_precedents("model selection", limit=5) |
| 多源增量构图 | 循环 ingest → extract,最后统一 build 消解 | FileIngestor+GraphBuilder | for src in FileIngestor().ingest("data/reports/"): text = parser.parse(src.path)["full_text"] all_entities.extend(ner.extract(text))graph = builder.build({"entities": all_entities, "relationships": all_rels}) |
几点选型直觉:数据里时间维度是业务核心(高管任职、合同周期)就开时序;图会跨进程/跨天使用就上GraphStore,纯内存 NetworkX 只适合脚本级;要过合规审计就把ProvenanceManager挂进流水线,各模块的*_provenance.py会自动接上;AgentContext记得必传vector_store,hybrid_alpha控制向量与图检索的权重,默认 0.5 各占一半。
🔍 踩坑手册:你大概率会撞上这几个
症状:抽不到任何实体,日志里还有一串警告。原因基本是扫描件——PDF 里没有机器可读的文本层,DocumentParser检测不到文本时会警告你。解法就是换带 OCR 的 DoclingParser:
from semantica.parse import DoclingParser # 先 pip install semantica[parse-docling] parsed = DoclingParser(enable_ocr=True).parse(path)症状:大语料跑起来慢得像挂机。两手准备:一是装 GPU extras(pip install semantica[gpu])让 embedding 和 ML 推理走 CUDA;二是别把整个语料一次读进内存,用scan_directory只扫元信息,逐文档流式处理并写持久化后端:
for info in FileIngestor().scan_directory("data/reports/", recursive=True): text = parser.parse(info["path"])["full_text"] # 一次只载一个文档 entities = ner.extract(text) rels = rel.extract(text, entities=entities) builder.build({"entities": entities, "relationships": rels}) # 直接落 Neo4j症状:大图一加载就 OOM。默认后端是内存里的 NetworkX,规模一大就顶不住。切持久化存储即可,实现都在semantica/graph_store/:
from semantica.graph_store import FalkorDBStore store = FalkorDBStore(host="localhost", port=6379) builder = GraphBuilder(merge_entities=True, graph_store=store)症状:企业网关环境下 NER 莫名回退到模式匹配。这是老版本的网关兼容问题,v0.5.0 已修复,pip install --upgrade semantica一把梭即可。
接下来看什么
- 核心概念:知识图谱、本体与推理引擎的心智模型,Semantica 的世界观;
- 模块总览:每个模块的关键类与常用调用链,速查手册;
- API 参考:所有模块、类与参数的完整文档;
- Cookbook:40+ 个真实数据集驱动的 Notebook,从 入门篇 到时序图谱、Datalog 推理等进阶专题;
- Pipeline 指南:把摄取、抽取、构图编排成可配置并行的流水线。
一句话收束这套设计哲学:先用零配置的规则抽取跑通最小闭环,再按需叠加 LLM 精度、持久化存储、时序语义与溯源——这就是图原生上下文基础设施的落地路径。
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考