SpringBoot接入deepseek深度求索示例代碼(jdk1.8)
以下是在SpringBoot中接入ai deepseek的過(guò)程。我這里的環(huán)境是jdk1.8,官網(wǎng)暫時(shí)沒(méi)有java的示例。
1. 創(chuàng)建 API key
新用戶會(huì)有500萬(wàn)的免費(fèi)token額度

2. 封裝詢問(wèn)deepseek的工具方法
添加key值和詢問(wèn)路徑。API_KEY為你創(chuàng)建的key值。這個(gè)在配置文件或者是寫在常量文件都可以,我這是寫在配置文件里了

接下來(lái)就是代碼實(shí)例了
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiwonders.paperserver.service.IAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
@RequestMapping("/api/v1")
@Slf4j
public class OpenAIController {
@Value("${ai.config.deepseek.apiKey}")
private String API_KEY;
@Value("${ai.config.deepseek.baseUrl}")
private String API_URL;
@Autowired
private IAuthService authService;
private final ExecutorService executorService = Executors.newCachedThreadPool();
private final ObjectMapper objectMapper = new ObjectMapper();
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter chat(
// @RequestHeader("Authorization")String token,
@RequestBody String question) {
// String openid = authService.openid(token);
// if (openid == null) {
// throw new RuntimeException("用戶未登錄");
// }
SseEmitter emitter = new SseEmitter(-1L);
executorService.execute(() -> {
try {
log.info("流式回答開始,問(wèn)題:{}", question);
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost request = new HttpPost(API_URL);
request.setHeader("Content-Type", "application/json");
request.setHeader("Authorization", "Bearer " + API_KEY);
Map<String, Object> message = new HashMap<>();
message.put("role", "user");
message.put("content", question);
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("model", "deepseek-chat");
requestMap.put("messages", Collections.singletonList(message));
requestMap.put("stream", true);
String requestBody = objectMapper.writeValueAsString(requestMap);
request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));
try (CloseableHttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("data: ")) {
String jsonData = line.substring(6);
if ("[DONE]".equals(jsonData)) {
break;
}
JsonNode node = objectMapper.readTree(jsonData);
String content = node.path("choices")
.path(0)
.path("delta")
.path("content")
.asText("");
if (!content.isEmpty()) {
emitter.send(content);
}
}
}
log.info("流式回答結(jié)束,{}",question);
emitter.complete();
}
} catch (Exception e) {
log.error("處理 Deepseek 請(qǐng)求時(shí)發(fā)生錯(cuò)誤", e);
emitter.completeWithError(e);
}
} catch (Exception e) {
log.error("處理 Deepseek 請(qǐng)求時(shí)發(fā)生錯(cuò)誤", e);
emitter.completeWithError(e);
}
});
return emitter;
}
}3.調(diào)用測(cè)試
curl -v -X POST \
http://localhost:8091/api/v1/chat \
-H "Content-Type: application/json" \
-d '"幫我寫一篇2000字的 我的祖國(guó)的文字"' \
--no-buffer打開終端輸入上述命令回車即可 但是端口必須要和你后端的一致 我這里是8091
4.運(yùn)行結(jié)果

總結(jié)
到此這篇關(guān)于SpringBoot接入deepseek深度求索的文章就介紹到這了,更多相關(guān)SpringBoot接入deepseek深度求索內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot兩種方式接入DeepSeek的實(shí)現(xiàn)
- SpringBoot快速接入DeepSeek?api(帶頁(yè)面)保姆級(jí)教程
- SpringBoot調(diào)用DeepSeek接口的實(shí)現(xiàn)
- SpringBoot或SpringAI對(duì)接DeepSeek大模型的詳細(xì)步驟
- SpringBoot整合DeepSeek實(shí)現(xiàn)AI對(duì)話功能
- SpringBoot調(diào)用DeepSeek?API的完整操作指南
- springboot接入deepseek深度求索代碼示例(java版)
- springboot集成Deepseek4j的項(xiàng)目實(shí)踐
相關(guān)文章
SpringBoot Swagger2 接口規(guī)范示例詳解
Swagger(在谷歌、IBM、微軟等公司的支持下)做了一個(gè)公共的文檔風(fēng)格來(lái)填補(bǔ)上述問(wèn)題,在本文中,我們將會(huì)學(xué)習(xí)怎么使用Swagger的 Swagger2注解去生成REST API文檔,感興趣的朋友一起看看吧2023-12-12
Mybatis中Mapper標(biāo)簽總結(jié)大全
這篇文章主要介紹了Mybatis中Mapper標(biāo)簽總結(jié)大全,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
java 靜態(tài)代理 動(dòng)態(tài)代理深入學(xué)習(xí)
代理模式是常用的java設(shè)計(jì)模式,特征是代理類與委托類有同樣的接口,代理類主要負(fù)責(zé)為委托類預(yù)處理消息、過(guò)濾消息、把消息轉(zhuǎn)發(fā)給委托類,以及事后處理消息等,需要的朋友可以參考下2012-11-11
Idea創(chuàng)建Jsp項(xiàng)目完整版教程
一直在使用eclipse,對(duì)idea嗤之以鼻,前些日子換成了idea以后覺(jué)得太香了,這篇文章主要給大家介紹了關(guān)于Idea創(chuàng)建Jsp項(xiàng)目的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-04-04

