资讯动态

5 分钟把文档库变成可查询知识图谱:Semantica 入门完整指南

发布时间:2026/10/26 9:47:24 来源:尧图企业网站定制
5 分钟把文档库变成可查询知识图谱Semantica 入门完整指南【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semanticaSemantica 是一个 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(methodpattern).extract(text) rels RelationExtractor(methodpattern).extract(text, entitiesentities) for e in entities: print(e.text, e.label, e.confidence)跑完会看到Apple Inc. ORG 0.9、Steve Jobs PERSON ...这样的实体行和founded_by之类的关系对象。关键开关是methodpattern走内置正则规则零模型零配置所以不需要 Key。不传method时NERExtractor默认mlspaCy需en_core_web_smRelationExtractor默认就是pattern内置founded_by、works_for、born_in等句式模板见 relation_extractor.py精度不够再换methodllm并传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(methodpattern) rel RelationExtractor(methodpattern) ents, rels [], [] for src in sources: text parser.parse(src.path)[full_text] ents.extend(ner.extract(text)) rels.extend(rel.extract(text, entitiesner.extract(text))) graph GraphBuilder(merge_entitiesTrue).build( {entities: ents, relationships: rels} ) print(len(graph[entities]), nodes,, len(graph[relationships]), edges)ingest()是统一入口传文件走ingest_file传目录走ingest_directory且默认递归见 file_ingestor.pyDocumentParser.parse()恒返回full_text与metadata两个键。哪个参数真正起作用merge_entitiesTrue。开启后构建期实例化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, outputhtml, file_pathgraph.html, node_color_bytype ) rdf RDFExporter() rdf.export(graph, file_pathgraph.ttl, formatturtle) ParquetExporter().export(graph, file_pathoutput/graph)浏览器打开graph.html就能缩放、点节点node_color_bytype让不同实体类型显示为不同颜色底层是 Plotly。哪个参数真正起作用format。RDFExporter只认turtle、rdfxml、jsonld三种见 rdf_exporter.pyParquetExporter会把 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_granularityday) print(tq.query_at_time(kg, query, at_time2020-06-15)[num_relationships]) # 1 print(tq.query_at_time(kg, query, at_time2023-01-01)[num_relationships]) # 1两次查询各返回 12020 年有效的边是ceo_of2023 年只剩advisor_of。query_at_time的实现就是按时间区间过滤边源码见 temporal_query.py。哪个参数真正起作用temporal_granularity。如果整条管道都要时序能力构建侧直接传GraphBuilder(enable_temporalTrue, temporal_granularitymonth)granularity支持second到year七档。容易踩的坑只给边写了时间戳但没建时序感知的图谱查询侧靠valid_from/valid_until也能过滤但涉及时间归一化、时序推理等完整能力时记得构建侧开enable_temporalTrue。Agent 记忆给 Agent 一个决策上下文解决什么问题多 Agent 或长程任务最怕前后矛盾。AgentContext把事实、图谱记忆和决策记录放在同一层后续决策可以检索历史先例而不是每次都从零开始。怎么调用from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore ctx AgentContext( vector_storeVectorStore(backendfaiss, dimension768), knowledge_graphContextGraph(), decision_trackingTrue, ) ctx.store(GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%) did ctx.record_decision( categorymodel_selection, scenarioChoose LLM for production reasoning pipeline, reasoningBenchmark advantage justifies 3x cost, outcomeselected_gpt4, confidence0.91, ) print(ctx.find_precedents(model selection, limit5)) print(ctx.analyze_decision_influence(did))哪个参数真正起作用decision_trackingTrue。record_decision必须先开它且决策后端依赖传入的knowledge_graph或 graph_store 后端否则调用报RuntimeError完整参数见 agent_context.py。容易踩的坑vector_store是必传参数漏传直接抛ValueError。默认值retention_days30天、max_memories10000、hybrid_alpha0.50 偏向量检索、1 偏图遍历按记忆规模调。find_precedents返回相关历史决策列表analyze_decision_influence输出该决策的因果影响链——决策在这里是一等对象不是日志。避坑清单Semantica 知识图谱上线前对照检查现象原因对策PDF 解析后抽不到任何实体扫描件只有图片层、没有机器可读文本DocumentParser检测到无文本层时会打警告换带 OCR 的DoclingParser需pip install semantica[parse-docling]同一实体在图中出现多个节点构建时没开实体消解或消解策略偏严GraphBuilder(merge_entitiesTrue)默认entity_resolution_strategyfuzzy想更保守改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(backendneo4j, uribolt://localhost:7687, userneo4j, passwordpassword) graph GraphBuilder(merge_entitiesTrue, graph_storestore).build(payload) for info in FileIngestor().scan_directory(data/reports/, recursiveTrue): text parser.parse(info[path])[full_text]延伸入口装完 Semantica 之后读什么入门文档docs/getting-started.md 和 docs/quickstart.md卡住时先翻这两篇概念与模块全貌在 docs/concepts.md、docs/modules.md。API 参考docs/reference/ 按模块逐篇组织查参数默认值最快的地方。教程 Notebookcookbook/introduction/ 有 26 篇入门课从数据摄入讲到语义层时序图谱与 Datalog 推理在 cookbook/advanced/。存储后端docs/storage-backends.md 讲 Neo4j、FalkorDB 等后端的选型数据量大到内存放不下时看这篇。框架集成integrations/ 提供 LangChain、CrewAI、Agno、Google ADK 的现成封装接入已有 Agent 栈不用从零写工具函数。MCP 服务端semantica_mcp/ 把图谱能力暴露成 MCP 工具接进支持 MCP 的客户端即可。LLM 抽取 providersemantica/llms/ 封装了 OpenAI、Anthropic、Gemini、Groq、Ollama 等精度不够换methodllm时从这里选。【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑