概述
GitHub,官網,目前最新版是1.0.1。
功能:
- 跨AI提供商的可移植API:用于聊天、文本到圖像和嵌入模型。
- 支持同步和流API選項。還支持下拉訪問模型特定功能。
- 跨Vector Store提供商的可移植API,包括同樣可移植的新穎的類似SQL的元數據過濾器API。支持8個矢量數據庫
- 函數調用。Spring AI使AI模型可以輕松調用
java.util.Function
POJO對象 - AI模型和向量存儲的Spring Boot自動配置和啟動器
- 數據工程的ETL框架。這為將數據加載到矢量數據庫提供了基礎,有助于實現檢索增強生成模式。
如需使用SNAPSHOT版本,Maven配置添加以下倉庫:
<repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository><repository><id>central-portal-snapshots</id><name>Central Portal Snapshots</name><url>https://central.sonatype.com/repository/maven-snapshots/</url><releases><enabled>false</enabled></releases><snapshots><enabled>true</enabled></snapshots></repository>
</repositories>
Spring Initializr:https://start.spring.io/
application.yml
配置文件:
spring:ai:chat:memory:repository:jdbc:initialize-schema: nerveropenai:api-key: embedding:options:model: text-embedding-v4base-url: https://dashscope.aliyuncs.com/compatible-mode/chat:options:model: qwen-maxvectorstore:pgvector:enabled: trueindexType: HNSWredis:initialize-schema: trueindex-name: custom-indexprefix: custom-prefixzhipuai:api-key: ${ZHIPUAI_API_KEY}mcp:server:name: webflux-mcp-serverversion: 1.0.0type: ASYNC sse-message-endpoint: /mcp/messagesclient:request-timeout: 30ssse:connections:server1:url: https://mcp.amap.comsse-endpoint: /sse?key=?server2:url: https://mcp-pan/baidu.comsse-endpoint: /sse?access_token=?server3:url: https://mcp-youxuan.baidu.comsse-endpoint: /mcp/sse?key=?toolcallback:enabled: truestdio:servers-configuration: classpath:/mcp-servers-config.json
amap:key: ${AMAP_API_KEY}
代碼片段
PromptTemplate template = new PromptTemplate("請用{style}風格解釋:{topic}");
Prompt prompt = template.create(Map.of("style", "幽默", "topic", "量子力學"));@Bean
VectorStore vectorStore(EmbeddingClient embeddingClient) {return new SimpleVectorStore(embeddingClient);
}@Resource
private SyncMcpToolCallbackProvider toolCallbackProvider;var chatClient = chatClientBuilder.defaultTools(toolCallbackProvider).build();// 實現Tool
@Service
public class WeatherService {@Tool(description = "Get weather information by city name")public String getWeather(String cityName) {}
}
// 注冊Tool
@Bean
public ToolCallbackProvider weatherTools(WeatherService weatherService) {return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();}
Chat Client,用于簡化與AI模型的交互過程,支持同步和反應式編程模型,隱藏諸多底層細節:
- 提示詞管理:定制和組裝模型的輸入(Prompt)
- 響應處理:格式化解析模型的輸出(Structured Output)
- 參數選項:調整模型交互參數(ChatOptions)
- 高級功能:整合聊天記憶、函數調用、RAG等能力
Spring AI提供兩種方式創建ChatClient:使用自動配置的Builder或編程方式。
@RestController
public class ChatController {private final ChatClient chatClient;public ChatController(ChatClient.Builder builder) {this.chatClient = builder.build();}@GetMapping("/chat")public String chat(String input) {return this.chatClient.prompt().user(input).call().content();}
}
禁用自動配置:spring.ai.chat.client.enabled=false
// 通常通過自動裝配獲取ChatModel實例
ChatModel myChatModel =
// 使用Builder
ChatClient chatClient = ChatClient.builder(myChatModel).build();
// 直接create
ChatClient chatClient = ChatClient.create(myChatModel);
ChatClient的流暢API通過prompt
方法提供三種不同的方式來創建Prompt:
prompt()
:無參方法,允許從頭開始構建提示,后續可添加用戶消息、系統消息等。chatClient.prompt().user("你好").call().content();
prompt(Prompt prompt)
:接受Prompt
對象參數,允許傳入使用非流暢API創建的Prompt
實例。
Prompt myPrompt = new Prompt(List.of(new UserMessage("你好")));
chatClient.prompt(myPrompt).call().content();
prompt(String content)
:便捷方法,直接接受用戶文本內容作為參數。
chatClient.prompt("你好").call().content();
ChatResponse
包含完整的響應數據和元數據,如Token使用情況。
entity()
方法還提供一個重載版本,允許傳入自定義參數來指導實體轉換過程:
record Product(String name, String description, Double price) {}Product product = chatClient.prompt().user("創建一個價格在100元以內的產品").call().entity(Product.class, EntityPreference.create().withFormat(EntityFormat.JSON).build());
ChatClient提供兩個核心方法來獲取響應:
call
:用于同步響應,返回ResponseWithChatClient
對象;stream()
:用于流式響應,返回StreamWithChatClient`對象。
Flux<String> responseStream = chatClient.prompt().user("給我講一個長故事").stream().content();
默認值:
ChatClient chatClient = ChatClient.builder(chatModel).defaultSystem("你是一位專業的Java開發助手,擅長使用Spring框架").defaultUser("默認用戶消息").defaultOptions(options -> options.withTemperature(0.7f)).defaultResponseFormat(new StructuredResponseFormat<>(MyResponseType.class)).build();
ToolCallback
之前叫FunctionCallback,升級:
- 術語更準確:從"函數"改為"工具",更符合行業通用術語
- 架構更清晰:分離工具定義與實現,提高復用性
- 功能更強大:支持更靈活的工具注冊和調用方式
- 注解驅動:新增
@Tool
注解,開發更便捷
FunctionToolCallback.builder("getWeather", service).description("獲取天氣")
結構化輸出
如JSON格式優勢:
- 便于程序解析和處理
- 確保數據格式一致性
- 方便與前端或其他服務集成
StructuredOutputConverter
- 在LLM調用前:轉換器會向提示詞追加格式指令,為模型生成目標輸出結構提供明確指導。
- 在LLM調用后:轉換器將模型的原始文本輸出轉換為結構化類型,將其映射為對應的結構化JSON特定的數據結。
StructuredOutputConverter實現類型:接口允許您從基于文本的AI模型輸出中獲取結構化數據,默認BeanOutConverter實現類
public News generateAsString(String message) {News news = this.chatClient.prompt().user(promptUserSpec -> promptUserSpec.text(message)).call().entity(News.class);
}@Data
public class News {private String entity;private String time;private String summary;
}
RAG
添加依賴:
implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis:1.0.1'
private final VectorStore vectorStore;
public String similaritySearch(String query) {SearchRequest request = SearchRequest.builder().query(query).topK(1).build();List<Document> results = this.vectorStore.similaritySearch(request);return JSONObject.valueToString(results);
}
或其他向量數據庫。
模型
CogView-4:智譜開源文生圖模型,支持任意長度的中英雙語輸入,能夠生成在給定范圍內的任意分辨率圖像。
implementation ‘org.springframework.ai:spring-ai-starter-model-zhipuai:1.0.1’
private final ZhiPuAiImageModel zhiPuAiImageModel;public String getImage(String imageName) {ImageResponse response = zhiPuAiImageModel.call(new ImagePrompt(imageName, ZhiPuAiImageOptions.builder().build()));return response.getResult().getOutput().getUrl();
}
Chat Memory
ChatMemory接口,支持實現不同類型的內存策略,默認MessageWindowChatMemory類
ChatMemoryRepository:專責消息的存儲與檢索,底層消息存儲實現默認實現 InMemoryChatMemoryRepository 類
引入依賴:implementation 'org.springframework.ai:spring-ai-starter-model-chat-memory-repository-jdbc:1.0.1'
,JdbcChatMemoryRepository
配置:
spring.ai.chat.memory.repository.jdbc.initialize-schema=nerver
public ChatClientService(ChatClient.Builder builder,JdbcChatMemoryRepository chatMemoryRepository)
ChatMemory chatMemory = MessageWindowChatMemory.builder().chatMemoryRepository(chatMemoryRepository).maxMessages(10).build();
ChatClient chatClient = builider.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()).build();chatClient.prompt().user("你好").advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId)).call().content();
Advisors
用于攔截、修改和增強AI驅動的交互,封裝常見的生成式AI模式,轉換發送到和接收自LLMs的數據,在各種模型和用例之間提供可移植性。
優勢:
- 封裝常見模式:將RAG、內容安全檢查等模式封裝為可重用組件
- 數據轉換:在請求發送前和響應接收后修改和增強數據
- 跨模型可移植性:編寫一次Advisor,可用于多種AI模型和用例
- 可觀測性:Advisors參與可觀測性堆棧,支持指標和跟蹤功能
工作原理類似于AOP:
- 在AI交互的請求和響應階段攔截處理流程
- 可以訪問和修改請求內容和上下文
- 可以訪問和修改響應內容和上下文
- 多個Advisors可以組成處理鏈,按特定順序執行
API
- Advisor:基礎接口,定義名稱和順序等基本特性
- CallAdvisor:用于非流式場景的接口
- StreamAdvisor:用于流式場景的接口
- BaseAdvisor:同時繼承CallAdvisor和StreamAdvisor的接口
- BaseChatMemoryAdvisor:繼承BaseAdvisor的接口
- MessageChatMemoryAdvisor:將記憶作為消息集合添加到prompt
- PromptChatMemoryAdvisor:將記憶整合到prompt的系統文本中
- SafeGuardAdvisor:用于防止模型生成有害或不適當的內容
- ChatModelCallAdvisor:
- ChatModelStreamAdvisor:
- SimpleLoggerAdvisor:日志記錄
繼承關系圖
其他相關API:
- ChatClientRequest:請求
- ChatClientResponse:響應
- CallAdvisorChain:
- StreamAdvisorChain:
Advisors的執行順序由getOrder()
方法決定:
- 較低的order值優先執行
- Advisor鏈按照棧的方式工作:第一個加入鏈的Advisor最先處理請求;也是最后處理響應的Advisor
- 高優先級的Advisor先執行請求處理,后執行響應處理
- 如果多個Advisor具有相同的order值,它們的執行順序不保證
Advisors支持兩種處理模式:
- 非流式處理:處理完整的請求和響應,實現
CallAdvisor
接口,重寫adviseCall()
方法; - 流式處理:處理連續的請求和響應流,實現
StreamAdvisor
接口,重寫adviseStream()
方法,使用響應式編程概念(如Flux)。
示例:
// 創建帶有Advisors的ChatClient
var chatClient= ChatClient.builder(chatModel).defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build(), // 聊天記憶顧問QuestionAnswerAdvisor.builder(vectorStore).build() // RAG顧問).build();// 設置運行時參數
String response= chatClient.prompt().advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, "678")).user(userText).call().content();
Prompt Engineering
幾個參數:
-
Temperature:控制模型響應的隨機性或創造力
- 較低的值:
0.0-0.3
,更具確定性、更集中的響應。適用于事實類問題、分類或對一致性要求嚴格的任務; - 中等值:
0.4-0.7
,在確定性和創造力之間取得平衡。適用于一般用例; - 較高值:
0.8-1.0
,更具創造力、多樣化且可能帶來驚喜的響應。適用于創意寫作、頭腦風暴或生成多樣化選項。
- 較低的值:
-
MaxTokens:限制模型在其響應中可生成Token數量
- 較低值:適用于單個詞、短語或分類標簽。
- 中等值:適用于段落或簡短解釋。
- 較高值:適用于長篇內容、故事或復雜解釋。
-
采樣控制:兩個參數,允許對生成過程中的Token選擇進行細粒度控制。
- Top-K:將Token選擇限制在K個最有可能的下一個Token中。較高值(如40-50)會引入更多多樣性
- Top-P:核采樣,從累積概率超過P的最小Token集合中動態選擇。常見的值如 0.8-0.95。
Role Prompting
public void rolePrompting(ChatClient chatClient) {String result = chatClient.prompt().system(s -> s.text("你是一位經驗豐富的Java開發專家,專注于Spring框架。請以簡潔、專業的方式回答問題,并提供代碼示例。")).user(u -> u.text("如何在Spring Boot應用中實現基本的認證功能?")).call().content();
}
Self-Consistency通過生成多個獨立的推理路徑,然后選擇最一致的答案來提高復雜推理任務的準確性。
public void selfConsistencyPrompting(ChatClient chatClient) {// 生成多個推理路徑List<String> responses = newArrayList<>();for (int i = 0; i < 3; i++) {String response = chatClient.prompt().user(u -> u.text("""問題: 小明有5個蘋果,他給了小紅2個,又從小華那里得到3個,然后他又吃了1個。小明現在有多少個蘋果?讓我們一步步思考得出答案。""")).options(ChatOptions.builder().temperature(0.7).build()) // 使用較高溫度以獲得多樣化的推理路徑.call().content(); responses.add(response);}
}
解讀:上面的讓我們一步步思考得出答案
正體現Chain-of-Thought Prompting。
MCP
MCP能力:
- 標準化交互協議:統一AI模型與外部工具的通信方式
- 多傳輸支持:STDIO/HTTP/SSE全兼容,適應本地或云端部署
- 會話管理:v0.8.0全新升級的會話架構
MCP Java SDK采用清晰的三層設計,可輕松集成到現有系統:
- 客戶端/服務端層
McpClient
:搞定協議協商、工具調用McpServer
:暴露工具接口,管理資源URI- 支持同步/異步調用,兼容HTTP長連接和進程間通信
- 會話層:通過
McpSession
管理對話狀態,多輪交互不再丟上下文 - 傳輸層:JSON-RPC消息一鍵序列化,三種傳輸任選:
- STDIO:本地進程間通信
- HTTP SSE:Servlet/WebFlux雙版本支持
- Reactive流:WebFlux實現高并發
server模塊引入依賴:
implementation 'org.springframework.ai:spring-ai-starter-mcp-server-webflux:1.0.1'
implementation 'org.springframework.ai:spring-ai-starter-mcp-server:1.0.1'
implementation 'org.springframework.ai:spring-ai-starter-mcp-server-webmvc:1.0.1'
client引入依賴:
implementation 'org.springframework.ai:spring-ai-starter-mcp-client:1.0.1'
implementation 'org.springframework.ai:spring-ai-starter-mcp-client-webflux:1.0.1'
MCP Server
諸如:
- 高德MCP Server:提供全場景覆蓋的地圖服務,包括地理編碼、逆地理編碼、IP定位、天氣查詢、騎行路徑規劃、步行路徑規劃、駕車路徑規劃、公交路徑規劃、距離測量、關鍵詞搜索、周邊搜索、詳情搜索等。
- 百度網盤MCP:核心API現已全面兼容MCP協議。涵蓋用戶信息、獲取文件信息、文件上傳、文件管理、文件搜索等。 開發者僅需簡單配置,即可快速接入百度網盤服務,實現文件上傳、文件管理等能力,大幅降低開發者調用網盤服務門檻,顯著提升開發者的開發效率。
- 百度優選MCP:提供MCP工具列表包含8個核心API,涵蓋參數對比、品牌排行、商品檢索、交易等。為用戶提供全維度對比決策助手,實時品牌天梯榜單,輕松獲取全網相關SPU與優質低價商品鏈接等能力。
- Playwright MCP:微軟推出的現代化跨瀏覽器自動化測試工具,支持Chromium、Firefox和WebKit,提供高速、可靠的端到端測試能力,適用于Web應用開發和持續集成。結合LLM能夠無障礙與網頁進行交互,從而實現智能瀏覽器頁面操作。
- Office-Word-MCP:用于創建、讀取、編輯和格式化Microsoft Word文檔。主要操作能力如下:創建表格、添加不同級別的標題、插入段落可選樣式;格式化加粗、斜體、下劃線、顏色和字體屬性、搜索和替換;邊框和樣式格式化表格、格式表頭行、應用單元格陰影和自定義邊框。
- antvis/mcp-server-chart:用于生成可視化圖表的,目前支持 15+ 種圖表:
- 條形圖、餅圖、 柱形圖、 折線圖
- 魚骨圖、思維導圖、流程圖、
- 直方圖、線型圖、樹形圖、網絡圖
- 雷達圖、二維散點圖、詞語圖、區域圖表
- MySQL MCP:提供SQL語句查詢數據庫的能力:
- execute_query :支持select查詢、show展示、describe描述;
- get_table_info:獲取數據表的詳細結構信息;
- list_tables:列出數據庫中的所有數據表。
- Excel-MCP:基于MCP的文件處理服務器,提供讀取、寫入和分析Excel文件的功能:
- 讀取Excel文件:獲取工作表列表,讀取特定工作表的數據,讀取所有工作表的數據;
- 寫入Excel文件:創建新的Excel文件,向特定工作表寫入數據,支持多工作表;
- 分析Excel結構:分析工作表結構,將結構導出到新文件
- Nacos MCP Router:一個基于MCP官方標準SDK實現的的MCP Server,提供一組工具,提供推薦、分發、安裝及代理其他MCP Server的功能,幫助用戶更方便地使用MCP Server服務。
安裝較新版Nacos,打開管理后臺,MCP管理,創建MCP Server。 - @Joooook/12306-mcp:提供簡單的API接口,允許用戶搜索12306的車票。
- HowToCooke MCP,讓AI助手能夠為你推薦菜譜、規劃膳食,解決"今天吃什么"的世紀難題!
- 查詢全部菜譜:獲取所有可用菜譜數據,做菜百科全書
- 根據分類查詢菜譜:按照分類篩選菜譜,想吃水產?早餐?葷菜?主食?一鍵搞定!
- 智能推薦膳食:根據你的忌口、過敏原和用餐人數,為你規劃整整一周的美味佳肴
- 不知道吃什么:選擇困難癥福音!根據人數直接推薦今日菜單,再也不用糾結了
- mcp-server-weread:支持將微信讀書的書籍、筆記和劃線數據提供給支持MCP的LLM:
- 從微信讀書獲取書架信息;
- 搜索書架中的圖書;
- 獲取圖書的筆記和劃線;
- 支持按章節組織筆記和劃線。
- Fetch MCP:從互聯網上抓取URL并將其內容作為Markdown文件,接口參數:
url
: 要抓取的URLmax_length
:返回的最大字符數,默認5000start_index
:字符索引開始提取內容,默認0raw
:獲取未經MarkDown轉換的原始內容,默認false
{"mcpServers": {"playwright": {"command": "npx.cmd","args": ["@playwright/mcp@latest"]},"nacos-mcp-router": {"command": "docker","args": ["run","-i","--rm","--network","host","-e","NACOS_ADDR=localhost:8848","-e","NACOS_USERNAME=nacos","-e","NACOS_PASSWORD=nacos","-e","TRANSPORT_TYPE=stdio","nacos/nacos-mcp-router:latest"]},"amap-maps": {"command": "npx","args": ["-y","@amap/amap-maps-mcp-server"],"env": {"AMAP_MAPS_API_KEY": ""}},"mysql": {"command": "npx","args": ["mysql-mcp-server"],"env": {"MYSQL_HOST": "127.0.0.1","MYSQL_PORT": "3306","MYSQL_USER": "root","MYSQL_PASSWORD": "root","MYSQL_DB": "demo"}},"excel": {"command": "npx","args": ["--yes","@zhiweixu/excel-mcp-server"],"env": {"fileAbsolutePath": "D:\data\excel"}},"12306-mcp": {"command": "npx","args": ["-y","12306-mcp"]},"word-document-server": {"command": "uvx","args": ["--from","office-word-mcp-server","word_mcp_server"]},"fetch": {"command": "uvx","args": ["mcp-server-fetch"]},"mcp-server-chart": {"command": "npx.cmd","args": ["-y","@antv/mcp-server-chart"]}}
}