尧图精选

LlamaIndex VectorDB Tool 深度解析:用 auto_retrieve_fn 为 Agent 赋予带元数据过滤的向量检索能力

🕒 发布时间:2026/9/11 3:25:28 📁 来源:尧图网络
LlamaIndex VectorDB Tool 深度解析用 auto_retrieve_fn 为 Agent 赋予带元数据过滤的向量检索能力【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_indexllama-index-tools-vector-db是 LlamaIndex 官方集成包中的一个轻量级工具模块它将一个VectorStoreIndex封装成标准的 LlamaIndex ToolSpec使 Agent 可以直接以自然语言查询的方式对向量数据库发起检索并在检索时携带top_k与元数据过滤条件。本文以 docs/api_reference/api_reference/tools/vector_db.md 中声明的VectorDBToolSpec为线索结合仓库源码、README 与测试用例完整讲解其工作原理、参数语义、Agent 集成方式与源码级实现细节读完即可在自有项目中复现结构化元数据过滤 语义检索的 Agent 工具。模块定位API Reference 指向谁该关联文档是 MkDocs 自动生成的 API 引用页声明内容为::: llama_index.tools.vector_db options: members: - VectorDBToolSpec这意味着它对应的 Python 模块为llama_index.tools.vector_db公开文档化的成员是VectorDBToolSpec类。该模块的实际源码位于 llama-index-integrations/tools/llama-index-tools-vector-db/llama_index/tools/vector_db/base.py包入口 llama_index/tools/vector_db/init.py 中对外导出VectorDB与VectorDBToolSpec两个名字。从 pyproject.toml 可以看到该包的元信息包名llama-index-tools-vector-db版本0.5.0License MIT运行时唯一依赖llama-index-core0.13.0,0.15要求 Python3.10,4.0在 LlamaHub 元数据中注册的导入路径为llama_index.tools.vector_db类作者登记为jerryjliu。也就是说只要安装了配套的llama-index-core该工具包不依赖任何特定向量数据库厂商 SDK——真正的存储与检索能力全部由核心层抽象的BaseIndex/VectorStoreIndex提供这正是它小而通用的设计前提。安装与导入使用本工具前需要安装核心库与本集成包pip install llama-index-core llama-index-tools-vector-db0.5.0然后按官方 README 的推荐方式导入from llama_index.tools.vector_db import VectorDB, VectorDBToolSpec其中VectorDB是源码中保留的向后兼容别名见 base.py 第 58-59 行# backwards compatibility VectorDB VectorDBToolSpec新代码建议直接使用VectorDBToolSpec但阅读旧项目时遇到VectorDB也应视为同一个类。VectorDBToolSpec 源码逐段解析VectorDBToolSpec继承自核心层的BaseToolSpec定义于 llama-index-core/llama_index/core/tools/tool_spec/base.py它通过类属性spec_functions声明自己暴露给 Agent 的函数集合通过to_tool_list()把内部方法转换为可供 Agent 调用的ToolMetadata列表。类声明与初始化class VectorDBToolSpec(BaseToolSpec): Vector DB tool spec. spec_functions [auto_retrieve_fn] def __init__( self, index: BaseIndex, # TODO typing ) - None: Initialize with parameters. self._index index关键点spec_functions [auto_retrieve_fn]整个 ToolSpec 只暴露一个工具函数即auto_retrieve_fn这是 Agent 可调用的全部能力边界构造参数只有一个index类型标注为BaseIndex源码注释里留有TODO typing说明此处类型约束较宽松实际使用时传入VectorStoreIndex实例即可构造函数仅将 index 保存在self._index不做任何连接、校验或数据加载因此初始化成本极低。auto_retrieve_fn唯一的工具函数def auto_retrieve_fn( self, query: str, top_k: int, filter_key_list: List[str], filter_value_list: List[str], ) - str: Auto retrieval function. Performs auto-retrieval from a vector database, and then applies a set of filters. exact_match_filters [ ExactMatchFilter(keyk, valuev) for k, v in zip(filter_key_list, filter_value_list) ] retriever VectorIndexRetriever( self._index, filtersMetadataFilters(filtersexact_match_filters), top_ktop_k, ) query_engine RetrieverQueryEngine.from_args(retriever) response query_engine.query(query) return str(response)四个入参的语义如下参数类型含义querystr要执行的语义检索查询文本top_kint返回的命中节点数量上限filter_key_listList[str]元数据过滤字段名列表filter_value_listList[str]与字段名一一对应的过滤值列表实现逻辑分四步构造精确匹配过滤条件用zip(filter_key_list, filter_value_list)将两个列表按位配对逐个生成ExactMatchFilter(keyk, valuev)。两个列表的长度应保持一致zip会以较短列表为准截断多余元素因此传入不对称列表时不会报错但会造成静默的过滤条件丢失——这是使用时需要注意的坑。装配带过滤的检索器VectorIndexRetriever接收index、filtersMetadataFilters(filtersexact_match_filters)与top_k即先按元数据精确过滤再按向量相似度取前 k 个。构建查询引擎RetrieverQueryEngine.from_args(retriever)以检索器为唯一来源生成查询引擎走默认的响应合成response synthesizer流程。执行查询并返回字符串query_engine.query(query)得到RESPONSE对象str(response)将其转换为纯文本返回给 Agent 作为工具调用结果。这里Auto Retrieval的含义是Agent 自行决定查询词、top_k 与过滤条件工具端无需预先编写任何存储过程或查询模板——只要把数据库 schema 描述清楚交给 LLMLLM 就会生成合理的调用参数。完整集成示例把向量库变成 Agent 工具官方 README.md 给出了一个可直接运行的 Agent 集成示例其核心思路是先构造索引再构造 ToolSpec然后用to_tool_list()配合元数据映射注册为 Agent 工具。from llama_index.tools.vector_db import VectorDB from llama_index.core.agent.workflow import FunctionAgent from llama_index.llms.openai import OpenAI from llama_index.core.vector_stores import VectorStoreInfo from llama_index.core import VectorStoreIndex index VectorStoreIndex(nodesnodes) tool_spec VectorDB(indexindex) vector_store_info VectorStoreInfo( content_infobrief biography of celebrities, metadata_info[ MetadataInfo( namecategory, typestr, descriptionCategory of the celebrity, one of [Sports, Entertainment, Business, Music], ), MetadataInfo( namecountry, typestr, descriptionCountry of the celebrity, one of [United States, Barbados, Portugal], ), ], ) agent FunctionAgent( toolstool_spec.to_tool_list( func_to_metadata_mapping{ auto_retrieve_fn: ToolMetadata( namecelebrity_bios, descriptionf\ Use this tool to look up biographical information about celebrities. The vector database schema is given below: {vector_store_info.json()} {tool_spec.auto_retrieve_fn.__doc__} , fn_schemacreate_schema_from_function( celebrity_bios, tool_spec.auto_retrieve_fn ), ) } ), llmOpenAI(modelgpt-4.1), ) print( await agent.run(Tell me about two celebrities from the United States. ) )这段示例的关键设计值得逐条拆解VectorStoreInfo/MetadataInfo描述 schemacontent_info说明库中内容是什么metadata_info逐个字段声明可过滤的元数据字段名、类型、可选值枚举。示例中数据库存放名人传记元数据包括category名人领域与country国籍description中直接写明枚举值方便 LLM 正确生成过滤参数。to_tool_list(func_to_metadata_mapping...)将auto_retrieve_fn重映射为一个名为celebrity_bios的对外工具。工具描述 用途说明 vector_store_info.json()结构化 schemaauto_retrieve_fn.__doc__参数文档三层信息拼接后注入 prompt让 LLM 知道什么时候用、schema 长什么样、参数怎么填。create_schema_from_function根据auto_retrieve_fn的签名自动生成 Pydantic 风格的函数调用 schema保证 Agent 输出的 JSON 参数能严格对应query、top_k、filter_key_list、filter_value_list四个字段。FunctionAgent以OpenAI(modelgpt-4.1)为 LLM 的通用 Agent。用户只需说Tell me about two celebrities from the United StatesLLM 就会自行推断出query如 biography of celebrities、top_k如 2以及filter_key_list[country]、filter_value_list[United States]再调用工具完成检索。运行结果即两段符合过滤条件的名人传记文本——整个过程 Agent 无需感知向量库的具体存储后端。元数据过滤机制从参数到检索器的传递链过滤能力是本工具区别于普通 VectorStoreIndex 直接查询的核心。相关类型全部来自核心层ExactMatchFilter与MetadataFilters定义于 llama-index-core/llama_index/core/vector_stores/types.pyVectorIndexRetriever位于llama_index.core.retrieversRetrieverQueryEngine位于llama_index.core.query_engine。调用链为auto_retrieve_fn(query, top_k, filter_key_list, filter_value_list) → zip() 逐对打包 → [ExactMatchFilter(key, value), ...] → MetadataFilters(filtersexact_match_filters) → VectorIndexRetriever(index, filters..., top_k...) → RetrieverQueryEngine.from_args(retriever).query(query) → str(response)值得注意的实现特征过滤是先过滤、后检索MetadataFilters在检索器构造阶段即被传入向量库在后端层面先做元数据精确匹配再做向量相似度排序这与先检索全部、再在结果上二次过滤的做法有本质区别能显著减少无效向量计算精确匹配语义ExactMatchFilter是等值匹配key 等于 value适用于枚举型元数据如上述示例的category、country。如果需求是范围过滤、模糊匹配或多值 OR则需要自行扩展MetadataFilters的其他过滤算子本工具默认只提供等值能力默认响应合成RetrieverQueryEngine.from_args使用默认的响应合成策略即把检索到的节点作为上下文交给 LLM 生成最终答案。示例中的输出因此是答案文本而非原始节点列表。兼容性VectorDB 别名与测试保障包内测试 tests/test_tools_vector_db.py 验证了类的继承契约def test_class(): names_of_base_classes [b.__name__ for b in VectorDBToolSpec.__mro__] assert BaseToolSpec.__name__ in names_of_base_classes该测试断言VectorDBToolSpec的方法解析顺序MRO中必须包含BaseToolSpec即任何使用该工具包的代码都可以依赖其 ToolSpec 接口spec_functions、to_tool_list()等稳定存在。同时__init__.py同时导出VectorDB与VectorDBToolSpec保证旧写法from llama_index.tools.vector_db import VectorDB依然可用。从源码结构推断本工具面向的典型场景是RAG Agent 工具化把已建好的向量索引直接作为 Agent 的工具让 LLM 自主决定查询与过滤参数多租户/分类检索通过元数据字段如部门、文档类型、语言、地区把检索范围限制在指定子集内避免跨域污染低代码接入由于只依赖llama-index-core任何实现了BaseIndex接口的索引包括各类向量库后端都可以被包装无需为每种后端单独写 Agent 工具。使用注意事项小结保证filter_key_list与filter_value_list长度一致zip会静默截断长度不匹配时多余的过滤条件会被丢弃top_k需为正整数由 LLM 生成时可能不稳定建议在 schema 描述中明确语义对结果数量有硬性要求时可结合后置处理兜底元数据必须与索引中节点的metadata字段对应ExactMatchFilter的值会与节点metadata中的同名 key 做等值比较节点构建时未写入该字段将过滤不到任何结果工具名与描述决定 Agent 的调用质量VectorStoreInfo中的枚举说明越精确LLM 生成合法过滤参数的概率越高版本约束包要求llama-index-core0.13.0,0.15升级核心库前需确认版本在兼容区间内。综上VectorDBToolSpec以极小的代码面一个工具函数 四个参数完成了向量检索 元数据精确过滤的完整闭环并通过标准 ToolSpec 协议无缝接入 LlamaIndex 的 Agent 体系。无论是希望快速为现有 RAG 系统增加 Agent 入口还是需要让 LLM 自主控制检索范围这个工具都是最直接的落地方案。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
上一篇/下一篇内容由系统自动关联 返回资讯列表 →