ARTICLE DETAIL

资讯详情

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

LlamaIndex ChromaReader 实战指南:从持久化 Chroma 集合加载文档到 LlamaIndex

LlamaIndex ChromaReader 实战指南:从持久化 Chroma 集合加载文档到 LlamaIndex LlamaIndex ChromaReader 实战指南从持久化 Chroma 集合加载文档到 LlamaIndex【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index本文是一篇围绕 LlamaIndex 官方集成包llama-index-readers-chroma中ChromaReader类的技术指南。ChromaReader是 LlamaIndex 读取器Reader家族的一员专门用于从已持久化的 Chroma 集合中检索文档并将其转换为 LlamaIndex 的Document对象从而无缝接入索引构建、检索与问答流水线。读完本文你将掌握ChromaReader的安装方式、全部构造参数与load_data查询参数的语义、底层实现原理并能直接用示例代码从本地磁盘或远程 Chroma 服务中批量加载数据。ChromaReader 是什么Chroma 是一个面向文档集合及其向量嵌入管理的高效框架而ChromaReader的作用正是充当 LlamaIndex 与 Chroma 之间的桥梁。它在 llama-index-integrations/readers/llama-index-readers-chroma/llama_index/readers/chroma/base.py 中实现官方描述为Retrieve documents from existing persisted Chroma collections.即从已经存在且已持久化的 Chroma 集合中检索文档。它不负责写入或创建集合而是专注于读取——这也意味着在使用它之前目标集合必须已经通过其他方式例如chromadb客户端或 LlamaIndex 的 Chroma Vector Store创建并写入数据。从源码结构看ChromaReader继承自 BaseReader因此天然具备 LlamaIndex 读取器的统一行为load_data返回List[Document]同时通过基类获得lazy_load_data、aload_data、load_langchain_documents等派生能力。包入口init.py 仅导出ChromaReader一个类。安装ChromaReader作为独立集成包发布可通过 pip 直接安装pip install llama-index-readers-chroma从 pyproject.toml 可以看到其运行时依赖chromadb0.4.22,0.5Chroma 官方客户端库llama-index-core0.13.0,0.15LlamaIndex 核心包提供Document、BaseReader等基础组件。如果你的环境尚未安装chromadbChromaReader会在初始化时抛出提示信息chromadb package not found, please run pip install chromadb初始化参数详解ChromaReader的构造函数定义如下源码见 base.pydef __init__( self, collection_name: str, persist_directory: Optional[str] None, chroma_api_impl: str rest, chroma_db_impl: Optional[str] None, host: str localhost, port: int 8000, ) - None:各参数含义与底层行为参数类型默认值说明collection_namestr必填要读取的持久化集合名称None时会抛出ValueError源码中显式校验 Please provide a collection name.persist_directoryOptional[str]None集合持久化所在目录。提供后走本地持久化模式实际路径缺省为./chromachroma_api_implstrrestChroma API 实现方式默认为 RESTchroma_db_implOptional[str]NoneChroma DB 实现当前版本源码中为预留参数不影响客户端选择逻辑hoststrlocalhost远程 Chroma 服务主机名用于 HTTP 客户端模式portint8000远程 Chroma 服务端口默认 8000客户端选择逻辑本地 vs 远程构造函数中有一个关键分支base.py#L43-L51当persist_directory非空时创建chromadb.PersistentClient(pathpersist_directory)读取本地磁盘上持久化的集合否则host或port非空而二者均有默认值因此通常总会进入该分支创建chromadb.HttpClient(hosthost, portport)连接远程 Chroma 服务。最后统一通过self._client.get_collection(collection_name)获取目标集合。需要特别注意的是这里的get_collection要求集合已存在如果集合不存在会报错这与从已有持久化集合检索的定位一致。load_data文本查询与向量查询load_data是读取器的核心入口签名如下base.py#L83-L125def load_data( self, query_embedding: Optional[List[float]] None, limit: int 10, where: Optional[dict] None, where_document: Optional[dict] None, query: Optional[Union[str, List[str]]] None, ) - Any:参数语义参数类型默认值说明query_embeddingOptional[List[float]]None查询向量。提供后走向量相似度检索路径collection.searchqueryOptional[Union[str, List[str]]]None查询文本或文本列表。提供后走文本查询路径collection.querylimitint10返回结果数量上限即n_resultswhereOptional[dict]{}按元数据过滤例如{metadata_field: is_equal_to_this}where_documentOptional[dict]{}按文档内容过滤例如{$contains: search_string}两条查询路径源码中load_data严格按照以下优先级分派向量检索路径query_embedding非空时调用collection.search(query_embedding..., n_resultslimit, where..., where_document..., include[metadatas, documents, distances, embeddings])。此时需要调用方自行准备查询向量例如用 Embedding 模型对查询文本编码适合以向量搜向量的语义检索场景。文本查询路径query_embedding为空但query非空时先将query规范化为列表query if isinstance(query, list) else [query]再调用collection.query(query_textsquery, ...)。此时由 Chroma 内部完成文本到向量的转换依赖集合创建时配置的 embedding 函数适合直接以自然语言查询。异常兜底两者都为空时抛出ValueError(Please provide either query embedding or query.)防止无意义的空查询。两条路径都显式传入include[metadatas, documents, distances, embeddings]即结果中同时携带元数据、文档文本、距离分数与向量。create_documents结果到 LlamaIndex Document 的映射无论走哪条查询路径最终都会调用create_documents(results)把 Chroma 的查询结果转换为List[Document]base.py#L55-L81。其核心逻辑是用zip并行遍历结果的四个字段并逐条构造Documentdocuments [] for result in zip( results[ids][0], results[documents][0], results[embeddings][0], results[metadatas][0], ): document Document( id_result[0], # Chroma 中的文档 ID textresult[1], # 文档文本 embeddingresult[2],# 文档向量 metadataresult[3], # 文档元数据 ) documents.append(document)这里展示了几个值得注意的实现细节字段索引[0]Chroma 的查询结果按查询条件分组对于单查询一个 embedding 或一个文本取第一个查询对应的结果列表即results[ids][0]等id_直接使用 Chroma 的文档 ID这保证了读取后的Document.node_id与 Chroma 中的原始 ID 一致便于后续追踪与去重向量被完整保留embedding字段被写入Document因此读取出的文档可以直接用于构建 LlamaIndex 向量索引无需重新计算嵌入。与 BaseReader 的关系及异步能力ChromaReader继承自 LlamaIndex 核心的 BaseReader抽象基类并直接覆写了load_data。通过基类ChromaReader实例还自动获得以下能力lazy_load_data惰性加载接口默认抛NotImplementedError提示子类未实现aload_data通过asyncio.to_thread将同步load_data包装为异步调用可在异步代码中直接使用load_langchain_documents将加载结果转换为 LangChain 文档格式d.to_langchain_format()便于与 LangChain 生态互操作。仓库中的单元测试 tests/test_readers_chroma.py 验证了类的继承关系def test_class(): names_of_base_classes [b.__name__ for b in ChromaReader.__mro__] assert BaseReader.__name__ in names_of_base_classes该测试通过检查__mro__方法解析顺序确认ChromaReader确实是BaseReader的子类从测试层面锁定了读取器体系的一致性。完整实战示例结合 README.md 与源码行为一个完整的读取流程如下from llama_index.core.schema import Document from llama_index.readers.chroma import ChromaReader # 1. 初始化指向已持久化的集合 reader ChromaReader( collection_nameYour Collection Name, persist_directoryDirectory Path, # 本地持久化目录 chroma_api_implrest, # Chroma API 实现默认 rest chroma_db_implNone, # Chroma DB 实现默认 None hostlocalhost, # 远程服务主机默认 localhost port8000, # 远程服务端口默认 8000 ) # 2. 方式一按文本查询字符串或字符串列表均可 documents reader.load_data( query_embeddingNone, # 文本查询时置空 limit10, # 返回条数 whereNone, # 元数据过滤如 {category: tech} where_documentNone, # 文档内容过滤如 {$contains: llama} query[search term], # 查询文本 ) # 3. 方式二按向量查询需自行提供查询向量 documents reader.load_data( query_embedding[0.1, 0.2, ...], # 查询向量 limit10, ) # 4. 使用结果构建 LlamaIndex 索引 from llama_index.core import VectorStoreIndex index VectorStoreIndex.from_documents(documents)远程模式示例当集合存放在远程 Chroma 服务时不传persist_directory改为指定host与portreader ChromaReader( collection_namemy_prod_collection, hostchroma.internal.example, # 远程服务地址 port8000, ) documents reader.load_data(query年度技术报告)过滤条件示例where与where_document是 Chroma 原生的过滤能力ChromaReader将其原样透传给底层search/query调用# 只检索 author 字段为 Alice 的文档 documents reader.load_data( query分布式系统, where{author: Alice}, ) # 只检索正文包含 LlamaIndex 的文档 documents reader.load_data( query最佳实践, where_document{$contains: LlamaIndex}, )使用注意事项集合必须预先存在ChromaReader通过get_collection获取集合若集合不存在会直接报错。请先用 Chroma 客户端或 LlamaIndex 的 Chroma Vector Store 写入数据并持久化。本地路径缺省值当persist_directory非空时源码中实际路径缺省为./chromapersist_directory if persist_directory else ./chroma但该分支只有在传入非空值时才会进入。query_embedding优先级高于query两者同时提供时load_data只走向量检索路径先判断query_embeddingquery会被忽略。limit默认 10需要更多结果时显式调大否则只会返回前 10 条。异步与 LangChain 互操作如需在异步环境或 LangChain 流水线中使用可借助基类提供的aload_data与load_langchain_documents。版本约束本集成依赖chromadb0.4.22,0.5与llama-index-core0.13.0,0.15见 pyproject.toml安装时请确保版本兼容。小结ChromaReader是 LlamaIndex 与 Chroma 生态对接的最小而完整的读取组件构造阶段根据persist_directory/host/port自动选择本地持久化客户端或 HTTP 客户端查询阶段支持向量检索与文本查询两条路径并通过create_documents将 Chroma 结果无损映射为携带id_、text、embedding、metadata的 LlamaIndexDocument。无论你是想把已有 Chroma 集合中的数据直接灌入索引还是作为检索工具嵌入 Agent 流水线都可以基于本文给出的参数表与示例快速落地。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表