炸裂:SpringAI內置DeepSeek啦!
SpringAI和DeepSeek介紹
Spring AI 是 Spring 生態(tài)系統(tǒng)中的一個重要項目,旨在將人工智能集成到 Spring 應用程序中,它為 Java 開發(fā)者提供了一種便捷的方式來構建、管理和部署 AI 模型。
圖片
“
Spring AI 的核心是解決了 Spring 生態(tài)和 AI 的快速集成:將您的企業(yè)數(shù)據(jù)和API 與 AI 模型連接起來。
Spring AI 幾乎支持所有主流的 AI 模型提供商,例如 Anthropic、OpenAI、Microsoft、Amazon、Google 和 Ollama。支持的功能如下:
- 聊天
- 嵌入附件
- 文本轉圖片
- 音頻轉文本
- 文本轉音頻
Spring AI 最新預覽版也將集成 DeepSeek 大模型。
DeepSeek 介紹
DeepSeek 是國內頂尖 AI 團隊「深度求索」開發(fā)的多模態(tài)大模型,具備數(shù)學推理、代碼生成等深度能力,堪稱"AI界的六邊形戰(zhàn)士"。DeepSeek 最新版本 R1 采用了“思維鏈”技術,能夠展示完整的推理過程,使其在復雜推理任務上表現(xiàn)出色,甚至在某些方面可以與 OpenAI 的 O1 模型相媲美。
DeepSeek 身上的標簽有很多,其中最具代表性的標簽有以下兩個:
- 低成本(不挑硬件、開源、使用簡單無需復雜提示詞)。
- 高性能(推理能力極強、回答準確)。
Spring AI 集成 DeepSeek 步驟如下。
1.環(huán)境準備
在開始集成之前,確保你的開發(fā)環(huán)境滿足以下要求:
- JDK 17 或更高版本
- Maven 或 Gradle 構建工具
- DeepSeek API Key(可通過官網(wǎng)注冊獲取),申請地址:https://platform.deepseek.com/usage
2.創(chuàng)建SpringBoot項目
使用 Spring Initializr 或其他工具創(chuàng)建一個新的 Spring Boot 項目,確保版本為 3.2.x 或更高。
3.添加依賴
在項目的 pom.xml 文件中添加 SpringAI 和 DeepSeek 的相關依賴。
以下是基于 Maven 的依賴配置示例:
<dependencies>
<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>
</dependencies>
4.配置文件
在 application.properties 或 application.yml 文件中添加 DeepSeek 的配置信息:
# 必填項
spring.ai.openai.api-key=you-apikey
spring.ai.openai.base-url=https://api.deepseek.com
# 模型選擇(示例使用對話模型)
spring.ai.openai.chat.options.model=deepseek-chat
其中,api-key 是你在 DeepSeek 官網(wǎng)注冊后獲取的密鑰,base-url 是 DeepSeek API 的服務地址,model 指定使用的模型版本。
DeepSeek模型介紹
DeepSeek 目前支持以下兩種模型:
圖片
- deepseek-chat(V3):適用于聊天機器人、智能客服、內容生成等,能夠理解和生成日常對話內容。
- deepseek-reasoner(R1):專為復雜推理任務設計,適合解決需要深度邏輯分析和推理的問題。
5.編寫代碼
創(chuàng)建一個控制器類,用于處理與 DeepSeek 的交互,以下是一個簡單的示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private DeepSeekClient deepSeekClient;
@PostMapping
public String chat(@RequestBody String message) {
return deepSeekClient.chatCompletion(message).getOutput().getContent();
}
@GetMapping(value = "/stream", produces = "text/event-stream")
public Flux<String> chatStream(@RequestParam String message) {
return deepSeekClient.chatFluxCompletion(message)
.map(response -> response.getOutput().getContent());
}
}
在上述代碼中,chat 方法用于處理普通的非流式請求,而 chatStream 方法則支持流式響應,能夠實時返回 AI 的推理結果。
課后思考:關于流式輸出
大模型的響應速度是很慢的,為了避免用戶用戶能夠耐心等待輸出的結果,我們通常會使用流式輸出一點點將結果輸出給用戶,那么問題來了,想要實現(xiàn)流式結果輸出,后端和前端要如何配合?后端要使用什么技術實現(xiàn)流式輸出呢?