
Semantica × LangChain 集成实战GraphRAG 检索器、VectorStore 适配器与 Agent 工具接入指南【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semanticaSemantica 通过 integrations/langchain 提供三个即插即用drop-in适配器将语义上下文图ContextGraph与混合检索能力平滑嵌入 LangChain 链路与 LangGraph Agent 中。读完本文你将掌握SemanticaRetriever的多跳 GraphRAG 检索原理、SemanticaVectorStore的标准VectorStore接口用法以及SemanticaKGTool/SemanticaDecisionTool两个 Agent 工具的接入方式并理解其在缺失langchain-core时如何优雅降级。安装与兼容性集成包随 Semantica 一起发布通过 extras 一键安装pip install semantica[langchain]也可以只安装核心适配器所依赖的最小依赖pip install langchain-core集成要求langchain-core 0.3。若环境中未安装langchain-core集成模块仍然可以正常导入所有类依然携带完整的 Semantica API只是无法绑定到 LangChain 的 Chain / Agent 上。此时build()方法返回None上层应用可以通过LANGCHAIN_AVAILABLE标志分支处理详见下文「优雅降级机制」一节。这一点在 integrations/langchain/init.py 中被显式导出公开 API 面为SemanticaRetrieverBaseRetriever子类SemanticaVectorStoreVectorStore子类SemanticaKGTool、SemanticaDecisionToolBaseTool子类LANGCHAIN_AVAILABLE布尔标志组件总览组件基类核心能力SemanticaRetrieverBaseRetriever混合检索HybridSearch作为种子召回再沿图边扩展hops步默认 2产出 GraphRAG 风格结果SemanticaVectorStoreVectorStore在HybridSearch之上实现add_texts/similarity_search/similarity_search_with_score/from_texts标准接口SemanticaKGTool/SemanticaDecisionToolBaseTool分别暴露semantica_query_graph与semantica_query_decisions两个工具供 LangGraph / tool-calling Agent 调用SemanticaRetriever多跳 GraphRAG 检索器检索器的工作流程是先用混合检索HybridSearch召回首轮命中再以这些命中节点为锚点沿图边扩展hops步使结果超越单纯的向量相似度获得图结构上下文。from integrations.langchain import SemanticaRetriever from semantica.context import ContextGraph from semantica.vector_store import HybridSearch graph ContextGraph() hybrid HybridSearch() retriever SemanticaRetriever(graphgraph, hybridhybrid, hops2, top_k10) from langchain.chains import RetrievalQA qa RetrievalQA.from_chain_type(llmllm, retrieverretriever)SemanticaRetriever可直接接入任何接受 retriever 的 LangChain 链路如上面的RetrievalQA也可用于 LCEL 的RunnableLambda/as_retriever组合。构造参数说明参数默认值说明graph必填一个semantica.context.ContextGraph实例承载上下文图与决策日志hybridNone一个semantica.vector_store.HybridSearch实例用于生成检索种子省略时退回图内关键词扫描hops2图边扩展步数即 BFS 遍历深度top_k10种子命中数量即首轮召回条数底层实现原理从源码 integrations/langchain/retriever.py 可以看到完整链路种子召回_seed_results若提供了hybrid调用self.hybrid.search(query, kself.top_k)若混合检索抛出异常如后端不可用自动降级为self.graph.query(query, limitself.top_k)的关键词扫描两者皆失败则返回空列表。命中解析HybridSearch.search()返回的命中结构形如{id, score, distance, metadata}其中内容位于metadata内部、id是向量 id 而非图节点 id。因此适配器提供_hit_id/_hit_content/_hit_type/_hit_score四个解析函数优先读取metadata.node_id、嵌套node.properties.content等字段兼容混合检索与ContextGraph.query两种不同的命中结构。这一点在 tests/integrations/langchain/test_langchain_integration.py 中有专门用例覆盖test_hit_id_prefers_metadata_node_id_over_vector_id。图扩展_get_relevant_documents对每个种子节点调用graph.get_neighbors(node_id, hopsself.hops)获取邻域节点。ContextGraph.get_neighbors见 semantica/context/context_graph.py采用 BFS 遍历边权重会随路径逐跳衰减next_decay decay_so_far * edge.weight并支持relationship_types白名单与min_weight过滤。扩展是 best-effort 的单个节点扩展失败仅记录 debug 日志不影响整体检索。结果排序种子命中带真实分数排在前面邻居节点随后同时用seen_ids去重并保持 id → payload 的确定性顺序避免 set 无序带来的抖动。文档产出每个命中被包装成 LangChainDocumentpage_content取命中内容metadata注入node_id、node_type、score以及原始元数据。测试test_retriever_reads_hybrid_metadata_and_expands_by_node_id验证了上述行为从混合检索命中alice调用get_neighbors(alice, hops2)得到bob最终返回文档顺序为[alice, bob]且bob的weight被映射为score。SemanticaVectorStore标准 VectorStore 适配器SemanticaVectorStore将 Semantica 的混合检索包装为标准 LangChainVectorStore可直接用于RetrievalQA、LCEL 链等场景from integrations.langchain import SemanticaVectorStore store SemanticaVectorStore(hybridhybrid) store.add_texts( [document one, document two], metadatas[{source: a}, {source: b}], ) docs store.similarity_search(document, k2) docs, scores store.similarity_search_with_score(document, k2)各方法的行为细节add_texts(texts, metadatasNone, **kwargs)委托给 Semantica 向量存储的add_documents写入并返回生成的 ID。底层委托链为优先使用构造时传入的vector_store参数否则回退到hybrid.vector_store两者皆不可用且缺少add_documents方法时抛出ValueError。因此HybridSearch初始化时应传入vector_store或在SemanticaVectorStore构造时直接传vector_store。对应实现见 integrations/langchain/vectorstore.py。similarity_search(query, k4, **kwargs)调用hybrid.search(query, kk)并把每个命中转为Documentmetadata含node_id、node_type但不含分数。similarity_search_with_score(query, k4, **kwargs)返回(Document, score)二元组列表score 取自命中的score或distance字段。from_texts(texts, embeddingNone, metadatasNone, **kwargs)LangChain 惯例的类方法。注意必须通过关键字参数传入预先配置好的hybrid实例from_texts(..., hybridhybrid)否则抛出ValueError。测试test_from_texts_requires_hybrid_kwarg专门验证了这一约束。向量检索本身由 semantica/vector_store/hybrid_search.py 中的HybridSearch承担其内部支持reciprocal_rank_fusion倒数排名融合与weighted_average加权平均等融合排序策略可通过ranking_strategy配置。Agent 工具查询上下文图与决策日志两个工具类都是 LangChainBaseTool子类可直接传入 LangGraph 的create_react_agent或其他 tool-calling Agentfrom integrations.langchain import SemanticaKGTool, SemanticaDecisionTool from langgraph.prebuilt import create_react_agent tools [ SemanticaKGTool(graph), SemanticaDecisionTool(graph), ] agent create_react_agent(model, tools)工具名称说明SemanticaKGToolsemantica_query_graph对共享上下文图执行关键词 / 自然语言查询返回匹配的实体与关系SemanticaDecisionToolsemantica_query_decisions检索已记录的决策日志decision log工具输入 Schema两个工具均通过 Pydantic 定义输入参数见 integrations/langchain/tools.py可被 LangChain 自动转换为模型可理解的工具描述QueryGraphInputquery自然语言或关键词图查询必填、limit最大返回节点数默认 10QueryDecisionsInputcategory用于搜索决策记录的关键词留空时返回决策洞察、limit按关键词搜索时的最大结果数默认 10。调用行为与返回格式SemanticaKGTool._run(query, limit10)调用graph.query(query, limitlimit)结果经json.dumps(..., defaultstr, ensure_asciiFalse)序列化为 JSON 字符串返回defaultstr保证非标准对象也能被序列化。SemanticaDecisionTool._run(category, limit10)当category非空时调用graph.query(category, limitlimit)检索决策日志为空时调用graph.get_decision_insights()返回决策统计洞察总数、类别分布、结果分布、置信度统计等见 semantica/context/context_graph.py。两个工具都提供同步_run与异步_arun两个入口异常时返回{error: ...}形式的 JSON保证 Agent 拿到的永远是合法 JSON。对应测试test_kg_tool_returns_full_valid_json、test_tool_errors_are_json、test_decision_tool_empty_category_uses_insights分别验证了长文本 JSON 序列化、异常兜底与空 category 走洞察路径的行为。优雅降级机制整个集成刻意设计为「langchain-core可有可无」模块顶层用try: from langchain_core...包裹导入成功则LANGCHAIN_AVAILABLE True失败则置为False并记录错误信息见 integrations/langchain/retriever.py。有langchain-core时BaseRetriever/VectorStore/BaseTool是 Pydantic 模型适配器通过super().__init__(...)显式传入声明字段完成校验没有时基类是普通object适配器直接手动赋值字段功能照常可用。工具的build()方法返回自身或NoneAgent 构建代码可据此判断是否将工具加入工具列表。测试 tests/integrations/langchain/test_degradation.py 通过子进程注入ImportError屏蔽langchain_core验证了「无 LangChain 环境下仍可导入、字段赋值正常、build()返回None、_get_document抛出带提示信息的RuntimeError」这一完整降级路径。测试与验证仓库为集成提供了两组自动化测试tests/integrations/langchain/test_langchain_integration.py覆盖命中解析id / content / type 的优先级与嵌套解包、检索器的种子召回与图扩展顺序、VectorStore 的add_texts委托与from_texts约束、工具的 JSON 契约与BaseTool兼容性并包含使用真实ContextGraph的端到端调用用例。tests/integrations/langchain/test_degradation.py在独立子进程中模拟无langchain-core环境证明降级路径真实可用。更多资源integrations/langchain/README.md集成的快速上手与兼容性说明integrations/langchain/init.py公开 API 面与版本号当前0.1.0docs/guides/graphrag.mdSemantica 的 GraphRAG 方法论与工程实践docs/integrations/agno.md与 Agno 生态的集成方式可作为多框架接入的对照参考semantica/context/context_graph.pyContextGraph的get_neighbors/query/get_decision_insights等被适配器依赖的核心实现semantica/vector_store/hybrid_search.pyHybridSearch的检索与融合策略实现。【免费下载链接】semanticaGraph-Native Infrastructure for Context and Accountable AI Systems项目地址: https://gitcode.com/GitHub_Trending/sema/semantica创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考