Spring Boot整合DeepSeek实现AI对话的 流式请求
时间: 2025-03-02 11:03:54 浏览: 117
### 集成 DeepSeek 实现流式 AI 对话
为了在 Spring Boot 项目中集成 DeepSeek 并实现流式的 AI 对话功能,可以按照如下方式操作:
#### 添加依赖项
首先,在 `pom.xml` 文件中添加必要的 Maven 依赖来支持与 DeepSeek 和 WebSocket 的交互。
```xml
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- spring-ai-openai-spring-boot-starter for DeepSeek integration -->
<dependency>
<groupId>com.spring.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
</dependencies>
```
此部分配置确保应用程序能够通过 HTTP 请求访问外部 API,并且可以通过 WebSocket 进行实时通信[^1]。
#### 创建配置类
接着创建一个 Java 类用于加载并管理连接到 DeepSeek 所需的各项参数。这通常涉及到设置 API 密钥和其他可能影响请求行为的选项。
```java
@Configuration
@ConfigurationProperties(prefix = "deepseek")
@Data
public class DeepSeekConfig {
private String apiKey;
@Bean
public ClientV4 getDeepSeekClient() {
return new ClientV4.Builder(apiKey).build();
}
}
```
这段代码定义了一个名为 `DeepSeekConfig` 的 Bean 来存储和提供给其他组件使用的客户端实例[^4]。
#### 构建控制器处理请求
最后一步是在应用内构建 RESTful 或者基于 WebSocket 的接口以便前端或其他服务发起对话请求。这里展示的是简单的 REST 控制器例子,它接收消息并通过 DeepSeek 发送出去获取回复。
```java
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final ClientV4 deepSeekClient;
public ChatController(ClientV4 deepSeekClient) {
this.deepSeekClient = deepSeekClient;
}
@PostMapping("/stream")
public ResponseEntity<StreamingHttpResponse> streamChat(@RequestBody Map<String, Object> requestMap) throws Exception {
// Prepare the chat completion request with streaming enabled.
var responseStream = deepSeekClient.createChatCompletion(
CreateChatCompletionRequest.builder()
.model("text-davinci-003")
.messages(List.of(new Message("user", (String)requestMap.get("message")), new Message("assistant","")))
.stream(true)
.build());
StreamingHttpResponse response = new StreamingHttpResponse(responseStream);
return ResponseEntity.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(response);
}
}
```
上述代码片段展示了如何利用 `@RestController` 注解建立一个新的端点 `/api/chat/stream` 接收 POST 方法传入的消息体作为输入数据发送至 DeepSeek,并开启流模式返回结果[^2]。
阅读全文
相关推荐
















