ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Semantica 快速上手:5 分钟从零构建你的第一张知识图谱

Semantica 快速上手:5 分钟从零构建你的第一张知识图谱 Semantica 快速上手5 分钟从零构建你的第一张知识图谱【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semanticaSemantica 是面向上下文与可问责 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(methodpattern).extract(text) relationships RelationExtractor(methodpattern).extract(text, entitiesentities) graph GraphBuilder(merge_entitiesTrue).build( {entities: entities, relationships: relationships}) print(f{len(graph[entities])} nodes, {len(graph[relationships])} edges) viz KGVisualizer(layoutforce) viz.visualize_network(graph, outputhtml, file_pathgraph.html, node_color_bytype)用浏览器打开graph.html可以平移、缩放、点节点看详情还能按实体类型过滤。两件事说明一下methodpattern走内置规则模板零配置零 Key所以上面整段直接能跑。merge_entitiesTrue让GraphBuilder按语义相似度自动合并 Apple、Apple Inc.、AAPL 这类重复引用省掉手工去重。可视化用的KGVisualizer基于 Plotlylayout可选force/hierarchical/circularoutput支持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()返回 dictfull_text和metadata每个格式都有其余键看解析器——PDF 带pagesDOCX 带tables和paragraphs。文档里表格图表多、多栏排版时换DoclingParser先pip install semantica[parse-docling]它会做版面分析并额外返回结构化的tables。实体关系抽取模式匹配还是 LLM这是流水线的核心两条路按需选# 模式匹配快、零 Key适合先跑通 ner NERExtractor(methodpattern) entities ner.extract(text) # - [Entity(textApple Inc., labelORG, confidence0.7), ...] rel RelationExtractor(methodpattern) relationships rel.extract(text, entitiesentities) # - [Relation(subject..., predicatefounded_by, object..., confidence0.7), ...] # LLM 抽取精度更高从环境变量读 GROQ_API_KEY ner NERExtractor(methodllm, providergroq, llm_modelllama-3.3-70b-versatile) entities ner.extract(text)两个抽取器都支持传入文本列表做批量处理常用旋钮列一下NERExtractormethod支持pattern/regex/rules/ml默认spaCy/huggingface/llm也能传方法列表组成回退链entity_types限定目标类型如[PERSON, ORG]min_confidence默认 0.5merge_strategy可选fallback/union/consensus配min_votes默认 2做多方法投票LLM 路径可用provider、llm_model选后端设base_url可对接任意 OpenAI 兼容网关会自动切到 JSON 模式适配 Qwen、LLaMA 网关这类不实现 function calling 的服务。RelationExtractormethod支持pattern默认/regex/cooccurrence/dependency/huggingface/llmrelation_types限定关系类型confidence_threshold默认 0.6max_distance控制两个实体间最大 token 距离默认 50bidirectional控制是否抽双向关系。内置模板覆盖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(methodpattern) rel, builder RelationExtractor(methodpattern), GraphBuilder(merge_entitiesTrue) 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, entitiesents)) graph builder.build({entities: all_entities, relationships: all_rels})GraphBuilder值得记的几个开关entity_resolution_strategy选实体消解策略fuzzy默认 /exact/ml-basedresolve_conflicts默认开启构建期顺带做冲突检测与消解enable_temporal/temporal_granularity开启时序图谱后文细说graph_store直接挂持久化后端也是后文的事。图建好了怎么交给下游semantica.export下每个格式一个导出器最常见的三个from semantica.export import RDFExporter, ParquetExporter, ArangoAQLExporter RDFExporter().export(graph, file_pathgraph.ttl, formatturtle) # 还有 json-ld、nt ParquetExporter().export(graph, file_pathoutput/graph) # dict 输入时每个 key 一个文件可直接进 Spark / BigQuery ArangoAQLExporter().export(graph, file_pathgraph.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_storefrom semantica.graph_store import GraphStore from semantica.kg import GraphBuilder store GraphStore(backendneo4j, uribolt://localhost:7687, userneo4j, passwordpassword) builder GraphBuilder(merge_entitiesTrue, graph_storestore) graph builder.build({entities: entities, relationships: relationships}) # 图已写入 Neo4j进程重启后依然存在backend可切neo4j/falkordb/ageApache AGE等对应实现在 neo4j_store.py、falkordb_store.py、age_store.py仓库还有 Amazon Neptune 和 Triplet StoreRDF4J、Blazegraph、Oxigraph、Jena、Anzo清单见 docs/storage-backends.md。时序图谱回答某个时间点事实是什么给边加上valid_from/valid_until同一张图就能回答不同年份的问题——比如 alice 先当 acme 的 CEO、后跳槽 betafrom 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_granularityday) r2020 tq.query_at_time(kg, query, at_time2020-06-15) r2023 tq.query_at_time(kg, query, at_time2023-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_storeVectorStore(backendfaiss, dimension768), # vector_store 是必填项 knowledge_graphContextGraph(advanced_analyticsTrue), decision_trackingTrue, ) context.store(GPT-4 outperforms GPT-3.5 on reasoning benchmarks by 40%) # 带溯源存一条事实 decision_id context.record_decision( categorymodel_selection, scenarioChoose LLM for production reasoning pipeline, reasoningGPT-4 benchmark advantage justifies 3x cost increase, outcomeselected_gpt4, confidence0.91, ) precedents context.find_precedents(model selection reasoning, limit5) # 相似历史决策 influence context.analyze_decision_influence(decision_id) # 该决策的下游影响几个默认值心里有数即可实现见 agent_context.py、agent_memory.pyretention_days30记忆保留天数None表示永久max_memories10000记忆条数上限hybrid_alpha0.5向量检索与图检索的平衡系数0 偏向量、1 偏图graph_expansionTruemax_expansion_hops默认 2 跳命中记忆后沿图扩展取证。同一套机制也支撑 GraphRAG 和多 Agent 共享上下文集成示例见 docs/guides/decision-intelligence.md 与 integrations/。排错速查症状大概率原因一步解决一个实体都抽不出来扫描件 PDF 没有文本层DocumentParser会警告换DoclingParser(enable_ocrTrue)先pip install semantica[parse-docling]大语料处理太慢全量载入内存 CPU 推理pip install semantica[gpu]上 CUDA或先用scan_directory只扫路径再逐文档解析、边抽边写持久化后端大图内存溢出默认图存在内存NetworkX里切持久化后端如FalkorDBStore(hostlocalhost, port6379)或直接 Neo4j企业网关后 NER 回退到 pattern 模式v0.5.0 已修复的老问题pip install --upgrade semantica大语料场景还有一个进阶编排思路FileIngestor().scan_directory(path, recursiveTrue)只返回文件元信息、不读内容你拿它循环每次只加载一个文档抽完立刻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),仅供参考
返回列表