尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

llmware Fast Start 六例实战:从零构建企业级 RAG 流水线的完整入门路径

llmware Fast Start 六例实战:从零构建企业级 RAG 流水线的完整入门路径 llmware Fast Start 六例实战从零构建企业级 RAG 流水线的完整入门路径【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmwarellmwareLLMWare是一个面向企业级 RAGRetrieval Augmented Generation检索增强生成流水线的统一框架强调用小型专用开源模型在本地完成解析、嵌入、检索与推理。官方文档 Fast Start 将其设计为一组 6 个自包含、可复制即跑copy-paste-run的示例按“核心组件 → RAG 场景”两条主线展开。本文以该文档为骨架结合仓库中solutions/rag/目录下的示例源码与llmware/包的核心实现带你完整走完这 6 个示例读完后你将能够独立创建知识库 Library、安装向量嵌入、用 Model Catalog 加载本地模型执行推理并实现文本检索 RAG、语义检索 RAG 与多步复合检索 RAG 三种典型工作流。一、Fast Start 是什么6 个示例的编排逻辑Fast Start 是一套结构化的入门教程对应 6 个自包含示例官方为每个示例配套了视频讲解。示例分为两个 SectionSection I — 学习核心组件Library知识库解析parse、文本分块text chunk、索引index把一堆文件变成 AI-ready 知识库Embeddings嵌入对 Library 应用嵌入模型存储向量开启自然语言查询Prompts提示与 Model Catalog模型目录开始执行推理、构建提示。Section II — 把知识与提示连接起来3 个 RAG 场景RAG with Text Query用文本查询把文档集成进提示RAG with Semantic Query用自然语言查询检索文档并集成进提示RAG with more complex retrieval更复杂的检索模式文档级筛选 多步推理 事实核查。每个示例都按复制即跑标准设计代码内嵌大量注释示例之间可自由跳转任意顺序执行。当前仓库中这些示例位于 solutions/rag/ 目录其 README 显示 Fast Start 已扩展为 9 个示例新增 Function Calls、Agents、Web Services 三节本文聚焦原始 6 例主线。完成 6 例后可进一步探索仓库中 100 其他示例solutions/ 各子目录与 tutorials/getting_started/ 教程脚本。二、环境要求与安装2.1 平台与硬件要求官方文档给出的适用前提如下操作系统Mac M1/M2/M3、Windows、Linux推荐 Ubuntu 20 或 Ubuntu 22内存16 GB 起步Python3.9、3.10、3.11、3.12版本文档发布时2024 年 5 月中旬推荐llmware0.2.14。需要注意仓库中的示例代码已经过更新以使用新版特性示例注释中均有标注与当前仓库配套的实际运行版本更高——从 llmware/configs.py 的源码注释可确认llmware v0.4.02025 年 3 月起默认集合数据库已改为sqlite与 Fast Start 的零安装理念一致。2.2 安装方式# 方式一pip 安装 pip3 install llmware # 方式二克隆仓库本地运行 git clone gitgithub.com:llmware-ai/llmware.gitllmware包完全包含在llmware/目录内含平台相关的预编译共享库 llmware/lib/克隆后可直接作为本地模块使用。仓库提供了初始化脚本 welcome_to_llmware.shMac/Linux与 welcome_to_llmware_windows.shWindows用于安装 llmware/requirements.txt 依赖、若干常用可选依赖并复制入门示例到根目录。2.3 关键依赖包说明Fast Start 各示例对依赖的要求不同这是初学者最容易踩坑的地方依赖用途对应示例llmware本体Library、Parser、Query、Prompt 等核心框架全部 6 例chromadb或faiss/pymilvus/lancedb免安装向量库 SDK示例 2、5torchtransformers运行 HuggingFace Sentence-Transformer 嵌入模型如mini-lm-sbert示例 2、5openai可选替换为 OpenAI 云端模型如text-embedding-ada-002、gpt-4按需文档特别说明使用 Python 3.12 以下版本时可改用faiss示例视频中使用即 faiss替代 chromadb根据安装 llmware 的方式不同可能需要单独执行pip install chromadb。而 GGUF 格式的量化模型目录中标记为GGUFGenerativeModel类别、名称含gguf或tool的模型无需任何额外依赖即可本地推理这是 Fast Start 示例的默认选择——所有示例均优化为使用本地 CPU 模型主要是 BLING 与 DRAGON 系列。三、底层存储选型三类数据库如何配置Fast Start 文档明确了三层存储策略解析器被优化为直接把文本块写入持久化数据源示例中全部采用零安装方案所有处理在本地笔记本完成Local Private数据不出本机。3.1 集合数据库Collection DBFast Start 使用sqlite——嵌入式数据库无需安装更大规模部署推荐mongo或postgres安装方式见仓库中的 docker-compose 文件scripts/docker/docker-compose.yaml、scripts/docker/docker-compose_mongo_milvus.yaml、scripts/docker/docker-compose-pgvector.yaml。3.2 向量数据库Vector DBFast Start 使用chromadb的持久化file模式同样零安装官方支持多种免安装向量库只需 pip 安装对应 SDKpip3 install chromadb、pip3 install pymilvusMilvus LiteMac/Linux、pip3 install faiss、pip3 install lancedb面向规模化部署支持 Milvus、PGVectorPostgres、Redis、Qdrant、Neo4j、Mongo-Atlas、Chroma、LanceDB、Pinecone 等向量库各库的安装示例位于 solutions/embeddings/如 using_pg_vector.py、using_milvus_lite.py、using_qdrant.py 等并配套 scripts/docker/ 下的各向量库 docker-compose 脚本docker-compose-neo4j.yaml、docker-compose-qdrant.yaml、docker-compose-redis-stack.yaml。3.3 源码视角配置如何实现上述选库动作全部通过LLMWareConfig全局配置类完成。从源码看支持的库清单定义在 llmware/configs.py_supported {vector_db: [chromadb, neo4j, milvus, pg_vector, postgres, redis, pinecone, faiss, qdrant, mongo_atlas, lancedb], collection_db: [mongo, postgres, sqlite], table_db: [postgres, sqlite]} # change 0.4.0: default collection_db set to sqlite _conf {collection_db: sqlite, vector_db: milvus, table_db: sqlite, debug_mode: 0, ...}set_active_db与set_vector_db会对入参做白名单校验不支持的库名会抛出LLMWareException见 llmware/configs.py。同时该配置类定义了 llmware 的工作目录结构数据统一落在~/llmware_data/下含accounts/Library 主目录、model_repo/、input_channel/、parser_history/、query_history/、prompt_history/、tmp/等子目录见 llmware/configs.py——后文示例中prompt 状态保存位置即由LLMWareConfig.get_prompt_path()指向prompt_history。四、示例 1Library——把文件堆变成知识库示例 1 演示完整的入库流程创建 Library → 下载官方样例文件 →add_files自动解析/分块/索引 → 文本查询验证。完整代码见 example-1-create_first_library.py。from llmware.library import Library from llmware.retrieval import Query from llmware.setup import Setup from llmware.configs import LLMWareConfig import os # 可选 - 设置活动集合数据库默认已是 sqlitellmware0.4.0 # 刚入门且未安装独立数据库时请选 sqlite LLMWareConfig().set_active_db(sqlite) # 调试视图0 - 默认显示状态管理器大批量解析任务有用2 - 显示正在解析的文件名 LLMWareConfig().set_config(debug_mode, 2) # Step 1 - 创建 Libraryllmware 中组织知识库的核心构造 library Library().create_new_library(example1_library) # Step 2 - 通过 Setup() 拉取官方样例文件来自公开 S3 桶 llmware-sample-docs # -- 若需刷新样例文件设置 over_writeTrue sample_files_path Setup().load_sample_files(over_writeFalse) ingestion_folder_path os.path.join(sample_files_path, Agreements) # 约 15 份合同文档 # Step 3 - 核心入库方法自动按扩展名路由到正确解析器解析 文本分块 索引 parsing_output library.add_files(ingestion_folder_path) # Step 4 - 查看 Library Card文档数/块数等元数据 updated_library_card library.get_library_card() # Step 5 - 文本查询验证。Agreements 库的hello world查询是 base salary query_results Query(library).text_query(base salary, result_count10) for i, result in enumerate(query_results): text result[text] file_source result[file_source] page_number result[page_num] doc_id result[doc_ID] block_id result[block_ID] matches result[matches] print(query results: , i, result)几个值得注意的细节样例文件共 6 个文件夹Agreements约 15 份合同、Invoices40 份发票、UN-Resolutions-500500 份 PDF、SmallLibrary约 10 份 pdf/office 混合、FinDocs约 15 份财报、AgreementsLarge约 80 份合同——见 example-1 源码注释add_files自动路由支持的扩展名包括.pdf, .pptx, .docx, .xlsx, .csv, .md, .txt, .json, .wav, .zip, .jpg, .png查询结果每条都是带丰富元数据键的字典text、file_source、page_num、doc_ID、block_ID、matches等建议花些时间浏览全部键Library 主目录含提取出的图片位于/images路径可通过library.library_main_path获取。从源码看Library.add_files 的默认参数为chunk_size400, max_chunk_size600, smart_chunking1, get_imagesTrue, get_tablesTrue, get_header_textTrue等这些参数直接决定了分块粒度对后续检索质量影响显著——llmware/parsers.py 中的Parser类即以此为默认配置执行解析流水线。Setup().load_sample_files()的实现位于 llmware/setup.py从公开 S3 桶下载并缓存样例文档。五、示例 2Embeddings——安装嵌入模型开启语义查询示例 2 在示例 1 的 Library 基础上安装向量嵌入完整代码见 example-2-build_embeddings.py。基本配方为 5 步创建 Library → 选择嵌入模型 → 选择向量库 → 安装嵌入 → 跑语义测试查询。from llmware.library import Library from llmware.retrieval import Query from llmware.setup import Setup from llmware.resources import Status from llmware.models import ModelCatalog from llmware.configs import LLMWareConfig, MilvusConfig # Fast Start 配置免安装嵌入式 sqlite 集合库 LLMWareConfig().set_active_db(sqlite) # 免安装向量库选 milvus | chromadb | lancedb | faiss 之一 LLMWareConfig().set_vector_db(chromadb) # 创建并填充样例库自包含版本 library Library().create_new_library(example2_library) sample_files_path Setup().load_sample_files(over_writeFalse) library.add_files(input_folder_pathos.path.join(sample_files_path, Agreements), chunk_size400, max_chunk_size600, smart_chunking1) # 发现目录中所有嵌入模型 embedding_models ModelCatalog().list_embedding_models() # 选用一个流行且快速的 sentence transformer需 pip3 install transformers torch embedding_model mini-lm-sbert # *** 创建嵌入的关键一行代码 *** vector_db LLMWareConfig().get_vector_db() library.install_new_embedding(embedding_model_nameembedding_model, vector_dbvector_db, batch_size100) # 将嵌入用于 Query跑一条语义/向量查询 query_results Query(library).semantic_query(incentive compensation, result_count20) for i, entries in enumerate(query_results): text entries[text] document_source entries[file_source] page_num entries[page_num] vector_distance entries[distance] print(i, document_source, page_num, vector_distance, text[:125])要点install_new_embedding是该库嵌入的唯一入口参数含embedding_model_name、vector_db、batch_size源码默认 500示例中按场景取 100/200等实现位于 llmware/library.py底层按所选向量库分派到 llmware/embeddings.py 中对应的EmbeddingIndexHandler子类Chroma、Milvus、Lance、FAISS、PGVector、Redis、Neo4j、MongoAtlas、Pinecone 各有实现嵌入过程中可轮询Status().get_embedding_status(library_name, model)获取实时进度——EmbeddingHandler与 Parsers 在处理期间都会向Status()写入状态见 llmware/resources.py安装完成后可用library.get_embedding_status()复核嵌入记录若想换成 OpenAItext-embedding-ada-002无需 torch/transformers改为pip3 install openai并设置os.environ[USER_MANAGED_OPENAI_API_KEY]——这就是文档所说的API Key 通过环境变量传入的模式。六、示例 3Prompts 与 Model Catalog——加载模型并执行推理示例 3 建立发现 → 加载 → 提示三段式通用配方完整代码见 example-3-prompts_and_models.py。llmware 对所有模型采用统一的加载形式学会这一配方即可加载目录中几乎任何模型。from llmware.prompts import Prompt from llmware.models import ModelCatalog # Step 1 - 发现模型 llm_models ModelCatalog().list_generative_models() # 全部生成模型 llm_local_models ModelCatalog().list_generative_local_models() # 仅本地模型 llm_open_source_models ModelCatalog().list_open_source_models() # 仅开源模型 for i, models in enumerate(llm_local_models): print(models: , i, models[model_name], models[model_family]) # Step 2 - 选模型。示例默认选 GGUF 模型无需额外依赖 pytorch_generative_models [llmware/bling-1b-0.1, llmware/bling-tiny-llama-v0, llmware/bling-falcon-1b-0.1] # 约 1B 参数CPU 可跑 gguf_generative_models [bling-answer-tool, bling-phi-3-gguf, llmware/dragon-yi-6b-gguf] # 1B~6B 参数量化 model_name gguf_generative_models[0] # Step 3 - 加载模型并跑hello world问答 prompter Prompt().load_model(model_name) output prompter.prompt_main(entries[query], contextentries[context], prompt_namedefault_with_context, temperature0.30) print(output[llm_response].strip(\n)) # 模型输出 print(output[usage]) # 使用统计tokens 等要点依赖差异GGUF 模型无额外依赖PyTorch 模型需pip3 install torch与pip3 install transformersOpenAI 模型需pip3 install openai并设置USER_MANAGED_OPENAI_API_KEY环境变量model_name gpt-4prompt_main返回含llm_response与usage两个键的字典llmware 的 BLING/DRAGON 等小模型被训练为仅基于给定上下文作答若不传 context passage 而提问可能得到Not Found.回复——这是模型特性而非错误模型发现与加载的实现在 llmware/models.py 的ModelCataloglist_generative_models、list_embedding_models、load_model、model_lookup等模型卡片以 JSON 注册表管理支持注册 Ollama、Open Chat、OpenVINO、Foundry 等多种外部模型来源。七、示例 4RAG with Text Query——两种入库问答路径示例 4 演示最基础 RAG 配方文本查询 LLM 提示的两种实现完整代码见 example-4-rag-text-query.py两者目标输出相同路径 4ALibrary Prompt最通用、最具扩展性的方案——对每份合同文档用带文档过滤的文本查询检索相关文本块打包为 source 后交给 LLMfrom llmware.prompts import Prompt, HumanInTheLoop from llmware.setup import Setup from llmware.retrieval import Query from llmware.library import Library from llmware.configs import LLMWareConfig LLMWareConfig().set_active_db(sqlite) sample_files_path Setup().load_sample_files() contracts_lib Library().create_new_library(example4_library) contracts_lib.add_files(os.path.join(sample_files_path, Agreements)) question_list [{topic: base salary, llm_query: What is the executives base salary?}, {topic: governing law, llm_query: What is the governing law?}] q Query(contracts_lib) doc_list q.list_doc_id() # 库内全部唯一文档 fn_list q.list_doc_fn() prompter Prompt().load_model(bling-phi-3-gguf) for i, doc_id in enumerate(doc_list): for question in question_list: doc_filter {doc_ID: [doc_id]} # 精确模式的文档级过滤文本查询 query_results q.text_query_with_document_filter(question[topic], doc_filter, result_count5, exact_modeTrue) source prompter.add_source_query_results(query_results) # *** 上下文自动打包进 source 的 LLM 调用 *** responses prompter.prompt_with_source(question[llm_query], prompt_namedefault_with_context, temperature0.3) for response in responses: print(response[llm_response]) prompter.clear_source_materials() # 换文档前清空 source # 持久化审计保存 JSONL 交互历史 导出人工复核 CSV prompter.save_state() csv_output HumanInTheLoop(prompter).export_current_interaction_to_csv()路径 4BPrompt 内联 Source无需 Library——prompter.add_source_document(contracts_path, contract, queryquery_topic)对单个文档执行内联解析、分块与查询过滤直接把结果打包进 prompt。适合随手拿起一份文档就提问的轻量场景。从源码看add_source_query_results、prompt_with_source、clear_source_materials、save_state与HumanInTheLoop.export_current_interaction_to_csv均实现在 llmware/prompts.pysource 打包会按 context window 切分大样本见 llmware/util.py 中SourcePackager的package_source/chunk_large_sampleprompt_with_source在 source 过大时会自动拆分多次调用 LLM。save_state将完整交互历史以 JSONL 写入prompt_history目录CSV 报告则包含模型、回答、提示词与证据便于人工复核human-in-the-loop。八、示例 5RAG with Semantic Query——最主流的 RAG 检索模式示例 5 演示最常见的 RAG 模式以自然语言语义查询检索相关文本块作为上下文向 LLM 提问完整代码见 example-5-rag-semantic-query.py。工作流四步建库并装嵌入 → 全库语义查询 → 按文档挑选最优结果 → 循环打包上下文并提问。# Step 1-3 - 建库 解析 索引 library Library().create_new_library(example_5_library) sample_files_path Setup().load_sample_files(over_writeFalse) contracts_path os.path.join(sample_files_path, Agreements) # 注释提示检索成功率对分块策略敏感替换自己的文档时请留意 library.add_files(input_folder_pathcontracts_path, chunk_size400, max_chunk_size800, smart_chunking2) # Step 4 - 安装嵌入chromadb 向量库 jina-ai 的嵌入模型 library.install_new_embedding(embedding_model_namejina-small-en-v2, vector_dbchromadb, batch_size200) # RAG 核心加载 LLM 后对全库发语义查询 prompter Prompt().load_model(bling-phi-3-gguf, temperature0.0, sampleFalse) query what is the executives base annual salary # 关键步骤embedding_distance_threshold 过滤距离过远的噪声块 results Query(library).semantic_query(query, result_count80, embedding_distance_threshold1.0) # 按文档分组逐份合同打包上下文提问 for contract in os.listdir(contracts_path): qr [entries for entries in results if entries[file_source].split(os.sep)[-1] contract] source prompter.add_source_query_results(query_resultsqr) response prompter.prompt_with_source(query, prompt_namedefault_with_context) for resp in response: if llm_response in resp: print(resp[llm_response]) prompter.clear_source_materials()要点与示例 2 相同的环境准备LLMWareConfig().set_active_db(sqlite)、LLMWareConfig().set_vector_db(chromadb)嵌入模型此处选jina-small-en-v2jina-ai 的开源嵌入模型semantic_query支持result_count、embedding_distance_threshold距离阈值过滤低相关块、custom_filter等参数实现位于 llmware/retrieval.py 的Query.semantic_queryprompt_with_source返回的是响应字典列表——取决于 source 上下文大小同一次调用可能触发多次 LLM 调用每个字典条目代表一次 LLM 调用。九、示例 6RAG 进阶——文档筛选、条款分析与事实核查示例 6 在示例 4/5 之上叠加多层能力演示对更大文档集合约 80 份合同的AgreementsLarge的复合 RAG 工作流完整代码见 example-6-rag-multi-step-query.py。目标只分析Master Service AgreementsMSA并核查 LLM 回答。from llmware.setup import Setup from llmware.library import Library from llmware.prompts import Prompt, HumanInTheLoop from llmware.retrieval import Query from llmware.configs import LLMWareConfig LLMWareConfig().set_active_db(sqlite) llm bling-phi-3-gguf # DRAGON 系列 RAG 微调问答模型可换 dragon-yi-answer-tool # Step 1 - 建库全部约 80 份合同 local_path Setup().load_sample_files() msa_lib Library().create_new_library(example6_library) msa_lib.add_files(os.path.join(local_path, AgreementsLarge)) # Step 2 - 首轮过滤master services agreement 总出现在第 1 页 # 用按页文本搜索精准筛出 MSA 文档 q Query(msa_lib) results q.text_search_by_page(master services agreement, page_num1, results_onlyFalse) msa_docs results[file_source] msa_doc_ids results[doc_ID] prompter Prompt().load_model(llm) # Step 3 - 逐份 MSA检索终止条款 → 打包 source → 提问 → 事实核查 for i, doc_id in enumerate(msa_doc_ids): doc_filter {doc_ID: [doc_id]} termination_provisions q.text_query_with_document_filter(termination, doc_filter) sources prompter.add_source_query_results(termination_provisions) response prompter.prompt_with_source(What is the notice for termination for convenience?) # Step 4 - 后处理事实核查与来源核查 stats prompter.evidence_comparison_stats(response) # 回答与证据的 token 比较统计 ev_source prompter.evidence_check_sources(response) # 逐 source 证据核查 for j, resp in enumerate(response): print(resp) print(stats[j][comparison_stats]) print(ev_source[j][source_review]) prompter.clear_source_materials() # Step 5 - 输出JSONL 交互历史 人工复核 CSV prompter.save_state() csv_output HumanInTheLoop(prompter).export_current_interaction_to_csv()这个示例体现了 RAG 工程化的三个关键手法利用文档布局特征做初筛text_search_by_page(query, page_num1, results_onlyFalse)只搜索指定页码且返回含query、results、doc_ID、file_source四键的字典实现见 llmware/retrieval.py 的Query.text_search_by_page文档级过滤检索text_query_with_document_filter保证只从目标文档中取块避免跨文档串扰事实核查闭环evidence_comparison_statstoken 级比较统计与evidence_check_sources证据来源核查均为 llmware/prompts.py 中Prompt类的方法HumanInTheLoop类进一步提供review、fact_checker_numbers、source_reviewer、token_comparison及 CSV 导入导出能力形成生成 → 核查 → 人工复核的闭环。文档同时建议此例使用更强的 GGUF 量化 DRAGON 模型6~7B 参数级别以在本地获得更可靠的 RAG 回答。十、小结与后续路径通过这 6 个自包含示例Fast Start 覆盖了企业级 RAG 流水线的完整闭环Library解析/分块/索引→ Embeddings向量存储/语义检索→ Model Catalog Prompt本地小模型推理→ 文本 RAG → 语义 RAG → 多步复合 RAG筛选 事实核查 审计输出。所有环节均可在本地笔记本零安装运行sqlite chromadb/file 模式 GGUF 量化模型并可通过 llmware/configs.py 中的set_active_db/set_vector_db平滑升级到 Mongo/Postgres 集合库与 Milvus、PGVector、Redis、Qdrant、Neo4j、Mongo-Atlas、Chroma、LanceDB、Pinecone 等规模化向量库。掌握本文的 6 例之后建议沿以下路径继续深入当前仓库solutions/rag/example-7-function-calls.py、example-8-agents.py、example-9-function-calls-with-web-services.py从问答提示走向 Function Calls 与 Agent 编排solutions/embeddings/ 与 solutions/rag/README.md各向量库/嵌入模型的具体安装与配置docs/getting_started/ 中其余入门文档platforms.md、installation.md以及 tutorials/getting_started/ 中的configure_db.py、loading_sample_files.py、working_with_libraries.py等配套教程脚本核心源码 llmware/library.py、llmware/parsers.py、llmware/retrieval.py、llmware/prompts.py、llmware/models.py当你的业务需要定制解析、分块、检索或提示逻辑时这些模块就是扩展点所在。【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmware创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表