面試對話標題自動總結
主要實現思路:每當AI回復用戶之后,調用方法查看當前對話是否大于三條,如果大于則將用戶的兩條和AI回復的一條對話傳給DeepSeek讓其進行總結(后端),總結后調用updateChatTopic
進行更新標題,此外本次標題的更改還實現了仿打字機效果。
后端實現
首先,要在.env
文件中配置DEEPSEEK_API
,然后在application.yml
中添加:
deepseek:api:key: ${DEEPSEEK_API} # DeepSeek API Key,從環境變量中獲取
之后創建DeesSeekService.java
package com.sdumagicode.backend.openai.service;import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;/*** DeepSeek API服務類* 用于與DeepSeek API進行交互*/
@Service
public class DeepSeekService {private static final Logger logger = LoggerFactory.getLogger(DeepSeekService.class);private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";@Value("${deepseek.api.key}")private String apiKey;private final OkHttpClient client;private final ObjectMapper objectMapper;public DeepSeekService() {this.client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).build();this.objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setSerializationInclusion(JsonInclude.Include.NON_NULL).setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);}/*** 發送聊天請求到DeepSeek API* * @param messages 消息列表* @param model 模型名稱,默認為 "deepseek-chat"* @param temperature 溫度參數,控制隨機性* @return API響應的JSON字符串* @throws IOException 如果API請求失敗*/public String chatCompletion(List<Map<String, String>> messages, String model, double temperature) throws IOException {Map<String, Object> requestBody = new HashMap<>();requestBody.put("messages", messages);requestBody.put("model", model);requestBody.put("temperature", temperature);String jsonBody = objectMapper.writeValueAsString(requestBody);RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);Request request = new Request.Builder().url(API_URL).addHeader("Authorization", "Bearer " + apiKey).addHeader("Content-Type", "application/json").post(body).build();try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("API請求失敗: " + response.code() + " " + response.message());}return response.body().string();}}/*** 發送聊天請求到DeepSeek API(使用默認參數)* * @param messages 消息列表* @return API響應的JSON字符串* @throws IOException 如果API請求失敗*/public String chatCompletion(List<Map<String, String>> messages) throws IOException {return chatCompletion(messages, "deepseek-chat", 0.7);}/*** 創建聊天消息* * @param role 角色 (system, user, assistant)* @param content 消息內容* @return 包含角色和內容的Map*/public Map<String, String> createMessage(String role, String content) {Map<String, String> message = new HashMap<>();message.put("role", role);message.put("content", content);return message;}/*** 流式聊天請求(SSE)* * @param messages 消息列表* @param model 模型名稱* @param temperature 溫度參數* @param callback 回調函數,用于處理每個SSE事件* @throws IOException 如果API請求失敗*/public void streamingChatCompletion(List<Map<String, String>> messages, String model, double temperature, Callback callback) throws IOException {Map<String, Object> requestBody = new HashMap<>();requestBody.put("messages", messages);requestBody.put("model", model);requestBody.put("temperature", temperature);requestBody.put("stream", true);String jsonBody = objectMapper.writeValueAsString(requestBody);RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);Request request = new Request.Builder().url(API_URL).addHeader("Authorization", "Bearer " + apiKey).addHeader("Content-Type", "application/json").post(body).build();client.newCall(request).enqueue(callback);}
}
該文件用于與DeepSeek AI API進行交互。主要功能包括:
-
基本配置:
- 使用OkHttpClient進行HTTP請求
- 配置ObjectMapper處理JSON序列化/反序列化
- 從配置文件讀取API密鑰
-
主要方法:
chatCompletion
:向DeepSeek API發送聊天請求,有兩個版本:- 完整參數版:可指定消息、模型和溫度
- 簡化版:使用默認參數
createMessage
:創建聊天消息對象streamingChatCompletion
:流式聊天請求,支持SSE(服務器發送事件)listModels
:獲取可用模型列表
-
技術特點:
- 使用Spring的
@Service
注解標記為服務 - 通過
@Value
注入API密鑰 - 支持異步回調處理流式響應
- 包含完整的異常處理和日志記錄
- 使用Spring的
這個服務類是后端與DeepSeek AI API通信的核心組件,負責處理所有AI聊天相關的請求。
DeepSeekController.java
package com.sdumagicode.backend.openai;import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdumagicode.backend.core.result.GlobalResult;
import com.sdumagicode.backend.core.result.GlobalResultGenerator;
import com.sdumagicode.backend.openai.service.DeepSeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** DeepSeek API控制器* 提供DeepSeek模型API的接口*/
@RestController
@RequestMapping("/api/v1/deepseek")
public class DeepSeekController {@Autowiredprivate DeepSeekService deepSeekService;private final ObjectMapper objectMapper = new ObjectMapper();/*** 發送聊天請求** @param requestBody 請求體,包含messages, model, temperature* @return 聊天響應*/@PostMapping("/chat")public GlobalResult<String> chatCompletion(@RequestBody Map<String, Object> requestBody) {try {@SuppressWarnings("unchecked")List<Map<String, String>> messages = (List<Map<String, String>>) requestBody.get("messages");String model = requestBody.containsKey("model") ? (String) requestBody.get("model") : "deepseek-chat";double temperature = requestBody.containsKey("temperature") ? Double.parseDouble(requestBody.get("temperature").toString()) : 0.7;String response = deepSeekService.chatCompletion(messages, model, temperature);return GlobalResultGenerator.genSuccessResult(response);} catch (Exception e) {return GlobalResultGenerator.genErrorResult("聊天請求失敗:" + e.getMessage());}}/*** 生成對話摘要* * @param requestBody 包含對話消息和chatId的請求體* @return 生成的摘要*/@PostMapping("/summarize")public GlobalResult<String> summarizeConversation(@RequestBody Map<String, Object> requestBody) {try {@SuppressWarnings("unchecked")List<Map<String, Object>> messages = (List<Map<String, Object>>) requestBody.get("messages");// 準備系統提示詞和用戶消息List<Map<String, String>> promptMessages = new ArrayList<>();// 添加系統提示Map<String, String> systemPrompt = new HashMap<>();systemPrompt.put("role", "system");systemPrompt.put("content", "你是一個專業的面試對話摘要生成器。請根據以下面試對話生成一個簡短的標題,標題應概括對話的主要內容。"+ "標題必須精煉,不超過20個字,不要加任何前綴和標點符號,直接輸出標題文本。標題應突出面試的主要話題或技能領域。");promptMessages.add(systemPrompt);// 構建對話歷史StringBuilder conversationBuilder = new StringBuilder();for (Map<String, Object> message : messages) {String role = (String) message.get("role");String content = (String) message.get("content");if (content == null || content.trim().isEmpty()) {continue;}conversationBuilder.append(role.equals("assistant") ? "面試官: " : "候選人: ");conversationBuilder.append(content).append("\n\n");}// 添加用戶消息,包含對話內容Map<String, String> userMessage = new HashMap<>();userMessage.put("role", "user");userMessage.put("content", "以下是一段面試對話,請為其生成一個簡短的標題:\n\n" + conversationBuilder.toString());promptMessages.add(userMessage);// 調用DeepSeek API生成摘要,使用較低的溫度以獲得更確定性的結果String response = deepSeekService.chatCompletion(promptMessages, "deepseek-chat", 0.3);// 解析響應,提取摘要文本JsonNode responseJson = objectMapper.readTree(response);String summary = responseJson.path("choices").get(0).path("message").path("content").asText();// 清理摘要文本,去除多余的引號、空格和換行符summary = summary.replaceAll("\"", "").trim();summary = summary.replaceAll("\\r?\\n", " ").trim();return GlobalResultGenerator.genSuccessResult(summary);} catch (Exception e) {return GlobalResultGenerator.genErrorResult("生成摘要失敗:" + e.getMessage());}}
前端實現
自動總結標題功能在handlePollingCompleted
方法中實現,主要流程如下:
async handlePollingCompleted() {try {if (!this.activeChatRecord) return;// 檢查是否有足夠內容生成摘要且未生成過if (this.$refs.chatArea &&this.$refs.chatArea.messageListForShow &&!this.summarizedChatIds.has(this.activeChatRecord)) {const messages = this.$refs.chatArea.messageListForShow;// 至少需要3條消息才生成摘要if (messages.length >= 3) {// 準備對話數據const dialogData = messages.map(msg => ({role: msg.role,content: msg.content.text}));try {// 調用DeepSeek API生成摘要const summaryResponse = await axios.post('/api/deepseek/summarize', {messages: dialogData,chatId: this.activeChatRecord});if (summaryResponse.message) {const summary = summaryResponse.message;// 更新對話標題await axios.post('/api/chat/updateChatTopic', null, {params: {chatId: this.activeChatRecord,newTopic: summary}});// 記錄已生成摘要的對話IDthis.summarizedChatIds.add(this.activeChatRecord);// 重新加載聊天記錄顯示新標題await this.loadChatRecords();// 啟動打字機效果展示新標題this.startTypingAnimation(this.activeChatRecord, summary);}} catch (error) {console.warn('生成對話摘要失敗:', error);// 即使失敗也標記為已處理,避免重復嘗試this.summarizedChatIds.add(this.activeChatRecord);}}}// 后續處理actions的代碼...} catch (error) {console.error('獲取actions失敗:', error);}
}
關鍵設計要點:
- 觸發時機:當輪詢完成后自動觸發,通過
handlePollingCompleted
方法 - 條件判斷:
- 必須有活躍的聊天記錄
- 對話消息數量至少3條
- 該對話ID未被記錄在
summarizedChatIds
集合中
- 數據收集:從
messageListForShow
中提取對話內容并格式化 - API調用:通過
/api/deepseek/summarize
請求生成摘要 - 標題更新:通過
/api/chat/updateChatTopic
更新對話標題 - 狀態管理:
- 使用
summarizedChatIds
集合跟蹤已處理的對話 - 無論成功失敗都標記為已處理,避免重復請求
- 使用
- 用戶體驗:使用打字機效果動態展示新標題
打字機效果
打字機效果在文件中的實現主要包含三個核心方法和相應的CSS樣式,用于在聊天記錄標題中實現逐字顯示的動畫效果。
數據結構
typingAnimation: {chatId: null, // 當前執行動畫的對話IDoriginalText: '', // 完整文本displayText: '', // 當前顯示的文本(逐漸增加)isActive: false, // 動畫激活狀態charIndex: 0, // 當前字符索引timerId: null // 定時器ID
}
核心方法
- 啟動動畫:
startTypingAnimation(chatId, text) {this.stopTypingAnimation(); // 先停止已有動畫if (!text || !chatId || text.length < 3) return;this.typingAnimation = {chatId, originalText: text, displayText: '',isActive: true, charIndex: 0, timerId: null};setTimeout(() => this.animateNextChar(), 200); // 延遲啟動
}
- 字符添加動畫:
animateNextChar() {const { charIndex, originalText } = this.typingAnimation;if (charIndex <= originalText.length) {this.typingAnimation.displayText = originalText.substring(0, charIndex);this.typingAnimation.charIndex = charIndex + 1;// 隨機速度模擬自然打字const baseSpeed = 70;const randomVariation = Math.random() * 100;const speed = baseSpeed + randomVariation;this.typingAnimation.timerId = setTimeout(() => {this.animateNextChar();}, speed);} else {this.stopTypingAnimation(true);}
}
- 停止動畫:
stopTypingAnimation(completed = false) {if (this.typingAnimation.timerId) {clearTimeout(this.typingAnimation.timerId);}if (completed) {// 完成后短暫延遲setTimeout(() => {this.typingAnimation.isActive = false;}, 500);} else {// 立即重置this.typingAnimation = {chatId: null, originalText: '', displayText: '',isActive: false, charIndex: 0, timerId: null};}
}
視覺效果
- 閃爍光標: 使用CSS動畫模擬打字光標閃爍
.cursor {width: 2px;height: 16px;background-color: #409eff;animation: blink 0.7s infinite;
}@keyframes blink {0%, 100% { opacity: 1; }50% { opacity: 0; }
}
- 調用時機:
- 生成聊天摘要后:
this.startTypingAnimation(this.activeChatRecord, summary);
- 重命名對話后:
this.startTypingAnimation(chatId, this.newTopicName);