LLMWare 端到端用例实战:七个基于本地小模型的 RAG 与 Agent 场景全解
发布时间:2026/9/14 8:26:05来源:尧图网络
LLMWare 端到端用例实战七个基于本地小模型的 RAG 与 Agent 场景全解【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmwareLLMWarellmware是一个用于构建企业级 RAG检索增强生成流水线的统一框架其核心理念是用一批小而专的本地模型Small, but Mighty完成原本依赖大型云端模型的复杂任务。本文围绕 Use Cases 文档 中列出的七类端到端场景展开逐一拆解每个场景的目标、关键代码与底层实现帮助读者掌握从文档解析、检索、提示到人工复核的完整落地路径。所有示例代码均位于 solutions/use_cases/ 目录可直接运行。用例集的总体设计Use Cases 文档 将这组示例定位为高层框架起点high-level framework starting point每个示例都是一个组合了多个 LLMWare 组件的复杂配方complex recipe覆盖特定业务目标。它们的共性设计是全部使用本地开源小模型如 slim-extract-tool、slim-summary-tool、bling 系列RAG 微调的量化小模型、dragon 系列GGUF 量化中模型部分场景可纯 CPU 在笔记本上运行统一的解析 → 检索 → 提示 → 证据核对 → 落盘复核骨架Parser/Library负责解析与切块Query负责检索Prompt或LLMfx负责推理evidence_check_*系列方法做事实核对save_state()与HumanInTheLoop导出 CSV/JSON 供人工审查样本数据零配置获取所有示例通过 Setup 类从不受限的 AWS S3 公共桶自动下载样本文件发票、合同、语音、投资者资料等首次运行自动拉取并缓存到本地工作区。从 Setup 源码 可以看到其缓存机制load_sample_files(over_writeFalse)会先检查sample_files目录是否存在存在则直接复用仅在over_writeTrue时重新从 S3 桶拉取 zip 并解压。三个下载入口分别是方法用途落盘目录Setup().load_sample_files()文档类样本发票、合同等llmware_path/sample_filesSetup().load_voice_sample_files(small_only...)语音样本wavllmware_path/voice_sample_files(_small)Setup().load_selected_sample_files(sample_folder...)指定文件夹样本如microsoft_irllmware_path/sample_folder以下按文档顺序逐一深入七个用例。用例一研究自动化——Agent 与 Web Services 联动web_services_slim_fx.py 演示了文档中描述的30 键研究报告场景以一篇 NIKE 财报新闻稿为输入用本地模型 两个 Web 服务产出一份包含约 30 个键值对的统一研究分析。用到的模型均在 模型目录 中注册通过ModelCatalog加载slim-extract-tool——结构化抽取slim-summary-tool——摘要bling-stablelm-3b-tool——RAG 问答。用到的 Web 服务YFinance实时股票信息与WikiParserWikipedia 公司背景实现分别在 web_services.py 与 parsers.py。完整流程分四步# Step 1: 从源文本抽取 7 个关键字段 model ModelCatalog().load_model(slim-extract-tool, temperature0.0, sampleFalse) extract_keys [stock ticker, company name, total revenues, restructuring charges, digital growth, ceo comment, quarter end date] for keys in extract_keys: response model.function_call(text, params[keys]) ... # Step 2: 用抽取出的股票代码查 YFinance yf YFinance().get_stock_summary(tickerticker_core) # 现价、52周高低、PE、成交量 yf2 YFinance().get_financial_summary(tickerticker_core) # 市值、营收增长、EBITDA... yf3 YFinance().get_company_summary(tickerticker_core) # 行业、员工数、高管薪酬...# Step 3: 用抽取出的公司名查 Wikipedia再对 Wikipedia 内容做摘要/抽取/问答 output WikiParser().add_wiki_topic(company_name, target_results1) company_overview .join([b[text] for b in output[blocks][:3]]) summary model2.function_call(company_overview, params[company history (5)]) # 摘要 response model.function_call(company_overview, params[founding date]) # 抽取 response model3.inference(What is an overview of companys business?, # 问答 add_contextcompany_overview)这个示例的关键设计是抽取结果作为二次检索的输入第一步从新闻稿中抽出的stock_ticker和company_name分别驱动 YFinance 和 Wikipedia 两个外部数据源外部数据源返回的内容又反过来被模型提示、抽取和总结最终汇总为一份统一研究字典。从 YFinance 源码 可以看到几个实现细节类内部维护了stock_summary_keys、financial_summary_keys、company_summary_keys等字段白名单get_stock_summary/get_financial_summary/get_company_summary三个方法分别按白名单从 Yahoo Finance API 返回值中筛选字段保证下游拿到的是稳定的精简结构构造时会检查yfinance依赖未安装则抛出LLMWareException提示pip3 install yfinance——这也是该示例的运行前提示例文件顶部同样有util.find_spec(yfinance)的运行时检查示例中有一处实用处理ticker.split(:)[-1]因为抽取模型可能返回NYSE:NKE这类带交易所前缀的 ticker需要截取交易所代码之后的部分再调用 API。用例二批量发票处理invoice_processing.py 演示解析 带源提示parsing prompts_with_sources的组合特点是不需要数据库、不需要 embedding且默认run_on_cpuTrue可在笔记本上运行。sample_files_path Setup().load_sample_files(over_writeFalse) invoices_path os.path.join(sample_files_path, Invoices) query_list [What is the total amount of the invoice?, What is the invoice number?, What are the names of the two parties?] model_name bling-phi-3-gguf # CPU 场景GGUF 量化的小模型 prompter Prompt().load_model(model_name) for invoice in os.listdir(invoices_path): for question in query_list: source prompter.add_source_document(invoices_path, invoice) # 在内存中解析并挂为 source output prompter.prompt_with_source(question, prompt_namedefault_with_context) prompter.clear_source_materials()核心调用链是add_source_document对发票做内存解析与切块挂到 Prompt 上→prompt_with_source将 source 自动打包进提示并执行 LLM→clear_source_materials清空进入下一份文档。发票支持 PDF/DOCX/PPTX/XLSX/CSV/TXT 格式也可以直接替换为自己的发票目录。模型选择上源码注释给出了取舍bling-1b-0.1是最小最快但错误率更高bling-phi-3-ggufGGUF 量化在本地 CPU 上更准确若run_on_cpuFalse则通过ModelCatalog().setup_custom_llmware_inference_server(server_uri_string, secret_key...)挂接本地 GPU 推理服务器model_name改为llmware-inference-server。结果落盘采用文档所述的双通道策略prompter.save_state() # JSONL 全量交易历史存于 prompt_history 目录 csv_output HumanInTheLoop(prompter).export_current_interaction_to_csv() # CSV 供 Excel 人工复核save_state()将完整的提示状态模型、提示词、响应、证据保存到LLMWareConfig.get_prompt_path()下的prompt_id目录HumanInTheLoop则把当前交互导出为含模型、响应、提示与证据列的 CSV这是 LLMWare 人工在环复核的标准模式后续 MSA 与合同分析用例同样复用。用例三语音转写分析与引用提取parsing_great_speeches.py 对应文档中50 世纪伟大演讲 wav 文件的转写、检索与要点提取场景最终产出带源文件、时间戳和原文的文献索引bibliography。voice_sample_files Setup().load_voice_sample_files(small_onlyFalse) input_folder os.path.join(voice_sample_files, greatest_speeches) # Step 1: 转写 解析 切块约 56 个 WAV 文件全部在内存中完成 parser_output Parser(chunk_size400, max_chunk_size600).parse_voice( input_folder, write_to_dbFalse, copy_to_libraryFalse, remove_segment_markersTrue, chunk_by_segmentTrue, real_time_progressFalse) # Step 3: 对转写文本块做快速文本搜索 results Utilities().fast_search_dicts(president, parser_output) # Step 4: LLM 审查每个命中块识别具体美国总统并保留时间戳坐标 extract_model ModelCatalog().load_model(slim-extract-tool, sampleFalse, temperature0.0, max_output200) response extract_model.function_call(res[text], params[president name])该流程的技术要点parse_voice配合chunk_by_segmentTrue按转写分段切块chunk_size400/max_chunk_size600控制块大小write_to_dbFalse表示全程在内存处理不落库检索用的是Utilities().fast_search_dicts——对内存中的块列表做快速文本搜索无需数据库命中块由slim-extract-tool抽取president_name再用白名单kennedy、carter、nixon、reagan、clinton、obama做二次过滤每个结果保留coords_x/coords_y等坐标元数据在语音场景中即时间戳最终列表形如{key: president, source: file_source, time_start: ..., text: ...}实现可定位到秒级原文的引用输出。语音样本包含四个文件夹famous_quotes、greatest_speeches、youtube_demos、earnings_callssmall_onlyFalse时下载完整集。仓库中还附有 Whisper.cpp 转写文档 与 语音转写学习指南可深入了解转写模型的配置。用例四MSA 合同批量处理与事实核对msa_processing.py 是七个用例中组件最全的一个从约 80 份合同的大批次中筛出主服务协议MSA定位终止条款让 LLM 作答并对 LLM 的回答做证据核对。local_path Setup().load_sample_files() agreements_path os.path.join(local_path, AgreementsLarge) # 建库并解析全部合同 msa_lib Library().create_new_library(msa_lib503_635) msa_lib.add_files(agreements_path) # 关键过滤只在第 1 页搜索 master services agreement q Query(msa_lib) results q.text_search_by_page(master services agreement, page_num1, results_onlyFalse) msa_docs results[file_source] # 返回 dict: {query, results, doc_ID, file_source} # 本地量化 6B 模型 prompter Prompt().load_model(llmware/dragon-yi-6b-gguf) for docs in msa_docs: doc_filter {file_source: [docs]} termination_provisions q.text_query_with_document_filter(termination, doc_filter) prompter.add_source_query_results(termination_provisions) response prompter.prompt_with_source(What is the notice for termination for convenience?) # 事实核对fact-check与来源核对source-check stats prompter.evidence_comparison_stats(response) # 响应与证据的词级重合统计 ev_source prompter.evidence_check_sources(response) # 逐条审查证据来源 prompter.clear_source_materials()这段代码展示了 LLMWare 检索层两个高频 APItext_search_by_page(query, page_num1)——按页过滤的文本搜索。MSA 识别正是依赖首页标题包含 Master Service Agreement这一业务规则results_onlyFalse返回含file_source的完整结果字典便于只取文件清单text_query_with_document_filter(keyword, {file_source: [docs]})——按文档过滤的查询把检索范围锁定在单份合同内找 termination 相关块。回答后的evidence_comparison_stats与evidence_check_sources是文档所述fact-check and source-check的落地前者量化 LLM 响应与所附证据的重合程度后者输出逐条证据的审查结果两者都打印在循环中并随save_state()与HumanInTheLoopCSV 一起落盘。该示例与 Fast Start 教程的示例 6 保持同步源码注释明确说明 tracks the example #6 in the Fast Start。用例五自然语言查询 CSVText2SQLagent_with_custom_tables.py 演示把customer_table.csv样本见 solutions/sources/customer_table.csv装入 Postgres然后用LLMfxAgent 执行自然语言查询。源码注释指出它是旧示例text2sql-end-to-end-2.py的泛化升级改用整合进 LLMfx 流程的CustomTable类且支持 Postgres 与 SQLite。第一步建表只需执行一次custom_table CustomTable(dbdb, table_nametable_name) analysis custom_table.validate_csv(load_fp, load_file) # 预校验 CSV output custom_table.load_csv(load_fp, load_file) # 或 load_json updated_schema custom_table.test_and_remediate_schema(samples20, auto_remediateTrue) custom_table.insert_rows() # 写入数据库test_and_remediate_schema(samples20, auto_remediateTrue)值得注意它用更多样本压力测试 schema 的数据类型并自动修复注释明确用更多样本可提高准确性。第二步Agent 自然语言查询agent LLMfx() agent.load_tool(sql, sampleFalse, get_logitsTrue, temperature0.0) query_list [Which customers have vip customer status of yes?, What is the highest annual spend of any customer?, Which customer has account number 1234953, Which customer has the lowest annual spend?, Is Susan Soinsin a vip customer?] for query in query_list: response agent.query_custom_table(query, dbdb, tabletable_name)从源码注释看query_custom_table内部完成了文档所述的全部链路查表 schema → 把 schema 与查询打包成 text2sql 提示 → 用 sql 工具执行推理生成 SQL → 在数据库上执行该 SQL → 将查询结果作为research输出结果最终汇聚在agent.research_list。这里的slim-sql-tool即通过load_tool(sql)加载的专用小模型。用例六笔记本上的合同分析contract_analysis_on_laptop_with_bling_models.py 演示完全在笔记本上、使用 RAG 微调的小模型bling-phi-3-gguf分析一批高管雇佣协议query_list {executive employment agreement: What are the name of the two parties?, base salary: What is the executives base salary?, vacation: How many vacation days will the executive receive?} prompter Prompt().load_model(bling-phi-3-gguf, temperature0.0, sampleFalse) for contract in os.listdir(contracts_path): for key, value in query_list.items(): # 解析 切块 按主题关键字过滤一步完成 source prompter.add_source_document(contracts_path, contract, querykey) responses prompter.prompt_with_source(value, prompt_namedefault_with_context) prompter.clear_source_materials() prompter.save_state() HumanInTheLoop(prompter).export_current_interaction_to_csv()该用例的检索策略如文档所述简单但有效add_source_document传入querykey参数后LLMWare 在解析的同时用关键字base salary、vacation 等过滤相关文本块再把命中的块自动打包进default_with_context提示模板。temperature0.0, sampleFalse保证输出确定性。最后同样以save_state() CSV 导出收尾形成模型、响应、提示、证据齐全的人工复核材料。用例七Office 文档的深度解析Slicing and Dicingslicing_and_dicing_office_docs.py 演示 ZIP 打包的 Office 格式约 150 个 PowerPoint/Word/Excel 文件的 Microsoft IR 投资者资料包的各种高级解析技巧microsoft_ir Setup().load_selected_sample_files(sample_foldermicrosoft_ir) my_lib Library().create_new_library(library_name) # ZIP 归档直接传入 add_files 即可——自动解压并按文件类型路由到对应解析器 parsing_output my_lib.add_files(microsoft_ir, chunk_size400, max_chunk_size600, smart_chunking1, get_tablesTrue, get_imagesTrue)建库之后的切片五步与文档描述一一对应步骤代码说明1. 表格导出 CSVQuery(lib).export_all_tables(output_fplib.output_path)导出建库时索引的所有表格2. 图片 OCRlib.run_ocr_on_images(add_to_libraryTrue, chunk_size400, min_size10, realtime_progressTrue)OCR 文本回写进库3. 全库导出lib.export_library_to_jsonl_file(lib.output_path, microsoft_ir_lib)整个库落盘为 JSONL4. 数据集构建Datasets(librarylib, testing_split0.10, validation_split0.10, ds_id_moderandom_number)ds.build_text_ds(min_tokens100, max_tokens500)生成按 token 数约束的模型就绪数据集5. 图片定位my_lib.image_path查看抽取出的 PNG/JPEG 存放路径注意两点前置条件其一示例开头用LLMWareConfig().set_active_db(sqlite)指定集合数据库可选 mongo/sqlite/postgres其二OCR 步骤依赖两个外部组件需先安装pip3 install pytesseract以及 Tesseract 引擎本体sudo apt install libtesseract-dev等见文件头部注释。建库参数中get_tablesTrue, get_imagesTrue会让解析器同步抽取表格与内嵌图片并索引这是后续导出与 OCR 的前提smart_chunking1则启用更智能的切块策略。运行前提与公共基础设施结合七个用例的源码可以归纳出统一的运行前提与 安装文档 和 快速上手 对应环境安装 llmware 后首次调用Setup().load_sample_files()会自动创建工作区并从公共 S3 桶拉取样本文件需要网络模型所有用例使用 模型目录 注册的本地模型slim 系列、bling-gguf 系列、dragon-yi-6b-gguf 等首次加载自动从 Hugging Face 下载并缓存CPU 场景优先选 gguf 量化版本数据库MSA、Office 解析、Text2SQL 用例需要集合/表数据库mongo/sqlite/postgres通过LLMWareConfig().set_active_db(...)切换发票与笔记本合同分析则完全不需要数据库可选依赖用例一需要yfinance用例七的 OCR 步骤需要pytesseract Tesseract复核落盘prompter.save_state()与HumanInTheLoop(prompter).export_current_interaction_to_csv()是每个提示类用例的标准收尾保证所有推理可追溯、可人工审查。以上七个用例覆盖了 Use Cases 文档 列出的全部场景solutions/use_cases/ 目录下还有业务机器人biz_bot.py等补充示例且仓库定期更新这些示例。【免费下载链接】llmwareUnified framework for building enterprise RAG pipelines with small, specialized models项目地址: https://gitcode.com/GitHub_Trending/ll/llmware创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网