ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

llmware 语义检索实战:用 Query 类构建从文档库到语义查询的完整 RAG 检索链路

llmware 语义检索实战:用 Query 类构建从文档库到语义查询的完整 RAG 检索链路 llmware 语义检索实战用 Query 类构建从文档库到语义查询的完整 RAG 检索链路【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmwarellmware 的检索Retrieval能力是其企业级 RAG 管线的核心环节。本文基于官方示例文档 docs/examples/retrieval.md以一个自包含的可运行示例为主线完整讲清楚三件事如何创建并加载一个财务文档样本库FinDocs、如何为其构建嵌入索引embeddings、如何用Query类的semantic_query方法执行语义查询并通过embedding_distance_threshold控制召回质量。读完后你可以直接复制示例代码在本地跑通建库 → 嵌入 → 查询全流程并理解每个参数在 llmware/retrieval.py 源码中的真实作用。一、示例的整体流程官方示例的核心逻辑在 llmware/retrieval.py 的模块文档中被概括为Query类提供对Library集合的高层查询接口支持三类检索策略文本检索text retrieval直接作用于文本集合数据库不依赖向量库语义检索semantic retrieval依赖向量数据库且要求已为该 Library 预先构建 embeddings混合策略hybrid结合文本与语义查询的便捷方法如dual_pass_query。示例代码的完整可执行版本位于 solutions/sources/semantic_retrieval.py与文档中的代码完全一致。整体流程分三步LLMWareConfig().set_active_db(sqlite) # 选择文本集合存储 ↓ Library().create_new_library(lib_semantic_query_1) Setup().load_sample_files() # 下载 FinDocs 财务文档 library.add_files(...) # 解析入库 library.install_new_embedding(...) # 构建嵌入索引 ↓ Query(library).semantic_query(ESG initiatives, result_count20)二、前提选择文本集合的底层数据库示例入口处执行LLMWareConfig().set_active_db(sqlite)这一行决定了 Library 的文本集合解析后的 block 数据存储在哪种数据库中与语义检索所用的向量库chromadb/Milvus 等是两个独立的选择。从 llmware/configs.py 的源码看set_active_db会将新值写入配置项collection_db并校验该值必须在支持列表cls._supported[collection_db]内否则抛出LLMWareExceptionclassmethod def set_active_db(cls, new_db): Sets the default database for Library text collections if new_db in cls._supported[collection_db]: cls._conf[collection_db] new_db else: raise LLMWareException(messagefLLMWareConfig - set_active_db - selected fdb is not supported - {new_db})使用sqlite意味着零外部依赖适合首次在本机体验完整流程。三、步骤一创建并加载 FinDocs 样本库import os from llmware.library import Library from llmware.setup import Setup def create_fin_docs_sample_library(library_name): print(fupdate: creating library - {library_name}) library Library().create_new_library(library_name) sample_files_path Setup().load_sample_files(over_writeFalse) ingestion_folder_path os.path.join(sample_files_path, FinDocs) parsing_output library.add_files(ingestion_folder_path) return library三个关键调用逐一说明Library().create_new_library(library_name)显式构造器创建新库从 llmware/library.py 的 docstring 可见如果同名库已存在则加载已有库If a library with the same name already exists, it will load the existing library并且库名会被做安全性检查与改写。因此该步骤是幂等的重复运行示例不会因库名冲突而失败。Setup().load_sample_files(over_writeFalse)从 llmware 维护的公开 AWS S3 桶下载样本文件到llmware_path/sample_files。从 llmware/setup.py 的源码看若sample_files目录已存在且over_writeFalse则直接返回本地路径而不重新下载这也是示例注释may take a few minutes the first time的原因传over_writeTrue会拉取最新版本。样本文件覆盖八个领域与本示例相关的FinDocs 约为 15 份财务年报、财报与 10-K 文件——这正好解释了为何示例查询词选择了 ESG initiatives、stock performance 这类财务语料主题。library.add_files(ingestion_folder_path)批量解析目录中的文档产出结构化的 text/table/image block 并写入文本集合返回解析统计结果示例中赋值给parsing_output可用于确认解析块数与文档数。四、步骤二构建嵌入索引library.install_new_embedding( embedding_model_nameindustry-bert-sec, vector_dbchromadb, batch_size200 )该调用为整个库构建语义检索的向量索引有三个参数需要把握install_new_embedding定义见 llmware/library.py参数示例取值说明embedding_model_nameindustry-bert-secllmware 模型目录中的行业向 BERT 嵌入模型面向金融/证券文本vector_dbchromadb向量存储。官方注释明确提示如果你已安装 Milvus 或其他向量库请随意替换please feel free to substitutebatch_size200嵌入批处理大小直接影响构建时的内存峰值文档中给出的两条实践建议值得保留内存受限的笔记本(1) 调小batch_size(2) 换用更小的嵌入模型mini-lm-sbert已有向量库环境可将vector_db替换为 Milvus 等Query类会自动从库的嵌入记录embedding record中读取对应的库名与模型名无需在查询侧额外配置。五、步骤三用 Query 类执行语义查询5.1 实例化与返回键控制from llmware.retrieval import Query q Query(library) # 可选只返回需要的键默认返回完整键集 q.query_result_return_keys [distance, file_source, page_num, text]Query的初始化逻辑llmware/retrieval.py值得细看它决定了语义检索能否开箱即用构造器会读取该库的embedding 状态记录self.library.get_embedding_status()。若库上存在状态为yes的嵌入记录则自动绑定对应的embedding_db与embedding_model_name并将search_mode置为semantic随后加载嵌入模型若找不到有效嵌入记录则回落到text模式。若库上存在多组嵌入多个嵌入模型或多个向量库可通过构造参数embedding_model_name、vector_db显式指定查询哪一组。返回键有三档默认集源码 llmware/retrieval.py 定义如下# 完整键集默认值 self.query_result_standard_keys [_id, text, doc_ID, block_ID, page_num, content_type, author_or_speaker, special_field1, file_source, added_to_collection, table, coords_x, coords_y, coords_cx, coords_cy, external_files, score, similarity, distance, matches] # 精简集 self.query_result_short_keys [text, file_source, page_num, score, distance, matches] # 最小必需集set_output_keys 时会自动补齐并合并进结果 self.query_result_min_required_keys [text, file_source, page_num]因此默认每条结果都会携带约 20 个字段含坐标、相似度、命中位置matches等示例中把query_result_return_keys手动收缩为 4 个键只为打印和下游消费保留distance、file_source、page_num、text。如需程序化设置也可以调用q.set_output_keys([...])它会对键做合法性校验并自动补回text/file_source/page_num这三个最小必需键见 llmware/retrieval.py。5.2 三个递进的查询# 查询 1基本语义查询 my_query ESG initiatives query_results1 q.semantic_query(my_query, result_count20) for i, result in enumerate(query_results1): print(results - , i, result) # 查询 2换主题、换召回数量 my_query2 stock performance query_results2 q.semantic_query(my_query2, result_count10) # 查询 3加大召回并设置距离阈值 my_query3 cloud computing # 注意embedding_distance_threshold 会截断 distance 1.0 的结果 query_results3 q.semantic_query(my_query3, result_count50, embedding_distance_threshold1.0)semantic_query的完整签名llmware/retrieval.py为def semantic_query(self, query, result_count20, embedding_distance_thresholdNone, custom_filterNone, results_onlyTrue):各参数的语义与默认行为query查询文本会被嵌入模型编码为查询向量result_count默认 20请求返回的块数上限embedding_distance_threshold距离阈值。不传时使用实例属性self.semantic_distance_threshold其默认值在__init__中设为1000源码注释# basic shut off at such a high level即默认实际不做截断。传入1.0后只保留嵌入空间距离小于 1.0 的块——这正好对应查询 3 中cloud computing与财务语料语义距离较远、需要阈值过滤无关召回的场景。custom_filter可选的{键: 值}精确过滤字典在语义结果返回后应用见下节源码results_only默认 TrueTrue 时返回结果列表False 时返回包含query/results/doc_ID/file_source的完整字典。从实现看llmware/retrieval.pysemantic_query的执行链路为self.load_embedding_model()确保嵌入模型就绪否则抛出ModelNotFoundExceptionself.embedding_model.embedding(query)生成查询向量调用self.embeddings.search_index(...)EmbeddingHandler方法定义于 llmware/embeddings.py在向量库中检索返回的每个元素是[block数据, 距离]的二元组逐条过滤if blocks[1] embedding_distance_threshold才保留并写入distance、semantic: semantic、score: 0.0若提供custom_filter调用apply_custom_filter做键值全匹配的二次筛选交给内部方法_cursor_to_qr打包定位命中位置生成matches、补默认score/similarity/distance为零值、按query_result_return_keys抽取输出键、附加account_name/library_name并把本次查询登记进query_history由save_history控制默认开启。另外注意一个健壮性设计在通用的query()入口中若请求query_typesemantic但嵌入模型不可用会静默回退到文本查询llmware/retrieval.py而直接调用semantic_query则会抛错——示例直接调用semantic_query正是因为库上已确认构建了有效嵌入。六、结果如何解读每条结果是一个 dict。示例输出中你至少应关注text召回的文本块内容库的默认分块目标大小约为 400 字符见 llmware/library.py 中block_size_target_characters 400distance查询向量与该块嵌入向量的距离数值越小语义越接近查询 3 的embedding_distance_threshold1.0即以此为截断线file_source/page_num来源文件与页码内部字段名为master_index打包时统一映射为page_num见 llmware/retrieval.py是 RAG 答案溯源与引用标注的基础matches查询词在块内文本中的命中位置列表locate_query_match生成。七、由该示例延伸的 Query 能力文档主线是语义查询但同一个Query实例还支持若干实用变体可在 llmware/retrieval.py 中逐一查证text_query(query, exact_modeFalse, ...)基于倒排/文本匹配的检索支持精确匹配预处理text_query_with_document_filter/semantic_query_with_document_filter在结果集上叠加doc_ID或file_source文档级过滤text_query_with_custom_filter(query, filter_dict, ...)按任意合法键如content_type、page_num做字典过滤filter_dict中每个键值对等价于 AND 条件similar_blocks_embedding(block, embedding_distance_threshold10, ...)以某个已有块为锚点查找语义近邻块dual_pass_query(query, result_count20, primarytext, ...)同时执行文本与语义两路查询按_id交叉比对把两路都命中的块标记为matched并优先排在合并结果头部match_status标记matched/primary_only/secondary_only。源码中有一个显式的性能安全阀当result_count 100时会告警并自动钳制为 100n² 比对不擅长超长列表可通过safety_checkFalse关闭llmware/retrieval.py。对于 RAG 场景文本 语义双路召回再重排的dual_pass_query通常是比单路语义查询更稳健的生产选择可以作为示例之后的进阶练习。八、完整可运行示例以下代码整合了原文档的全部要素可直接保存为脚本运行首次运行需要网络下载样本文件与嵌入模型import os from llmware.library import Library from llmware.retrieval import Query from llmware.setup import Setup from llmware.configs import LLMWareConfig def create_fin_docs_sample_library(library_name): print(fupdate: creating library - {library_name}) library Library().create_new_library(library_name) sample_files_path Setup().load_sample_files(over_writeFalse) ingestion_folder_path os.path.join(sample_files_path, FinDocs) parsing_output library.add_files(ingestion_folder_path) print(update: building embeddings - may take a few minutes the first time) # 如已安装 Milvus 或其他向量库可替换 vector_db # 内存受限时调小 batch_size或换用 mini-lm-sbert 嵌入模型 library.install_new_embedding(embedding_model_nameindustry-bert-sec, vector_dbchromadb, batch_size200) return library def basic_semantic_retrieval_example(library): q Query(library) q.query_result_return_keys [distance, file_source, page_num, text] query_results1 q.semantic_query(ESG initiatives, result_count20) print(\nQuery 1 - ESG initiatives) for i, result in enumerate(query_results1): print(results - , i, result) query_results2 q.semantic_query(stock performance, result_count10) print(\nQuery 2 - stock performance) for i, result in enumerate(query_results2): print(results - , i, result) # embedding_distance_threshold1.0 会截断 distance 1.0 的结果 query_results3 q.semantic_query(cloud computing, result_count50, embedding_distance_threshold1.0) print(\nQuery 3 - cloud computing) for i, result in enumerate(query_results3): print(result - , i, result) return [query_results1, query_results2, query_results3] if __name__ __main__: print(Example - Running a Basic Semantic Query) LLMWareConfig().set_active_db(sqlite) lib create_fin_docs_sample_library(lib_semantic_query_1) my_results basic_semantic_retrieval_example(lib)九、关键参考文件文件内容docs/examples/retrieval.md本文所依据的官方示例文档solutions/sources/semantic_retrieval.py与文档一致的完整可运行脚本llmware/retrieval.pyQuery类语义/文本/混合检索的全部实现llmware/library.pyLibrary类建库、add_files、install_new_embeddingllmware/setup.pySetup.load_sample_filesFinDocs 等八类样本文件下载llmware/configs.pyLLMWareConfigset_active_db、向量库等配置llmware/embeddings.pyEmbeddingHandler向量库检索search_index封装适用前提提示示例默认使用chromadb向量库与sqlite文本库适合单机快速验证生产环境建议将vector_db替换为常驻的 Milvus 等向量数据库并依据内存情况调整batch_size。【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmware创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表