文章目錄
- 前言
- 測試環境
- 項目構建
- 依賴引入
- 指定openai 相關配置
- 基于 application.yml 配置 Open AI 屬性
- application.yml
- 編寫測試類
- 測試請求
- 基于讀取后配置請求
- 編寫測試接口
- 測試效果展示
- 流式輸出
前言
AI 技術越來越火爆,作為Java開發人員也不能拖了后腿。
前段時間使用LangChain4j
也寫了一些技術博客,實現了比如一些基礎對話功能
、流式輸出功能
、多輪對話
等。但在嘗試進行MCP
操作的時候,總感覺MCP Server
部分不能很好的獨立出來,就像一個Function Call
一樣,很別扭。嘗試使用了Spring AI
,效果還行。
本篇博客依舊從最基本的Springboot 項目整合 Spring AI實現簡單對話,流式輸出開始,逐步說明怎么去玩 Spring AI。
測試環境
- jdk 17
- maven 3.6.3
- springboot 3.4.0
- spring-ai-bom 1.0.0-M6
項目構建
依賴引入
測試使用的是spring-ai-openai
,但經濟受限,沒有去購買國外的KEY
。但DeepSeek
天然支持Open AI
的格式。
本次測試依賴導入:
<properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring-ai.version>1.0.0-M6</spring-ai.version>
</properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 封裝了各大模型的交互接口 --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId></dependency><!-- 用于各大模型進行自動裝配 --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>${spring-ai.version}</version><type>pom</type><!-- 父maven項目,由于已經引入 springboot-parent,此處只能這種方式引入 --><scope>import</scope></dependency></dependencies>
</dependencyManagement>
因為項目是基于Spring boot
構建的,項目創建的時候已經引入了一個spring-boot-dependencies
的父級依賴,無法再引入一個。而spring-ai-bom
也是一個父級框架,所以采取了dependencyManagement
的方式引入。