是deepseek
时间: 2025-06-10 16:43:47 浏览: 24
### 如何在 Spring Boot 中接入 DeepSeek
要在 Spring Boot 项目中接入 DeepSeek,可以按照以下方法实现。以下是完整的步骤和代码示例。
#### 准备工作
1. **注册 DeepSeek 账号**:访问 DeepSeek 官方网站,完成注册并获取 API Key[^1]。
2. **创建 Spring Boot 项目**:使用 Spring Initializr(https://start.spring.io/)创建一个基本的 Spring Boot 项目,并添加必要的依赖项[^1]。
#### 添加依赖
在项目的 `pom.xml` 文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
```
这些依赖项用于支持 Web 功能和响应式编程[^2]。
#### 配置 API Key
将获取到的 DeepSeek API Key 配置到项目的 `application.properties` 文件中:
```properties
deepseek.api.key=YOUR_API_KEY_HERE
```
#### 创建服务类
创建一个服务类来处理与 DeepSeek 的交互。例如:
```java
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
@Service
public class DeepSeekService {
private final WebClient webClient;
public DeepSeekService() {
this.webClient = WebClient.builder()
.baseUrl("https://api.deepseek.com/v1/completion")
.defaultHeader("Authorization", "Bearer " + getApiKey())
.build();
}
private String getApiKey() {
return System.getenv("DEEPSEEK_API_KEY"); // 或从配置文件中读取
}
public Flux<String> streamCompletion(String prompt) {
return webClient.post()
.bodyValue(Map.of("prompt", prompt, "max_tokens", 100))
.retrieve()
.bodyToFlux(String.class);
}
}
```
此服务类使用 `WebClient` 发送请求到 DeepSeek API,并返回流式输出[^2]。
#### 编写测试代码
编写测试代码以验证功能是否正常。例如:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.test.StepVerifier;
@SpringBootTest
public class DeepseekDemoApplicationTests {
@Autowired
private DeepSeekService deepSeekService;
@Test
public void contextLoads() {
Flux<String> flux = deepSeekService.streamCompletion("springboot如何接入DeepSeek的流式输出");
StepVerifier.create(flux)
.thenConsumeWhile(content -> {
System.out.print(content);
return true;
})
.verifyComplete();
}
}
```
此测试代码通过 `StepVerifier` 验证流式输出是否正确。
#### 使用 Spring AI Alibaba 框架(可选)
如果希望使用更高级的功能,可以考虑使用 Spring AI Alibaba 框架。该框架允许轻松集成 DeepSeek 模型,并提供对话功能。具体步骤如下:
1. 确保 JDK17 和 Spring Boot 3.3.x 环境已准备好[^3]。
2. 申请阿里云的 API Key,并在百炼页面开通服务。
3. 配置依赖并注入 `ChatClient`,即可与模型进行对话[^3]。
---
### 注意事项
- 如果需要更高的性能或更低的成本,可以考虑自行搭建 DeepSeek 模型[^3]。
- 确保 API Key 安全,避免泄露给未经授权的用户。
---
阅读全文
相关推荐














