Spring AI 使用教程(2025年5月24日更新)
一、環境搭建與項目初始化
-
創建Spring Boot項目
- 使用IDEA或Spring Initializr創建項目,選擇JDK 17或更高版本(推薦21)。
- 勾選依賴項:
Spring Web
、Lombok
,Maven或Gradle作為構建工具。 - 添加Spring AI依賴(以OpenAI為例):
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId><version>1.0.0-M6</version> </dependency>
-
配置API密鑰
在application.yml
中配置模型服務(以DeepSeek為例):spring:ai:openai:api-key: sk-your-api-keybase-url: https://api.deepseek.com/v1chat:options:model: deepseek-chat ```<sup>5</sup><sup>8</sup><sup>11</sup>
二、基礎功能實現
-
調用大模型生成文本
- 通過
ChatClient
發送請求:@RestController public class ChatController {@Autowiredprivate ChatClient chatClient;@GetMapping("/chat")public String chat(@RequestParam String prompt) {return chatClient.prompt(prompt).call().content();} }
- 啟動應用后,訪問
http://localhost:8080/chat?prompt=寫一首春天的詩
即可獲取響應。
- 通過
-
文檔處理(ETL)
- 添加文檔處理依賴(如PDF解析):
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-tika-document-reader</artifactId> </dependency>
- 讀取并轉換本地文檔:
DocumentReader reader = new TikaDocumentReader(); List<Document> docs = reader.read("file:///data.pdf");
- 添加文檔處理依賴(如PDF解析):
三、高級應用場景
-
RAG(檢索增強生成)
- 結合本地數據與大模型,實現知識庫增強問答:
- 使用
spring-ai-spark
集成訊飛星火:<dependency><groupId>com.iflytek.spark</groupId><artifactId>spring-ai-spark-spring-boot-starter</artifactId><version>1.0.0-M6-SNAPSHOT</version> </dependency>
- 將本地數據向量化存儲,通過語義檢索生成精準答案。
- 使用
- 結合本地數據與大模型,實現知識庫增強問答:
-
MCP服務集成
- 搭建MCP(Model Context Protocol)服務:
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-server-webmvc</artifactId> </dependency>
- 通過JSON-RPC與模型交互,支持多模態輸入輸出。
- 搭建MCP(Model Context Protocol)服務:
四、實戰案例:構建網頁聊天應用
-
前端集成
- 使用Thymeleaf或React/Vue搭建前端頁面,通過WebSocket或SSE與后端通信。
- 示例代碼片段(SSE推送):
@GetMapping("/stream-chat") public SseEmitter streamChat(@RequestParam String prompt) {SseEmitter emitter = new SseEmitter();chatClient.prompt(prompt).stream().subscribe(content -> {emitter.send(content);});return emitter; }
-
記憶存儲與會話管理
- 使用
ChatMemory
組件保存上下文:@Bean public ChatMemory chatMemory() {return new InMemoryChatMemory(50); // 保留最近50輪對話 }
- 使用
五、注意事項與調試技巧
-
常見問題
- 模型響應慢:調整超時配置
spring.ai.openai.chat.options.timeout=60s
。 - 中文支持不佳:在
prompt
中明確指定“用中文回答”。
- 模型響應慢:調整超時配置
-
日志調試
- 啟用詳細日志:
logging:level:org.springframework.ai: DEBUG
- 啟用詳細日志:
六、總結與擴展
Spring AI通過模塊化設計,支持快速接入主流模型(如DeepSeek、訊飛星火)和高級功能(RAG、MCP)。開發者可結合業務需求擴展以下場景:
- 多模型混合調用:通過
@Qualifier
注解切換不同模型。 - 工具調用:集成外部API(如天氣查詢)增強AI能力。
- 企業級部署:結合Kubernetes實現彈性擴縮容。