🎉🎉🎉🎉🎉🎉
歡迎訪問的個人博客:https://swzbk.site/,加好友,拉你入福利群
🎉🎉🎉🎉🎉🎉
1、deepseek介紹
DeepSeek(深度求索)是一家成立于2023年7月的中國人工智能公司,由量化資管巨頭幻方量化創立,專注于開發高性能大語言模型(LLM)及相關技術。今年年初以其模型高性能能力而備受關注,目前國內企業正在廣泛接入使用。
2、vue前端界面
-
加了一個nav頁簽:深度探索
-
頁面代碼如下:
<template><div class="chat-wrapper"><div class="chat-container"><div class="chat-header"><h2>DeepSeek 對話</h2></div><div class="chat-messages" ref="chatMessages"><div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.includes('你:') ? 'user-message' : 'bot-message']"><span>{{ message }}</span></div></div><div class="input-container"><input v-model="userInput" type="text" placeholder="輸入你的問題" @keydown.enter="sendMessage"><button @click="sendMessage">發送</button></div></div></div>
</template><script>
export default {data() {return {userInput: '',chatMessages: []};},methods: {async sendMessage() {if (this.userInput.trim() === '') return;// 顯示用戶消息this.chatMessages.push(`你: ${this.userInput}`);try {//這里后面換成服務器ipconst response = await fetch('http://localhost:8090/deepseek', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ prompt: this.userInput })});const data = await response.json();const answer = data.answer;// 顯示 DeepSeek 的回答this.chatMessages.push(`DeepSeek: ${answer}`);} catch (error) {console.error('請求出錯:', error);this.chatMessages.push('請求出錯,請稍后再試');}// 清空輸入框this.userInput = '';this.$nextTick(() => {this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;});}}
};
</script><style scoped>
.chat-wrapper {display: flex;justify-content: center;align-items: center;min-height: 100vh;background-color: #f4f4f9;
}.chat-container {width: 80%;height: 80vh;border-radius: 12px;box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);background-color: #fff;overflow: hidden;display: flex;flex-direction: column;
}.chat-header {background-color: #007bff;color: #fff;padding: 15px 20px;text-align: center;flex-shrink: 0;
}.chat-header h2 {margin: 0;font-size: 1.3rem;
}.chat-messages {flex-grow: 1;overflow-y: auto;padding: 20px;display: flex;flex-direction: column;
}.message {padding: 10px 15px;border-radius: 8px;margin-bottom: 10px;max-width: 80%;word-wrap: break-word;
}.user-message {background-color: #e0f7fa;align-self: flex-end;color: #212121;
}.bot-message {background-color: #f1f8e9;align-self: flex-start;color: #212121;
}.input-container {display: flex;padding: 15px 20px;border-top: 1px solid #e0e0e0;flex-shrink: 0;
}.input-container input {flex: 1;padding: 10px;border: 1px solid #ccc;border-radius: 6px;margin-right: 10px;font-size: 1rem;
}.input-container button {padding: 10px 20px;background-color: #007bff;color: #fff;border: none;border-radius: 6px;cursor: pointer;font-size: 1rem;transition: background-color 0.2s ease;
}.input-container button:hover {background-color: #0056b3;
}
</style>
3、deepseek api申請
deepseek api
申請完之后,需要充值使用,有的新人會有免費使用次數,我這里充值了5米,測試用夠了。
4、springboot接口增加
- DeepSeekController接口
package top.naccl.controller;
import com.fasterxml.jackson.databind.JsonNode;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.naccl.model.dto.DeepSeekRequest;
import top.naccl.model.dto.DeepSeekResponse;
import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;
import java.util.concurrent.TimeUnit;@RestController
public class DeepseekController {private static final ObjectMapper objectMapper = new ObjectMapper();//換成自己的deepseek apiprivate static final String DEEPSEEK_API_KEY = "sk-xxxx";private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";@PostMapping("/deepseek")public DeepSeekResponse handleDeepSeekRequest(@RequestBody DeepSeekRequest request) throws IOException {OkHttpClient client = new OkHttpClient.Builder().readTimeout(100, TimeUnit.SECONDS) // 增加讀取超時時間.build();MediaType JSON = MediaType.get("application/json; charset=utf-8");String json = "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"" + request.getPrompt() + "\"}]}";// 使用 okhttp3.RequestBody 創建請求體okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON, json.getBytes());Request apiRequest = new Request.Builder().url(DEEPSEEK_API_URL).post(body).addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY).addHeader("Content-Type", "application/json").build();try (Response response = client.newCall(apiRequest).execute()) {if (!response.isSuccessful()) {return new DeepSeekResponse("請求失敗:" + response.code());}return handleNormalResponse(response);} catch (IOException e) {return new DeepSeekResponse("請求異常:" + e.getMessage());}}private DeepSeekResponse handleNormalResponse(Response response) throws IOException {try (ResponseBody body = response.body()) {if (body == null) {return new DeepSeekResponse("空響應");}String responseData = body.string();JsonNode jsonNode = objectMapper.readTree(responseData);if (jsonNode.has("choices") && !jsonNode.get("choices").isEmpty()) {JsonNode messageNode = jsonNode.get("choices").get(0).get("message");if (messageNode != null && messageNode.has("content")) {return new DeepSeekResponse(messageNode.get("content").asText());}}return new DeepSeekResponse("未找到有效回答");}}}
- DeepSeekRequest請求類
package top.naccl.model.dto;import com.fasterxml.jackson.annotation.JsonProperty;// 請求類,用于接收前端傳來的用戶問題
public class DeepSeekRequest {@JsonProperty("prompt")private String prompt;public String getPrompt() {return prompt;}public void setPrompt(String prompt) {this.prompt = prompt;}
}
- DeepSeekResponse響應類
package top.naccl.model.dto;// 響應類,用于返回 DeepSeek 的回答給前端
public class DeepSeekResponse {private String answer;public DeepSeekResponse(String answer) {this.answer = answer;}public String getAnswer() {return answer;}public void setAnswer(String answer) {this.answer = answer;}
}
5、pom.xml引入
<!-- deepseek --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.11.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
6、問題總結
- 調用比較慢,上面的讀取時間需要設置長點
- 目前不支持記憶問答,每次刷新之前的問答就會清空
- 目前使用的是非流式響應,具體后面在研究流式響應,據說比較快,所以推薦
- 測試使用調用api 30次左右,花費0.05
- 界面還需待優化
🎉🎉🎉🎉🎉🎉
歡迎訪問的個人博客:https://swzbk.site/,加好友,拉你入福利群
🎉🎉🎉🎉🎉🎉