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

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

接下來就是代碼實例了
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("流式回答開始,問題:{}", 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 請求時發(fā)生錯誤", e);
emitter.completeWithError(e);
}
} catch (Exception e) {
log.error("處理 Deepseek 請求時發(fā)生錯誤", e);
emitter.completeWithError(e);
}
});
return emitter;
}
}3.調(diào)用測試
curl -v -X POST \
http://localhost:8091/api/v1/chat \
-H "Content-Type: application/json" \
-d '"幫我寫一篇2000字的 我的祖國的文字"' \
--no-buffer打開終端輸入上述命令回車即可 但是端口必須要和你后端的一致 我這里是8091
4.運行結(jié)果

總結(jié)
到此這篇關(guān)于SpringBoot接入deepseek深度求索的文章就介紹到這了,更多相關(guān)SpringBoot接入deepseek深度求索內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于在使用Lombok時maven?install找不到符號問題的解決辦法
Maven環(huán)境下開發(fā)項目時,尤其是涉及Lombok或其他依賴時,IDE會在構(gòu)建和編譯過程中進(jìn)行注解處理,這篇文章主要介紹了關(guān)于在使用Lombok時maven?install找不到符號問題的解決辦法,需要的朋友可以參考下2025-10-10
java?數(shù)組越界判斷和獲取數(shù)組長度的實現(xiàn)方式
這篇文章主要介紹了java?數(shù)組越界判斷和獲取數(shù)組長度的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Spring之底層架構(gòu)核心概念Environment及用法詳解
這篇文章主要介紹了Spring之底層架構(gòu)核心概念-Environment,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12
SpringBoot中使用MyBatis-Plus實現(xiàn)分頁接口的詳細(xì)教程
MyBatis-Plus是一個MyBatis的增強(qiáng)工具,在MyBatis的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生,在SpringBoot項目中使用MyBatis-Plus可以大大簡化分頁邏輯的編寫,本文將介紹如何在 SpringBoot項目中使用MyBatis-Plus實現(xiàn)分頁接口2024-03-03

