山東大學軟件學院項目實訓-基于大模型的模擬面試系統-面試對話標題自動總結

面試對話標題自動總結

主要實現思路:每當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進行交互。主要功能包括:

  1. 基本配置

    • 使用OkHttpClient進行HTTP請求
    • 配置ObjectMapper處理JSON序列化/反序列化
    • 從配置文件讀取API密鑰
  2. 主要方法

    • chatCompletion:向DeepSeek API發送聊天請求,有兩個版本:
      • 完整參數版:可指定消息、模型和溫度
      • 簡化版:使用默認參數
    • createMessage:創建聊天消息對象
    • streamingChatCompletion:流式聊天請求,支持SSE(服務器發送事件)
    • listModels:獲取可用模型列表
  3. 技術特點

    • 使用Spring的@Service注解標記為服務
    • 通過@Value注入API密鑰
    • 支持異步回調處理流式響應
    • 包含完整的異常處理和日志記錄

這個服務類是后端與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);}
}

關鍵設計要點:

  1. 觸發時機:當輪詢完成后自動觸發,通過handlePollingCompleted方法
  2. 條件判斷
    • 必須有活躍的聊天記錄
    • 對話消息數量至少3條
    • 該對話ID未被記錄在summarizedChatIds集合中
  3. 數據收集:從messageListForShow中提取對話內容并格式化
  4. API調用:通過/api/deepseek/summarize請求生成摘要
  5. 標題更新:通過/api/chat/updateChatTopic更新對話標題
  6. 狀態管理
    • 使用summarizedChatIds集合跟蹤已處理的對話
    • 無論成功失敗都標記為已處理,避免重復請求
  7. 用戶體驗:使用打字機效果動態展示新標題

打字機效果

打字機效果在文件中的實現主要包含三個核心方法和相應的CSS樣式,用于在聊天記錄標題中實現逐字顯示的動畫效果。

數據結構

typingAnimation: {chatId: null,      // 當前執行動畫的對話IDoriginalText: '',  // 完整文本displayText: '',   // 當前顯示的文本(逐漸增加)isActive: false,   // 動畫激活狀態charIndex: 0,      // 當前字符索引timerId: null      // 定時器ID
}

核心方法

  1. 啟動動畫:
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); // 延遲啟動
}
  1. 字符添加動畫:
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);}
}
  1. 停止動畫:
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};}
}

視覺效果

  1. 閃爍光標: 使用CSS動畫模擬打字光標閃爍
.cursor {width: 2px;height: 16px;background-color: #409eff;animation: blink 0.7s infinite;
}@keyframes blink {0%, 100% { opacity: 1; }50% { opacity: 0; }
}
  1. 調用時機:
  • 生成聊天摘要后: this.startTypingAnimation(this.activeChatRecord, summary);
  • 重命名對話后: this.startTypingAnimation(chatId, this.newTopicName);

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/84526.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/84526.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/84526.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring Cloud與Alibaba微服務架構全解析

Spring Cloud與Spring Cloud Alibaba微服務架構解析 1. Spring Boot概念 Spring Boot并不是新技術&#xff0c;而是基于Spring框架下“約定優于配置”理念的產物。它幫助開發者更容易、更快速地創建獨立運行和產品級別的基于Spring框架的應用。Spring Boot中并沒有引入新技術…

AI 賦能 Java 開發:從通宵達旦到高效交付的蛻變之路

作為一名深耕 Java 開發領域多年的從業者&#xff0c;相信很多同行都與我有過相似的經歷&#xff1a;在 “996” 甚至 “007” 的高壓模式下&#xff0c;被反復修改的需求、復雜的架構設計、無休止的代碼編寫&#xff0c;以及部署時層出不窮的問題折磨得疲憊不堪。長期以來&…

06. C#入門系列【自定義類型】:從青銅到王者的進階之路

C#入門系列【自定義類型】&#xff1a;從青銅到王者的進階之路 一、引言&#xff1a;為什么需要自定義類型&#xff1f; 在C#的世界里&#xff0c;系統自帶的類型&#xff08;如int、string、bool&#xff09;就像是基礎武器&#xff0c;能解決一些簡單問題。但當你面對復雜的…

使用 PyTorch 和 TensorBoard 實時可視化模型訓練

在這個教程中&#xff0c;我們將使用 PyTorch 訓練一個簡單的多層感知機&#xff08;MLP&#xff09;模型來解決 MNIST 手寫數字分類問題&#xff0c;并且使用 TensorBoard 來可視化訓練過程中的不同信息&#xff0c;如損失、準確度、圖像、參數分布和學習率變化。 步驟 1&…

第十五章 15.OSPF(CCNA)

第十五章 15.OSPF(CCNA) 介紹了大家都能用的OSPF動態路由協議 注釋&#xff1a; 學習資源是B站的CCNA by Sean_Ning CCNA 最新CCNA 200-301 視頻教程(含免費實驗環境&#xff09; PS&#xff1a;喜歡的可以去買下他的課程&#xff0c;不貴&#xff0c;講的很細 To be cont…

手機連接windows遇到的問題及解決方法

文章目錄 寫在前面一、手機與windows 連接以后 無法在win端打開手機屏幕,提示801方法零、檢查連接方法一、系統修復方法二、斷開重連方法三、軟件更新方法四、關閉防火墻 寫在前面 本文主要記錄所遇到的問題以及解決方案&#xff0c;以備后用。 所用機型&#xff1a;win11 專業…

Spring Boot + MyBatis Plus 項目中,entity和 XML 映射文件的查找機制

在 Spring Boot MyBatis - Plus 項目中&#xff0c;entity&#xff08;實體類&#xff09;和 XML 映射文件的查找機制有其默認規則&#xff0c;也可通過配置調整&#xff0c;以下詳細說明&#xff1a; 一、實體類&#xff08;entity&#xff09;的查找 MyBatis - Plus 能找到…

itvbox綠豆影視tvbox手機版影視APP源碼分享搭建教程

我們先來看看今天的主題&#xff0c;tvbox手機版&#xff0c;然后再看看如何搭建&#xff1a; 很多愛好者都希望搭建自己的影視平臺&#xff0c;那該如何搭建呢&#xff1f; 后端開發環境&#xff1a; 1.易如意后臺管理優化版源碼&#xff1b; 2.寶塔面板&#xff1b; 3.ph…

Vue Electron 使用來給若依系統打包成exe程序,出現登錄成功但是不跳轉頁面(已解決)

描述 用vue打成electron可執行exe程序時&#xff0c;發現個問題&#xff0c;一直登錄之后&#xff0c;頁面跳轉不了&#xff0c;其實后臺請求已成功發送 那么懷疑就是vue頁面跳轉的事情 解決 大部分vue 前段項目 會使用 js-cookie 這個庫 來操作瀏覽器的cookie 然而這個庫 …

Blob設置type為application/msword將document DOM節點轉換為Word(.doc,.docx),并下載到本地

core code // 導出為Word文檔downloadWord({ dom, fileName "", fileType "doc", l {} } {}) {l.show && l.show();// 獲取HTML內容const content dom.innerHTML;// 構建Word文檔的HTML結構const html <!DOCTYPE html><html>&l…

無需 Mac,使用Appuploader簡化iOS上架流程

作為開發者&#xff0c;尤其是從事跨平臺開發的團隊&#xff0c;iOS應用上架一直是一項繁瑣且挑戰重重的工作。盡管Flutter、React Native等框架使得我們可以在不同平臺之間共享代碼&#xff0c;iOS上架仍然是一個不可忽視的難題。因為它不僅僅涉及代碼構建&#xff0c;還涉及到…

【JVM】Java虛擬機(二)——垃圾回收

目錄 一、如何判斷對象可以回收 &#xff08;一&#xff09;引用計數法 &#xff08;二&#xff09;可達性分析算法 二、垃圾回收算法 &#xff08;一&#xff09;標記清除 &#xff08;二&#xff09;標記整理 &#xff08;三&#xff09;復制 &#xff08;四&#xff…

Android 實現可拖動的ImageView

Android 實現可拖動的ImageView 代碼實現&#xff1a; public class DraggableImageView extends AppCompatImageView {private float lastTouchX;private float lastTouchY;public DraggableImageView(Context context) {super(context);init();}public DraggableImageView(C…

微信小程序中wxs

一、先新建wxs文件subutil.wxs 1、寫過濾器 //return class var isClass function(val) {if (val 0) {return grid-item} else if (val 1) {return temperature-error-slot} else if (val 2) {return chargingCycles-error-slot} else {return unrecognized-slot} } 2、…

Nginx攻略

&#x1f916; 作者簡介&#xff1a;水煮白菜王&#xff0c;一位前端勸退師 &#x1f47b; &#x1f440; 文章專欄&#xff1a; 前端專欄 &#xff0c;記錄一下平時在博客寫作中&#xff0c;總結出的一些開發技巧和知識歸納總結?。 感謝支持&#x1f495;&#x1f495;&#…

常見系統設計

秒殺系統 前端層&#xff1a; 靜態資源緩存&#xff1a;通過CDN緩存商品圖片、頁面靜態HTML&#xff0c;減少回源請求。 請求合并&#xff1a;合并用戶頻繁刷新的請求&#xff08;如10秒內僅允許一次真實請求&#xff09;。 端側限流&#xff1a;通過JS或APP端限制用戶高頻點擊…

git撤回commit

最常見的幾種撤回方式&#xff1a; 目標使用命令是否保留修改撤回最后一次 commit&#xff0c;但保留代碼修改git reset --soft HEAD~1? 保留撤回最后一次 commit&#xff0c;并丟棄修改git reset --hard HEAD~1? 丟棄撤回某個 commit&#xff0c;但保留后續提交git revert …

docker 安裝運行mysql8.4.4

先前一直使用mysql5.7&#xff0c;最新公司新項目&#xff0c;無意翻閱看下5.x版本mysql官方已經不再支持&#xff0c;于是準備選用MySQL8&#xff0c;官方8.4版本是個長期支持版本&#xff0c;選則最新版本8.4.4&#xff0c;如下是MySQL官方對版本支持計劃 MySQL版本下載查看地…

[java八股文][MySQL面試篇]索引

索引是什么&#xff1f;有什么好處&#xff1f; 索引類似于書籍的目錄&#xff0c;可以減少掃描的數據量&#xff0c;提高查詢效率。 如果查詢的時候&#xff0c;沒有用到索引就會全表掃描&#xff0c;這時候查詢的時間復雜度是On如果用到了索引&#xff0c;那么查詢的時候&a…

低代碼平臺的版本管理深度解析

引言 在當今快速發展的軟件開發領域&#xff0c;低代碼平臺憑借其可視化界面和拖拽功能&#xff0c;極大地減少了手動編碼的工作量&#xff0c;顯著提高了開發效率和質量。它提供了豐富的預構建模塊、組件和服務&#xff0c;讓開發者能夠根據業務需求和邏輯進行組合與配置&…