SpringAI+DeepSeek

0. 前言

DeepSeek的爆火,推动着SpringAI大力的发展,接入大模型处理信息在将来一定是一个基本的信息流程。

1. 创建项目

image-20250226225412758 image-20250226225504879

2. 项目配置

在application.yml中编写:

1
2
3
4
5
6
7
8
spring:
ai:
openai:
base-url: https://api.deepseek.com
api-key: sk-xxxxxxxxxxxxxxxxxxxx614d5
chat:
options:
model: deepseek-chat

3. api对接

编写控制层交换数据:

OpenAIChatController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.kdd.deepseek.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class OpenAIChatController {

@Autowired
private OpenAiChatModel openAiChatModel;
/**
* @description: 静态输出
* @author: 康弟弟
* @date: 2025/2/26 22:57
* @param: [message]
* @return: java.lang.String
**/
@GetMapping(value = "/chat", produces = "text/plain;charset=utf-8")
public String chat(@RequestParam String message) {
return openAiChatModel.call(message).toString();
}
/**
* @description: 流式输出
* @author: 康弟弟
* @date: 2025/2/26 22:57
* @param: [message]
* @return: reactor.core.publisher.Flux<java.lang.String>
**/
@GetMapping(value = "/chatStream")
public Flux<String> chatStream(@RequestParam String message) {
return openAiChatModel.stream(message);
}
}

4. 项目测试

静态测试:

image-20250226225932345

流式测试:

image-20250226225908327

可以看到在流式输出的时候由于编码格式的问题导致了乱码,但是在F12中查看传输的数据包是发现没有问题的,问题出现在了数据的页面渲染,由于是直接返回的文字文本内容,我们只需要将返回的内容值重新渲染到html网页并且重新设置编码格式就可以解决这个问题。

5. 编写渲染网页

由此可见,我们编写一个设置UTF8的静态网页就可以解决这个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat</title>
<style>
body { font-family: Arial, sans-serif; }
#output { white-space: pre-wrap; }
</style>
</head>
<body>
<h1>AI Chat Interface</h1>
<input type="text" id="message" placeholder="输入消息...">
<button id="sendBtn">发送</button>
<h2>响应:</h2>
<div id="output"></div>

<script>
document.getElementById('sendBtn').onclick = function() {
const message = document.getElementById('message').value;
// 静态渲染
// // 发送聊天请求
// fetch(`/ai/chat?message=${encodeURIComponent(message)}`)
// .then(response => response.text())
// .then(data => {
// document.getElementById('output').innerText = data;
// });

// 启动流式聊天
const eventSource = new EventSource(`/ai/chatStream?message=${encodeURIComponent(message)}`);
eventSource.onmessage = function(event) {
document.getElementById('output').innerText += event.data;
};
eventSource.onerror = function() {
eventSource.close();
};
};
</script>
</body>
</html>

6. 网页测试

点击发送后,会有一定的数据发送和接收时间,重复点击会导致重复扣费。

image-20250226230329357

7. key的申请

DeepSeek 开放平台

image-20250226230545487