好消息,Spring AI 最新快照版已经内置 DeepSeek 了,所以以后项目中对接 DeepSeek 就方便多了。但因为快照版会有很多 Bug,所以今天咱们就来看稳定版的 Spring AI 如何对接 DeepSeek 满血版。
Spring AI 是 Spring 生态系统中的一个重要项目,旨在将人工智能集成到 Spring 应用程序中,它为 Java 开发者提供了一种便捷的方式来构建、管理和部署 AI 模型。
Spring AI 的核心是解决了 Spring 生态和 AI 的快速集成:将您的企业数据和****API 与 AI 模型连接起来。
Spring AI 几乎支持所有主流的 AI 模型提供商,例如 Anthropic、OpenAI、Microsoft、Amazon、Google 和 Ollama。支持的功能如下:
Spring AI 最新预览版也将集成 DeepSeek 大模型。
DeepSeek 介绍
DeepSeek 是国内顶尖 AI 团队「深度求索」开发的多模态大模型,具备数学推理、代码生成等深度能力,堪称"AI界的六边形战士"。DeepSeek 最新版本 R1 采用了“思维链”技术,能够展示完整的推理过程,使其在复杂推理任务上表现出色,甚至在某些方面可以与 OpenAI 的 O1 模型相媲美。
DeepSeek 身上的标签有很多,其中最具代表性的标签有以下两个:
SpringAI 集成 DeepSeek 步骤如下。
在开始集成之前,确保你的开发环境满足以下要求:
使用 Spring Initializr 或其他工具创建一个新的 Spring Boot 项目,确保版本为 3.2.x 或更高。
在项目的 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>
在 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 官网注册后获取的密钥,base-url 是 DeepSeek API 的服务地址,model 指定使用的模型版本。
DeepSeek 目前支持以下两种模型:
创建一个控制器类,用于处理与 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 的推理结果。
大模型的响应速度是很慢的,为了避免用户用户能够耐心等待输出的结果,我们通常会使用流式输出一点点将结果输出给用户,那么问题来了,想要实现流式结果输出,后端和前端要如何配合?后端要使用什么技术实现流式输出呢?
欢迎评论区给出你的解决答案,文章点赞过 100 咱们公布完整解决思路和具体实现源码哦。