Spring AI 系列(三):RAG 開發(fā)必知——兩種 Advisor 到底怎么選?附完整代碼實現(xiàn)
Spring AI 系列三RAG 開發(fā)必知——兩種 Advisor 到底怎么選附完整代碼實現(xiàn)Spring AI 提供了對常見 RAG 流程的開箱支持通過 Advisor API 實現(xiàn)向量數(shù)據(jù)庫存儲著AI模型所不知道的數(shù)據(jù)當用戶提問時Advisor 會向向量數(shù)據(jù)庫查詢與用戶問題相關(guān)的文檔將檢索結(jié)果附加到用戶文本中然后通過 AI 大模型推理生成最終回答。在 RAG 流程中有兩種 AdvisorQuestionAnswerAdvisor 和 RetrievalAugmentationAdvisor。QuestionAnswerAdvisor當用戶提出問題時QuestionAnswerAdvisor 會幫助系統(tǒng)從已有的知識庫或數(shù)據(jù)庫中檢索答案并將其返回給用戶其核心目的是將用戶的問題與知識庫中的答案進行匹配提供答案。QuestionAnswerAdvisor 側(cè)重問答處理通過理解和分析用戶的問題找到最合適的答案。RetrievalAugmentationAdvisor當需要從大型數(shù)據(jù)庫或知識庫中檢索信息時RetrievalAugmentationAdvisor 會在檢索請求前后插入增強邏輯。例如在查詢過程中RetrievalAugmentationAdvisor 可以自動加入額外的上下文信息如用戶的歷史查詢、偏好、領(lǐng)域知識等以提高檢索結(jié)果的相關(guān)性和準確性。RetrievalAugmentationAdvisor 側(cè)重信息檢索通過增強檢索條件和上下文信息來優(yōu)化查詢過程。備注Advisor顧問是 Spring AI 中用于增強方法執(zhí)行邏輯的組件類似于一個攔截器通過 Advisor可以在方法執(zhí)行前后插入自定義邏輯從而提升代碼的可擴展性與靈活性常用于任務(wù)增強、數(shù)據(jù)預(yù)處理等場景。使用以上兩種Advisor時需要在項目maven pom.xml導入如下依賴!-- QuestionAnswerAdvisor 依賴包--dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-advisors-vector-store/artifactId/dependency!-- RetrievalAugmentationAdvisor 依賴包--dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-rag/artifactId/dependency下面通過SpringBoot程序演示兩種Advisor的使用方式該案例中我們將固定的文檔片段存入到Milvus向量庫然后通過chatClient 輸入問題分別使用兩種Advisor進行檢索向量庫進行回答。1. 創(chuàng)建SpringBoot項目SpringBoot項目命名為SpringAIRAGWithAdvisor設(shè)置使用的JDK為17版本。2. 在項目中加入如下Maven依賴?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion3.5.3/versionrelativePath/!-- lookup parent from repository --/parentgroupIdcom.example/groupIdartifactIdSpringAIRAGWithAdvisor/artifactIdversion0.0.1-SNAPSHOT/versionnameSpringAIRAGWithAdvisor/namedescriptionSpringAIRAGWithAdvisor/descriptionpropertiesjava.version17/java.version/properties!-- 導入 Spring AI BOM用于統(tǒng)一管理 Spring AI 依賴的版本 引用每個 Spring AI 模塊時不用再寫 version只要依賴什么模塊 Mavens 自動使用 BOM 推薦的版本 --dependencyManagementdependenciesdependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-bom/artifactIdversion1.0.0-SNAPSHOT/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Deepseek AI 依賴 --dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-deepseek/artifactId/dependency!-- 智普AI 依賴 --dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-zhipuai/artifactId/dependency!-- QuestionAnswerAdvisor 依賴包--dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-advisors-vector-store/artifactId/dependency!-- RetrievalAugmentationAdviso 依賴包--dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-rag/artifactId/dependency!-- Milvus VectorStore 依賴包--dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-vector-store-milvus/artifactId/dependency/dependencies!-- 聲明倉庫 用于獲取 Spring AI 以及相關(guān)預(yù)發(fā)布版本--repositoriesrepositoryidspring-snapshots/idnameSpring Snapshots/nameurlhttps://repo.spring.io/snapshot/urlreleasesenabledfalse/enabled/releases/repositoryrepositorynameCentral Portal Snapshots/nameidcentral-portal-snapshots/idurlhttps://central.sonatype.com/repository/maven-snapshots//urlreleasesenabledfalse/enabled/releasessnapshotsenabledtrue/enabled/snapshots/repository/repositories/project注意在該 pom.xml 中引入了spring-ai-starter-model-zhipuai依賴包用于文檔片段轉(zhuǎn)換成向量存入向量庫在該 pom.xml 中引入了spring-ai-starter-model-deepseek依賴包用于 chatClient 聊天。在該 pom.xml 中引入了spring-ai-advisors-vector-store和spring-ai-rag依賴包兩個依賴包分別為 QuestionAnswerAdvisor 和 RetrievalAugmentationAdvisor 依賴。在該 pom.xml 中引入了spring-ai-starter-vector-store-milvus依賴包該依賴為 Milvus VectorStore 依賴包。3. 配置resources/application.propertiesspring.application.nameSpringAIRAGWithAdvisor server.port8080 ## 使用 智普AI Embedding 模型需要在pom.xml中引入對應(yīng)依賴 spring.ai.zhipuai.api-keyd...4 spring.ai.zhipuai.base-urlhttps://open.bigmodel.cn/api/paas spring.ai.zhipuai.embedding.options.modelembedding-2 ## 配置 Chat Model:Deepseek的基礎(chǔ)URL、密鑰和使用模型 spring.ai.deepseek.base-urlhttps://api.deepseek.com spring.ai.deepseek.api-keysk-8...1 spring.ai.deepseek.chat.options.modeldeepseek-chat ## Milvus 配置 spring.ai.vectorstore.milvus.client.hostnode2 spring.ai.vectorstore.milvus.client.port19530 # 默認用戶名和密碼為 root 和 Milvus spring.ai.vectorstore.milvus.client.tokenroot:Milvus # 要使用的 Milvus 數(shù)據(jù)庫的名稱 spring.ai.vectorstore.milvus.database-namedefault # 用于存儲 vector 的 Milvus 集合名稱 spring.ai.vectorstore.milvus.collection-namevector_store #是否自動初始化 schema如vector_store如果沒有會自動創(chuàng)建 spring.ai.vectorstore.milvus.initialize-schematrue # Milvus 集合中要存儲的 vector 的維度默認為1536要與所使用的 embedding 模型的維度匹配如DeepSeek、ZhiPuAI 或其他都是1024維 spring.ai.vectorstore.milvus.embedding-dimension10244. 構(gòu)建兩個Rag Advisor和Chat Client在項目中創(chuàng)建config/AIConfig.java 該類標記為Configuration類。類中注入QuestionAnswerAdvisor、RetrievalAugmentationAdvisor以及ChatClient并且每次運行SpringBoot項目時向Milvus中插入指定文檔向量數(shù)據(jù)如果已存在則不重復(fù)插入。packagecom.example.springairagwithadvisor.config;importio.milvus.client.MilvusServiceClient;importio.milvus.grpc.GetCollectionStatisticsResponse;importio.milvus.param.R;importio.milvus.param.collection.FlushParam;importio.milvus.param.collection.GetCollectionStatisticsParam;importio.milvus.response.GetCollStatResponseWrapper;importjakarta.annotation.PostConstruct;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;importorg.springframework.ai.deepseek.DeepSeekChatModel;importorg.springframework.ai.document.Document;importorg.springframework.ai.rag.advisor.RetrievalAugmentationAdvisor;importorg.springframework.ai.rag.generation.augmentation.ContextualQueryAugmenter;importorg.springframework.ai.rag.retrieval.search.VectorStoreDocumentRetriever;importorg.springframework.ai.vectorstore.SearchRequest;importorg.springframework.ai.vectorstore.VectorStore;importorg.springframework.ai.vectorstore.milvus.MilvusVectorStore;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjava.util.List;ConfigurationpublicclassAIConfig{// 注入 MilvusVectorStore 實例AutowiredprivateMilvusVectorStorevectorStore;// 從配置文件中讀取 Milvus 集合名稱Value(${spring.ai.vectorstore.milvus.collection-name})privateStringcollectionName;//配置 QuestionAnswerAdvisor用于問答任務(wù)BeanpublicQuestionAnswerAdvisorquestionAnswerAdvisor(){returnQuestionAnswerAdvisor.builder(vectorStore)// 配置向量搜索的參數(shù)這里設(shè)置了相似度閾值為 0.5返回前 6 個結(jié)果.searchRequest(SearchRequest.builder().similarityThreshold(0.5d).topK(6).build()).build();}//配置 RetrievalAugmentationAdvisor用于增強檢索任務(wù)BeanpublicRetrievalAugmentationAdvisorretrievalAugmentationAdvisor(){//VectorStoreDocumentRetriever 負責在向量數(shù)據(jù)庫中根據(jù)查詢獲取最相關(guān)的文檔//支持根據(jù)相似度閾值、top-K返回前K個最相關(guān)文檔和過濾表達式等方式進行精確檢索VectorStoreDocumentRetrieverretrieverVectorStoreDocumentRetriever.builder().vectorStore(vectorStore)// 設(shè)置向量存儲對象.similarityThreshold(0.5)//設(shè)置相似度閾值.topK(6)//設(shè)置返回前K個最相關(guān)文檔.build();//ContextualQueryAugmenter 用于增強查詢根據(jù)上下文信息生成更具體的查詢//支持基于上下文的查詢增強例如根據(jù)用戶輸入的上下文信息生成更具體的查詢提高檢索的準確性和效率ContextualQueryAugmentercqaContextualQueryAugmenter.builder().allowEmptyContext(true)//允許空上下文.build();//返回 RetrievalAugmentationAdvisor 對象用于增強檢索任務(wù)returnRetrievalAugmentationAdvisor.builder().documentRetriever(retriever)// 設(shè)置文檔檢索器.queryAugmenter(cqa)// 設(shè)置查詢增強器.build();}//配置 ChatClient初始化聊天客戶端BeanpublicChatClientchatClient(DeepSeekChatModelchatModel){returnChatClient.builder(chatModel).defaultSystem(你是一個助手回答用戶問題是不要提及回復(fù)是從上下文信息中獲取的不要回答你不知道的問題如果你不知道答案就回答抱歉我不清楚這個問題。).build();}/** * PostConstruct 注解的方法會在 Spring 容器完成依賴注入后自動調(diào)用一次常用于執(zhí)行初始化邏輯。 */PostConstructpublicvoidinitVectorData(){System.out.println(初始化向量數(shù)據(jù)寫入到 Milvus 數(shù)據(jù)庫中...);// 獲取 Milvus 客戶端實例MilvusServiceClientclient(MilvusServiceClient)vectorStore.getNativeClient().get();// 獲取集合統(tǒng)計信息查詢集合的記錄數(shù)量RGetCollectionStatisticsResponserespclient.getCollectionStatistics(GetCollectionStatisticsParam.newBuilder().withCollectionName(collectionName).build());// 獲取實體數(shù)量即數(shù)據(jù)行數(shù)longrowCountnewGetCollStatResponseWrapper(resp.getData()).getRowCount();System.out.println(Milvus vector_store 中數(shù)據(jù)數(shù)量rowCount);//如果集合沒有數(shù)據(jù)就寫入if(rowCount0){System.out.println(Milvus vector_store 中沒有數(shù)據(jù)寫入...);ListDocumentdocsList.of(newDocument(Spring AI 是一個開源 AI 集成項目),newDocument(Milvus 是一款高性能向量數(shù)據(jù)庫),newDocument(DeepSeek 是一個開源大語言模型));//vectorStore.add(docs) 調(diào)用時Spring AI 的 MilvusVectorStore 會使用注入的 EmbeddingModel 將每個 Document 中的文本內(nèi)容轉(zhuǎn)換成向量并寫入vectorStore.add(docs);// 獲取 Milvus 客戶端并手動調(diào)用 flush刷新索引確保數(shù)據(jù)被持久化到 Milvus 數(shù)據(jù)庫中System.out.println(Milvus vector_store 刷新索引...);client.flush(FlushParam.newBuilder().withCollectionNames(List.of(collectionName))// 設(shè)置刷新操作的集合名稱.build());}}}5. 創(chuàng)建RagController.javapackagecom.example.springairagwithadvisor.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;importorg.springframework.ai.rag.advisor.RetrievalAugmentationAdvisor;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;RestControllerRequestMapping(/ai)publicclassRagController{AutowiredprivateChatClientchatClient;AutowiredprivateQuestionAnswerAdvisorqaAdvisor;AutowiredprivateRetrievalAugmentationAdvisorragAdvisor;GetMapping(/chat1)publicStringask1(RequestParamStringmessage){returnchatClient.prompt().user(message)//設(shè)置使用 QuestionAnswerAdvisor.advisors(List.of(qaAdvisor)).call().content();}GetMapping(/chat2)publicStringask2(RequestParamStringmessage){returnchatClient.prompt().user(message)//設(shè)置使用 RetrievalAugmentationAdvisor.advisors(List.of(ragAdvisor)).call().content();}}6. 啟動Milvus在linux node2 節(jié)點啟動Milvus#進入 milvus目錄cd/software/milvus#啟動 Milvusdockercompose up-d7. 啟動項目并測試啟動SpringAiRAGWithAdvisor項目運行主應(yīng)用類SpringAiragWithAdvisorApplication.java啟動該項目。在瀏覽器中輸入如下內(nèi)容進行測試# http://localhost:8080/ai/chat1?messageMilvus是什么 Milvus是一款高性能向量數(shù)據(jù)庫。 # http://localhost:8080/ai/chat1?message今天天氣如何 抱歉我不清楚這個問題。 # http://localhost:8080/ai/chat2?messageSpring AI是什么 Spring AI 是一個開源 AI 集成項目。 # http://localhost:8080/ai/chat2?message今天天氣如何 抱歉我不清楚這個問題。

相關(guān)新聞

技術(shù)博客內(nèi)容聚合平臺實踐:OpenClaw 如何采集公開優(yōu)質(zhì)內(nèi)容并生成每日技術(shù)內(nèi)參

技術(shù)博客內(nèi)容聚合平臺實踐:OpenClaw 如何采集公開優(yōu)質(zhì)內(nèi)容并生成每日技術(shù)內(nèi)參

一、引言在信息爆炸的時代,技術(shù)從業(yè)者每天需要面對海量的技術(shù)博客、官方文檔、行業(yè)資訊和開源項目動態(tài)。如果逐一打開各個博客站點、論壇和 Newsletter,不但耗時巨大,而且很難區(qū)分內(nèi)容質(zhì)量的高低,往往會陷入“每天閱讀上百篇文章&…

2026/8/2 6:15:00 閱讀更多
步進電機驅(qū)動實戰(zhàn):從微步細分到靜音控制,解決振動發(fā)熱與丟步難題

步進電機驅(qū)動實戰(zhàn):從微步細分到靜音控制,解決振動發(fā)熱與丟步難題

1. 項目概述:從“會轉(zhuǎn)”到“轉(zhuǎn)得準、轉(zhuǎn)得穩(wěn)”搞過機器人、3D打印機或者自動化設(shè)備的朋友,對步進電機肯定不陌生。它不像普通直流電機那樣,給電就轉(zhuǎn),停不停得準全看緣分。步進電機的魅力在于,它能“走一步,算…

2026/8/2 7:05:01 閱讀更多
母線槽采購避坑:不要只對比單價,重點核查這幾項硬性指標

母線槽采購避坑:不要只對比單價,重點核查這幾項硬性指標

不少機電采購、電氣設(shè)計師在母線槽招標比價階段,單純關(guān)注產(chǎn)品單價,忽略核心配置差異,低價產(chǎn)品往往通過縮減銅排厚度、簡化絕緣、取消鍍錫、降低外殼用料壓縮成本,投入使用后運維成本大幅上升,存在安全隱患。采購母線槽…

2026/8/2 7:05:01 閱讀更多
從星號梯形到循環(huán)控制:編程入門項目的深度解析與實踐

從星號梯形到循環(huán)控制:編程入門項目的深度解析與實踐

1. 從“畫星星”到理解循環(huán)控制:一個被低估的編程入門項目很多編程新手在接觸循環(huán)結(jié)構(gòu)時,都覺得“畫個星號梯形”這種題目太簡單、太“小兒科”了,無非就是幾個for循環(huán)嵌套,打印一堆*和空格。我剛開始學編程時也這么想&#xff0c…

2026/8/2 7:05:01 閱讀更多
照片視頻丟失不要急!北京德智康多媒體素材數(shù)據(jù)恢復(fù)

照片視頻丟失不要急!北京德智康多媒體素材數(shù)據(jù)恢復(fù)

照片視頻丟失不要急!北京德智康多媒體素材數(shù)據(jù)恢復(fù)攝影師、短視頻創(chuàng)作者、家庭用戶的硬盤、存儲卡里存放大量照片、原始視頻素材。格式化存儲卡、硬盤損壞、素材誤刪除,丟失的影像資料很難重新拍攝,損失難以估量。多媒體文件碎片多&#xff0…

2026/8/2 7:05:01 閱讀更多
系統(tǒng)科學大會投稿指南:從選題到錄用的全流程策略

系統(tǒng)科學大會投稿指南:從選題到錄用的全流程策略

1. 會議背景與核心價值解析第十屆中國系統(tǒng)科學大會的征文通知,對于圈內(nèi)人來說,絕不僅僅是一份簡單的會議通知。它更像是一張集結(jié)令,一個風向標,標志著國內(nèi)系統(tǒng)科學研究領(lǐng)域一年一度的頂級學術(shù)盛會即將拉開帷幕。我參加過幾屆&…

2026/8/2 6:55:01 閱讀更多
3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南 【免費下載鏈接】GetQzonehistory 獲取QQ空間發(fā)布的歷史說說 項目地址: https://gitcode.com/GitHub_Trending/ge/GetQzonehistory 你是否曾想過,那些年發(fā)過的QQ空間說說,那些記錄青春的文字…

2026/8/2 0:04:01 閱讀更多
3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南

3分鐘搞定!QQ空間歷史說說完整備份終極指南 【免費下載鏈接】GetQzonehistory 獲取QQ空間發(fā)布的歷史說說 項目地址: https://gitcode.com/GitHub_Trending/ge/GetQzonehistory 你是否曾想過,那些年發(fā)過的QQ空間說說,那些記錄青春的文字…

2026/8/2 0:04:01 閱讀更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O分配PCB板是應(yīng)用材料(Applied Materials)公司生產(chǎn)的一款用于半導體設(shè)備的I/O信號分配電路板。該型號(0100-02186)的核心特點如下:專用于Endura等半導體工藝腔室。集成信號路由與分配功能。連接控制…

2026/8/2 2:51:21 閱讀更多
Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機是日本日清(Nissei)品牌的一款工業(yè)用三相異步電機,適用于自動化設(shè)備及通用機械驅(qū)動。該型號(FFMN-32L-10-T0 40AX)的核心特點如下:三相交流異步電動機。額定…

2026/8/2 2:52:49 閱讀更多