Semantica 入门:为 AI 系统构建可查询、可解释的上下文与语义层
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
Semantica 是位于 LLM、向量存储与 Agent 框架之下的语义与上下文基础设施:它不是模型,而是一套不依赖 LLM 参与即可运行的确定性基础设施,用于图构建、推理与溯源。本文基于仓库 docs/index.md 编写,带你理解它的五大核心能力(上下文图、决策智能、全链路溯源、可解释推理、时间智能),并给出可直接复制的 OpenAI / Anthropic / Ollama 三种接入代码,以及从安装到深入使用的完整路线图。
为什么需要一个"语义层",而不是只靠向量检索
多数 AI Agent 运行在 embedding 之上,而不是"意义"之上。一个相似度分数没有结构、没有关系,也无法解释结果为何被召回。pip install semantica安装的正是解决这一问题的层:
- 确定性基础设施:图构建、推理、溯源全部可以在无 LLM 参与的闭环中运行;
- 把碎片化的企业数据转化为结构化、可查询的上下文图与知识图;
- 通过本体(ontology)、分类体系(taxonomy)与受控词表(OWL、SHACL、SKOS)治理,让数据的含义是显式声明的,而不是被 embedding 近似出来的;
- 溯源与审计线索不是事后补丁:一旦数据具备这种结构,溯源会自然产生——同一个支撑检索与推理的图,当监管者问"为什么"时也能给出直接答案。
这一设计在 semantica/context/agent_context.py 的模块说明中也有体现:AgentContext提供store()、retrieve()、forget()、conversation()等通用方法,自动检测"记忆 vs 文档""RAG vs GraphRAG",并通过布尔开关(advanced_analytics、kg_algorithms、vector_store_features、graph_expansion等)开启高级能力。
五大核心能力一览
上下文图(Context Graphs)
一个持久化、可查询的图,记录 Agent 所知道、所决定、所推理的一切。参考 上下文图指南,ContextGraph是线程安全的内存属性图,每个节点与边都带时间有效性窗口,内置 BFS 遍历与 FAISS 向量索引,并通过AgentContext提供近邻混合检索。
从源码看,ContextGraph完全由 Python dict 与threading.RLock支撑(见 semantica/context/context_graph.py),无需外部服务即可在单测中快速搭建;当多个 Agent 或线程并发写入共享知识库、分析师实时查询时尤为适用。
决策智能(Decision Intelligence)
record_decision()捕获每一次决策的完整生命周期与因果链:分类、场景、推理、结果、置信度、决策者、时间有效性(valid_from/valid_until),并支持跨系统上下文与实体关联。find_precedents()做混合先例检索(语义 + 结构),analyze_decision_influence()用图算法分析决策影响力。
源码中的record_decision()实现(semantica/context/agent_context.py#L1648-L1731)会构造Decision模型(见 semantica/context/decision_models.py),并依据_decision_backend路由到图存储或ContextGraph。决策数据模型支持序列化、校验、克隆与元数据/embedding 扩展,为审计与合规奠定基础。
全链路溯源(Full Provenance)
每一条事实都回溯到其来源,符合 W3C PROV-O 规范,面向 HIPAA、SOX、GDPR 等审计场景开箱即用。参考 溯源指南:ProvenanceManager为每个实体、关系、文档块与属性值记录 PROV-O 兼容条目,并附带 SHA-256 校验和用于防篡改检测,每次track_entity()自动形成版本链。
可解释推理(Explainable Reasoning)
前向链(forward chaining)、Datalog 与 SPARQL 三类推理引擎,每条推导都有可检查的推导路径。参考 推理指南,推理层把领域逻辑编码为规则并应用到知识图上,从而推导出原始文档中从未直接陈述的新事实——例如分别陈述 "APT29 uses SUNBURST" 与 "SUNBURST exploits CVE-2020-10148" 后,推理自动得出 "APT29 exploits CVE-2020-10148"。
时间智能(Temporal Intelligence)
Allen 区间代数与时间点快照(point-in-time snapshots),让图不仅知道"是什么",还知道"什么时候"。节点与边的时间有效性窗口支撑历史状态查询与"仅看当前信息"的过滤。
快速上手:一个 Agent 上下文的完整示例
AgentContext是这一切的统一入口。下面的三段代码(来自 docs/index.md 原文,并附源码参数说明)分别展示了 OpenAI、Anthropic 与本地 Ollama 三种配置。
OpenAI 接入
from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore from semantica.llms import OpenAI context = AgentContext( vector_store=VectorStore(backend="faiss", dimension=1536), knowledge_graph=ContextGraph(advanced_analytics=True), decision_tracking=True, llm=OpenAI(model="gpt-4o"), ) 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)Anthropic 接入
from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore from semantica.llms import LiteLLM import os context = AgentContext( vector_store=VectorStore(backend="faiss", dimension=1024), knowledge_graph=ContextGraph(advanced_analytics=True), decision_tracking=True, llm=LiteLLM(model="anthropic/claude-opus-4-7", api_key=os.getenv("ANTHROPIC_API_KEY")), ) context.store("Claude excels at long-context reasoning and code generation") decision_id = context.record_decision( category="model_selection", scenario="Choose LLM for document analysis pipeline", reasoning="Claude's 200k context window eliminates chunking overhead", outcome="selected_claude", confidence=0.94, ) precedents = context.find_precedents("document analysis model", limit=5)Ollama 本地部署(数据不出内网)
from semantica.context import AgentContext, ContextGraph from semantica.vector_store import VectorStore from semantica.llms import LiteLLM context = AgentContext( vector_store=VectorStore(backend="faiss", dimension=768), knowledge_graph=ContextGraph(advanced_analytics=True), decision_tracking=True, llm=LiteLLM(model="ollama/llama3.2", base_url="http://localhost:11434"), ) # Fully local: no data leaves your infrastructure context.store("Local LLMs enable air-gapped compliance deployments") decision_id = context.record_decision( category="deployment_model", scenario="Choose inference strategy for on-prem environment", reasoning="Air-gap requirement eliminates cloud API options", outcome="local_inference", confidence=0.99, )参数与调用链说明
VectorStore(backend="faiss", dimension=...):向量后端与维度需与所用 embedding 匹配。从 semantica/vector_store/config.py 看,默认配置为default_backend="faiss"、dimension=768、index_type="flat"、metric="cosine",并支持环境变量(如VECTOR_STORE_DEFAULT_BACKEND、VECTOR_STORE_DIMENSION)与 YAML/JSON/TOML 配置文件覆盖。ContextGraph(advanced_analytics=True):开启高级图分析。从 semantica/context/context_graph.py 的模块说明看,还可声明centrality_analysis、community_detection、node_embeddings等开关,它们懒加载但需在构造时声明。decision_tracking=True且knowledge_graph非空时,AgentContext.__init__(semantica/context/agent_context.py#L124-L291)会初始化DecisionRecorder、DecisionQuery、CausalChainAnalyzer与PolicyEngine;vector_store_features=True时还会调用vector_store.initialize_decision_pipeline()为决策检索建立混合搜索管线。store()支持自动类型检测:单个字符串按记忆项存储;字符串/字典列表按文档存储,并在extract_entities=True/extract_relationships=True时自动构建知识图(返回stored_count、graph_nodes、graph_edges统计)。retrieve()在提供knowledge_graph时自动启用 GraphRAG 混合检索。
与其他组件协同:不止于 Agent 上下文
AgentContext是入口,但不是全部。仓库中完整的模块链覆盖数据到决策的每个环节,可在 docs/index.md 的模块列表与 API 参考 中进一步查阅:
- 数据接入与加工:
semantica.ingest(文件、Web、数据库、Salesforce、Snowflake、SAP、Databricks 等 20+ 接入器)、semantica.parse、semantica.split、semantica.normalize、semantica.semantic_extract; - 图与存储:
semantica.kg、semantica.ontology、semantica.graph_store(Neo4j、Amazon Neptune、Apache AGE、FalkorDB 等)、semantica.triplet_store、semantica.vector_store; - 治理与质量:
semantica.provenance、semantica.change_management、semantica.deduplication、semantica.conflicts; - 推理与决策:
semantica.reasoning、semantica.context、semantica.embeddings; - 交付与运维:
semantica.export、semantica.visualization、semantica.pipeline、semantica.seed、semantica.llms、semantica.mcp_server、semantica.explorer、semantica.evals、semantica.core。
与任意技术栈共存
Semantica 可与任意 LLM 提供商、任意 Agent 框架共存,并直接从 Databricks、SAP、Salesforce、Snowflake 等企业数据平台接入数据——把它叠加到现有技术栈中,无需改变架构。仓库的 integrations 目录提供了 agno、crewai、google_adk、langchain、openclaw 等框架的适配层,集成指南 与 LLM 参考 覆盖 9 家提供商封装。
从安装到深入的路线图
- 安装:
pip install semantica可选 extras:
[all]、[neo4j]、[pinecone]。详见 安装指南。 - 构建流水线:按 快速开始 在 5 分钟内完成"接入文档 → 抽取实体 → 构建图 → 记录决策"全流程(LLM API key 为可选项,基于规则的抽取开箱即用)。
- 理解核心模型:核心概念 讲解知识图 vs 向量存储、GraphRAG,以及溯源与决策如何协同;注意其明确边界——这是系统级可解释性,说明的是"AI 系统做了什么"(输入上下文、产生的决策、溯源、应用的政策与完整执行轨迹),而非基础模型内部的思维链。
- 深入每个模块:每个模块都有带完整 API 文档与可运行示例的 参考页;Cookbook 提供 30+ 真实场景 notebook,覆盖高级抽取、图分析、可视化套件、多格式导出、时序知识图、Datalog 风格推理等主题。
小结
Semantica 的价值在于把"检索相关性"升级为"结构化意义":上下文图让关系可遍历、推理让隐含知识可推导、溯源让每一步可审计、时间智能让状态可回放——而这一切都不依赖 LLM 参与核心管线。对于需要可解释、可审计、可问责(Accountable AI)的高风险领域(金融、医疗、合规、安全情报)而言,它就是位于模型与业务之间的确定性语义层。
【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考