LLMWare FAQ 深度解读:分块大小、向量库、Collection 存储与模型配置的源码级实操指南
2026/9/14 14:12:30 网站建设 项目流程

LLMWare FAQ 深度解读:分块大小、向量库、Collection 存储与模型配置的源码级实操指南

【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmware

本文以 LLMWare 官方 FAQ 文档(docs/community/faq.md)为主线,系统回答六个高频使用问题:如何设置分块大小(chunk_size / max_chunk_size)、如何选择嵌入向量库(vector_db)、如何切换 Collection 存储(MongoDB / Postgres / SQLite)、如何通过 result_count 获取更多检索上下文、如何更换生成式 LLM 与嵌入模型,以及 Google Colab 下模型运行缓慢的解决方法。文中每一项参数说明均对照 llmware/library.py、llmware/configs.py、llmware/retrieval.py 等源码实现进行了佐证,帮助读者从"会用参数"进阶到"理解参数在底层如何生效"。

1. 如何设置分块大小(chunk_size 与 max_chunk_size)

核心问题:"我想把文档解析成更小的块"。

LLMWare 通过Library类的add_files方法暴露两个分块控制参数:

  • chunk_size:目标分块大小,默认 400
  • max_chunk_size:分块大小上限,默认 600

从源码结构看,这两个参数会原样传递给Parser类。在 library.py 中,add_files的方法签名为:

def add_files(self, input_folder_path=None, encoding="utf-8", chunk_size=400, get_images=True, get_tables=True, smart_chunking=1, max_chunk_size=600, table_grid=True, get_header_text=True, table_strategy=1, strip_header=False, verbose_level=2, copy_files_to_library=True, set_custom_logging=-1, use_logging_file=False):

方法内部随后在 library.py 构造Parser(library=self, chunk_size=chunk_size, max_chunk_size=max_chunk_size, ...)并调用ingest(...),也就是说分块行为完全由解析阶段决定,解析完成后还会调用CollectionWriter.build_text_index()重建文本索引。此外,add_files返回的output_results字典包含docs_addedblocks_added等计数,可用于验证不同 chunk_size 下产生的块数差异。

官方 FAQ 的完整示例——将同一批文件以不同分块大小分别加入同一个库:

from pathlib import Path from llmware.library import Library path_to_my_library_files = Path('~/llmware_data/sample_files/Agreements') my_library = Library().create_new_library(library_name='chunk_size_example') my_library.add_files(input_folder_path=path_to_my_library_files, chunk_size=400) my_library.add_files(input_folder_path=path_to_my_library_files, chunk_size=600)

需要注意:add_files默认执行重复检查(dupe_check=True),以不同 chunk_size 重复添加同一批文件时,实际入库行为受解析与去重逻辑影响,建议通过返回的docs_added/blocks_added计数确认每次添加的实际效果。

2. 如何设置嵌入向量库(vector_db)

核心问题:"我想使用某个特定的 embedding store"。

为某个库构建嵌入时,Libraryinstall_new_embedding方法通过vector_db参数指定向量存储。从源码看,该方法签名为(见 library.py):

def install_new_embedding(self, embedding_model_name=None, vector_db=None, from_hf=False, from_sentence_transformer=False, model=None, tokenizer=None, model_api_key=None, vector_db_api_key=None, batch_size=500, max_len=None, use_gpu=True):

其关键行为有三点:

  1. 不传vector_db时的回退逻辑:方法内部若vector_db为空,会读取全局默认值LLMWareConfig().get_config("vector_db")(见 library.py)。在 configs.py 中,默认配置为"vector_db": "milvus"
  2. 合法性校验:所选向量库必须出现在支持列表中,否则抛出LLMWareException(见 library.py)。
  3. 实际写入:加载模型后,通过EmbeddingHandler(self).create_new_embedding(vector_db, my_model, batch_size=batch_size)路由到对应向量库的资源层完成写入。

当前仓库支持的向量库清单定义在 configs.py:

_supported = {"vector_db": ["chromadb", "neo4j", "milvus", "pg_vector", "postgres", "redis", "pinecone", "faiss", "qdrant", "mongo_atlas", "lancedb"], ...}

源码中还有一条注释值得注意(configs.py):"postgres""pg_vector"是同一后端的两个别名。可用LLMWareConfig().get_supported_vector_db()动态查询,避免硬编码。

FAQ 的完整示例——对同一份数据构建三套嵌入并存入三种不同的向量库:

import logging from pathlib import Path from llmware.configs import LLMWareConfig from llmware.library import Library logging.info(f'Currently supported embedding stores: {LLMWareConfig().get_supported_vector_db()}') library = Library().create_new_library(library_name='embedding_store_example') library.add_files(input_folder_path=Path('~/llmware_data/sample_files/Agreements')) library.install_new_embedding(vector_db="pg_vector") library.install_new_embedding(vector_db="milvus") library.install_new_embedding(vector_db="faiss")

(原 FAQ 中参数名误写为input_foler_path,此处已按 library.py 的实际签名修正为input_folder_path。)

3. 如何设置 Collection 存储(set_active_db)

核心问题:"我想使用某个特定的 collection store"。

Collection 存储保存的是库的文本块集合(text collections),它与向量库相互独立。切换入口是LLMWareConfig类的set_active_db方法(见 configs.py):

@classmethod 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(message=f"LLMWareConfig - set_active_db - selected " f"db is not supported - {new_db}")

从源码结构看,当前支持的 Collection 存储为三种(configs.py):"mongo""postgres""sqlite";自 0.4.0 版本起,默认值为"sqlite"(见 configs.py 中"collection_db": "sqlite"及注释# change 0.4.0: default collection_db set to "sqlite")。查询当前值用get_active_db(),查询支持清单用get_supported_collection_db()

FAQ 的完整示例——打印当前值、打印支持清单、然后切换到 Postgres:

import logging from llmware.configs import LLMWareConfig logging.info(f'Currently active collection store: {LLMWareConfig.get_active_db()}') logging.info(f'Currently supported collection stores: {LLMWareConfig().get_supported_collection_db()}') LLMWareConfig.set_active_db("postgres") logging.info(f'Currently active collection store: {LLMWareConfig.get_active_db()}')

注意get_active_dbset_active_db都是类方法,通过类名直接调用(LLMWareConfig.get_active_db())或通过实例调用均可。

4. 如何检索到更多上下文(result_count)

核心问题:"我想从一次查询中检索到更多上下文"。

LLMWare 的Query类(llmware/retrieval.py)提供三个主查询方法:querytext_querysemantic_query,三者均接受result_count参数,默认值均为 20(见 retrieval.py 与 retrieval.py)。其中querytext_querysemantic_query的统一包装入口,依据query_type参数路由到具体实现(见 retrieval.py)。增大result_count即增大返回结果数量,从而扩大送入下游模型的上下文规模。

底层原理以 pgvector 为例最为直观:result_count最终会成为 SQL 语句中LIMIT关键字之后的取值。在 embeddings.py 的search_index方法中,语义检索的 SQL 模板为:

q = (f"SELECT id, block_mongo_id, embedding <-> %s AS distance, text " f"FROM {self.collection_name} ORDER BY distance LIMIT %s")

其中<->是 pgvector 的欧氏距离运算符。当result_count=10、集合名为agreements、查询向量为[1, 2, 3]时,展开后的等价 SQL 即 FAQ 中展示的样子:

SELECT id, block_mongo_id, embedding <-> '[1, 2, 3]' AS distance, text FROM agreements ORDER BY distance LIMIT 10;

FAQ 的完整示例——对同一库执行两次相同查询,仅将结果数从 3 调到 6:

import logging from pathlib import Path from llmware.configs import LLMWareConfig from llmware.library import Library from llmware.retrieval import Query logging.info(f'Currently supported embedding stores: {LLMWareConfig().get_supported_vector_db()}') library = Library().create_new_library(library_name='context_size_example') library.add_files(input_folder_path=Path('~/llmware_data/sample_files/Agreements')) library.install_new_embedding(vector_db="pg_vector") query = Query(library) query_results = query.semantic_query(query='salary', result_count=3, results_only=True) logging.info(f'Number of results: {len(query_results)}') query_results = query.semantic_query(query='salary', result_count=6, results_only=True) logging.info(f'Number of results: {len(query_results)}')

semantic_query还有一个可选的embedding_distance_threshold参数可用于按距离阈值过滤结果(见 retrieval.py),可与result_count配合使用,在扩大上下文的同时控制召回质量。

5. 如何更换大语言模型(gen_model)

核心问题:"我想使用不同的 LLM"。

入口是Prompt类的load_model方法,其gen_model参数指定模型名(见 prompts.py):

def load_model(self, gen_model, api_key=None, from_hf=False, trust_remote_code=False, ...): ... self.llm_model = self.model_catalog.load_model(gen_model, api_key=self.llm_model_api_key, ...)

从源码结构看,gen_model会被透传给ModelCatalog.load_model(models.py),由模型目录统一解析该模型来自本地还是 HuggingFace 等来源并完成加载。ModelCatalog还提供三个清单方法,便于在写代码前枚举可用模型:

  • list_generative_models():列出全部生成式模型(models.py);
  • list_generative_local_models():仅列出本地可运行的模型(models.py);
  • list_open_source_models():仅列出开源模型(models.py)。

FAQ 的完整示例——打印三类模型清单,并用 BLING 系列模型分别创建三个 prompter:

import logging from llmware.models import ModelCatalog from llmware.prompts import Prompt llm_gen = ModelCatalog().list_generative_models() logging.info(f'List of all LLMs: {llm_gen}') llm_gen_local = ModelCatalog().list_generative_local_models() logging.info(f'List of all local LLMs: {llm_gen_local}') llm_gen_open_source = ModelCatalog().list_open_source_models() logging.info(f'List of all open source LLMs: {llm_gen_open_source}') prompter_bling_1b = Prompt().load_model(gen_model='llmware/bling-1b-0.1') prompter_bling_tiny_llama = Prompt().load_model(gen_model='llmware/bling-tiny-llama-v0') prompter_bling_falcon_1b = Prompt().load_model(gen_model='llmware/bling-falcon-1b-0.1')

(原 FAQ 中日志语句误将变量写作llm_local,此处已统一为llm_gen_local。)

6. 如何更换嵌入模型(embedding_model_name)

核心问题:"我想使用不同的 embedding model"。

嵌入模型同样通过install_new_embeddingembedding_model_name参数指定(见 library.py)。源码中该方法对模型的加载分三条路径:

  • 传入embedding_model_name时,走ModelCatalog().load_model(selected_model=embedding_model_name, api_key=model_api_key)从模型目录查找并加载;
  • 传入已实例化的modelfrom_hf=True时,走ModelCatalog().load_hf_embedding_model(model, tokenizer),此时batch_size会被强制调整为 50(library.py);
  • 传入modelfrom_sentence_transformer=True时,必须同时提供embedding_model_name,否则抛出LLMWareException(library.py)。

可用嵌入模型清单通过ModelCatalog().list_embedding_models()获取(models.py)。FAQ 的示例意图是:列出全部嵌入模型,然后用mini-lm-sberindustry-bert-contracts两个模型对同一库各构建一次嵌入。按当前仓库 API 整理后的可运行版本如下:

import logging from pathlib import Path from llmware.models import ModelCatalog from llmware.library import Library # 原 FAQ 误用了 list_generative_models,正确方法为 list_embedding_models embedding_models = ModelCatalog().list_embedding_models() logging.info(f'List of embedding models: {embedding_models}') library = Library().create_new_library(library_name='embedding_models_example') library.add_files(input_folder_path=Path('~/llmware_data/sample_files/Agreements')) library.install_new_embedding(embedding_model_name='mini-lm-sber') library.install_new_embedding(embedding_model_name='industry-bert-contracts')

同一库可以用不同嵌入模型重复调用install_new_embedding,每套嵌入独立存储,便于后续对比不同模型的检索效果。

7. 为什么模型在 Google Colab 中运行缓慢

FAQ 给出的解释:LLMWare 的模型设计为至少需要 16GB 内存运行,而 Colab 默认仅提供约 13GB 内存,会显著拖慢计算速度。建议在 Colab 中启用 T4 GPU,以获得包括 16GB 内存在内的额外资源,使模型流畅运行。

启用 T4 GPU 的步骤:

  1. 在 Colab 笔记本中点击 "Runtime"(运行时)标签;
  2. 选择 "Change runtime type"(更改运行时类型);
  3. 在 "Hardware Accelerator"(硬件加速器)下选择 T4 GPU。

注意:免费使用 T4 存在每周用量上限。此外,结合上文第 5、6 节可知,load_modelinstall_new_embedding均默认use_gpu=True,因此在启用 GPU 后无需额外改动代码即可利用加速。

参考路径汇总

主题关键文件与方法
分块参数library.py:add_files
向量库选择library.py:install_new_embedding;configs.py:支持清单
Collection 存储configs.py:get_active_db/set_active_db/get_supported_collection_db
检索上下文retrieval.py:query/text_query/semantic_query;embeddings.py:pgvector SQL 模板
模型选择prompts.py:Prompt.load_model;models.py:ModelCatalog 清单方法
原始 FAQdocs/community/faq.md

以上各小节的参数默认值、支持清单与回退逻辑均以当前仓库源码为准;由于 LLMWare 持续迭代,若升级版本后行为有出入,建议以get_supported_vector_db()get_supported_collection_db()等运行时查询接口返回的结果为最终依据。

【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmware

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询