当前位置: 首页 > news >正文

Spring AI 2.0:RAG

一、简介

知识库。

二、代码

pom.xml

<!-- pdf解析 --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-pdf-document-reader</artifactId></dependency>

application.yml

spring:servlet:multipart:max-file-size:10MBmax-request-size:20MB

util

@ComponentpublicclassRagDocumentLoader{@AutowiredprivateVectorStorevectorStore;privatefinalTokenTextSplittertextSplitter=newTokenTextSplitter(800,150,5,10000);/** * 上传文件入库:支持 txt / pdf */publicvoidloadMultipartFile(MultipartFilefile)throwsIOException{Resourceresource=newByteArrayResource(file.getBytes());Stringfilename=file.getOriginalFilename();List<Document>documentList;if(filename!=null&&filename.endsWith(".pdf")){//PDF读取PagePdfDocumentReaderpdfReader=newPagePdfDocumentReader(resource);documentList=pdfReader.get();}else{//默认当作txt文本TextReadertextReader=newTextReader(resource);documentList=textReader.get();}//分片List<Document>splitDocs=textSplitter.apply(documentList);//写入向量库vectorStore.add(splitDocs);}publicvoidloadTxt(Resourceresource){List<Document>docs=newTextReader(resource).get();List<Document>splitDocs=textSplitter.apply(docs);vectorStore.add(splitDocs);}publicvoidloadText(Stringcontent){Documentdoc=newDocument(content);vectorStore.add(textSplitter.apply(List.of(doc)));}}

Configuration

/** * 内存向量库 SimpleVectorStore * 注意:重启丢失,仅用于开发测试;生产替换为Milvus等 * 依赖注入EmbeddingModel,使用阿里云百炼的Embedding */@BeanpublicVectorStoresimpleVectorStore(EmbeddingModelembeddingModel){returnSimpleVectorStore.builder(embeddingModel).build();}/** * RAG 问答Advisor,自定义prompt模板 */@BeanpublicQuestionAnswerAdvisorquestionAnswerAdvisor(VectorStorevectorStore){StringragSystemPrompt=""" 你是知识库助手,严格依据【参考资料】回答用户问题。 参考资料没有的信息,直接回复不知道,禁止编造。 【参考资料】 {question_answer_context} """;SearchRequestsearchRequest=SearchRequest.builder().topK(1).similarityThreshold(0.6).build();returnnewQuestionAnswerAdvisor(vectorStore,searchRequest,ragSystemPrompt);}@BeanpublicChatClientchatClient(ChatClient.Builderbuilder,QuestionAnswerAdvisorquestionAnswerAdvisor,ChatMemorychatMemory){// spring‑ai‑alibaba 环境,默认使用的是DashScopeChatModel(阿里云百炼聊天模型)returnbuilder.builder().defaultAdvisors(questionAnswerAdvisor).build();}

Controller

也可以删掉 ChatClient 里面的.defaultAdvisors(questionAnswerAdvisor),在接口处手动添加 advisor:

@AutowiredprivateRagDocumentLoaderragDocumentLoader;/** * 文件上传,解析并存入向量库 * postman测试:POST form‑data key=file,选择txt或者pdf文件 */@PostMapping("/upload")publicResponseEntity<String>uploadFile(@RequestParam("file")MultipartFilefile){if(file.isEmpty()){returnResponseEntity.badRequest().body("文件不能为空");}try{ragDocumentLoader.loadMultipartFile(file);returnResponseEntity.ok("上传成功,已加载到向量库");}catch(Exceptione){e.printStackTrace();returnResponseEntity.internalServerError().body("解析失败:"+e.getMessage());}}@GetMapping("/chat")publicStringchat(@RequestParamStringsid,@RequestParamStringquestion){returnchatClient.prompt().user(question).advisors(a->a.param(ChatMemory.CONVERSATION_ID,sid).add(questionAnswerAdvisor)//仅本次请求启用RAG).call().content();}
http://www.jsqmd.com/news/1402403/

相关文章:

  • 2026年8月广东C型钢铁材料/钢铁材料厂家推荐案例_佛山市团铸钢铁有限公司 - 行业平台推荐
  • [封装科普] 芯片先进封装解析:SiP 架构、PoP 焊接工艺与后段封装核心技术
  • NuGet存储路径深度解析:从原理到实践,优化.NET开发环境与CI/CD构建
  • 前端网络请求封装:架构设计与性能优化实践
  • 小龙虾烹饪全攻略:从选虾处理到麻辣蒜蓉风味实战
  • Vibe Coding 构建百万文档 RAG:冷热分层后 API 响应仍暴增 2000ms——我的三层索引止血术
  • Hermes Agent 解决的核心问题是什么?
  • 260815周H热泵项目
  • 从零到一搭建智能客服系统(LangGraph + FastAPI + 智谱AI 实战)
  • 2026年上海旧房翻新翻新:刷新墙面三档报价,价差来自基层处理深度 - 优家闲谈
  • 四足机器人技术栈解析:从硬件到AI的工程化落地与商业思考
  • 书架排列问题(区间查询)
  • OpenClaw Agent Send:命令行驱动的多平台消息自动化投递工具实战指南
  • Linux上安装FFmpeg
  • 宇树科技IPO启示:从技术期权到机器人商业化的硬科技创业逻辑
  • PostgreSQL笔记1:AI时代的数据底座——从趋势到实践的全面解读
  • 从信息熵到KL散度:深入理解Transformer损失函数的核心数学原理
  • 2026年8月全自动闪测仪/‌精密五金闪测仪厂家优选推荐_东莞市质伟捷达机械设备有限公司 - 品牌宣传支持者
  • 低压直流电机驱动优选|LTK118 单通道 H 桥驱动芯片,玩具 / 电动牙刷 / 电子锁全能适配
  • 银行流水模拟系统开发指南与实现方案
  • DeepSeek Harness 为什么敢说“一切皆插件“?拆透 Cordis 引擎的五大核心机制
  • 账房先生的数据库算盘:ArkTS 为鸿蒙记账本设计流水表与分类字典
  • Mac系统卡顿排查:搜狗输入法导致UI响应延迟的深度分析与解决方案
  • Go语言钉钉机器人插件ddingtalk实战:从入门到生产级告警系统构建
  • 2026年8月安徽非转基因菜籽油/安徽农家菜籽油优质厂家推荐_宁国市沙埠粮油加工厂 - 行业平台推荐
  • 检测机构查询小程序众多,哪家才是你的最优之选?
  • php内核源码解析=类型系统——PHP的类型到底怎么运作的
  • OpenAI 客户端取消传播连环炸:MCP Server 超时后我的重试逻辑为何雪崩
  • 企业级应用CLI化:从ChatDev看命令行工具在自动化工作流中的核心价值
  • 卢湾可靠的水利直缝管/Q355B-Z15钢板卷管有哪些 - 行业推荐官[官方】--