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

面試對話標題自動總結

主要實現思路:每當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/84862.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/84862.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/84862.shtml

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

相關文章

降階法求解偏微分方程

求解給定的四個偏微分方程,采用降階法,令 v = u x v = u_x v=ux?,從而將原方程轉化為關于 v v v 的一階方程。 方程 u x y = 0 u_{xy} = 0 uxy?=0 令 v = u x v = u_x v=ux?,則方程變為 v y = 0 v_y = 0 vy?=0。解得 v = C 1 ( x ) v = C_1(x) v=C1?(x),即 u …

提的缺陷開發不改,測試該怎么辦?

經歷長時間的細致檢查&#xff0c;逐條執行數十條測試用例&#xff0c;終于發現一處疑似缺陷。截圖留存、粘貼日志&#xff0c;認真整理好各項信息&#xff0c;將它提交到缺陷管理系統。可不到五分鐘&#xff0c;這條缺陷就被打回了。開發人員給出的回復十分簡潔&#xff1a;“…

【Flutter】Widget、Element和Render的關系-Flutter三棵樹

【Flutter】Widget、Element和Render的關系-Flutter三棵樹 一、前言 在 Flutter 中&#xff0c;所謂的“三棵樹”是指&#xff1a; Widget Tree&#xff08;部件樹&#xff09;Element Tree&#xff08;元素樹&#xff09;Render Tree&#xff08;渲染樹&#xff09; 它們是…

IO之詳解cin(c++IO關鍵理解)

目錄 cin原理介紹 控制符(hex、oct、dec) cin如何檢查輸入 cin與字符串 cin.get(char ch) cin.get(void) istream &get(char*,int) istream &get(char*,int,char) istream &getline(char*,int); 遇到文件結尾EOF 無法完成一次完整輸入&#xff1a;設置f…

Bootstrap 5學習教程,從入門到精通, Bootstrap 5 分頁(Pagination)知識點及案例代碼(13)

Bootstrap 5 分頁&#xff08;Pagination&#xff09;知識點及案例代碼 Bootstrap 5 提供了強大的分頁組件&#xff0c;幫助開發者輕松實現分頁功能。以下是關于 Bootstrap 5 分頁的詳細語法知識點以及一個完整的案例代碼&#xff0c;包含詳細注釋&#xff0c;幫助初學者快速上…

Dina靶機滲透

1.信息查詢 1.1. Ip查詢 arp-scan -l 192.168.220.137 1.2. 端口收集 nmap -T4 -A -p- 192.168.220.137 1.3. 目錄掃描 dirsearch -u 192.168.220.137 -e* -i 200 通過訪問 robots.txt 文件發現有些禁止訪問得目錄 User-agent: *Disallow: /ange1Disallow: /angel1Dis…

通俗理解存儲過程注入

【通俗理解】存儲過程注入&#xff1a;SQL注入的“豪華升級版” 一、從廚房做菜說起&#xff1a;為什么需要存儲過程&#xff1f; 想象你經營一家連鎖餐廳&#xff0c;每道菜的制作流程非常復雜&#xff08;比如“招牌紅燒肉”需要先焯水、再炒糖色、最后慢燉1小時&#xff09…

【算法】基于中位數和MAD魯棒平均值計算算法

問題 在項目中&#xff0c;需要對異常值進行剔除&#xff0c;需要一種魯棒性比較好的方法&#xff0c;總結了一個實踐方法。 方法 基于中位數和MAD&#xff08;中位數絕對偏差&#xff09;的魯棒平均值計算算法的詳細過程&#xff0c;按照您要求的步驟分解&#xff1a; 算法…

插入點(position) 和對齊點(AlignmentPoint)詳解——CAD c#二次開發

在 AutoCAD 中&#xff0c;文本對象的位置由插入點&#xff08;position&#xff09; 和對齊點&#xff08;Alignment Point&#xff09; 共同控制&#xff0c;兩者的關系取決于文本的對齊方式。以下是詳細說明&#xff1a; 一、插入點與對齊點的定義 1. 插入點&#xff08;p…

QT打包應用

本次工程使用qt mingGw 64-bit 下面詳細介紹下windows平臺qt應用程序打包流程 1、先編譯項目的release版本生成exe文件 2、創建腳本運行windeployqt.exe完成打包 rundeploy.bat腳本 set PATHE:\Tools\qt\Qt5\5.14.2\mingw73_64\bin;%PATH% windeployqt.exe MyDesignWidget.ex…

[軟件測試]:什么是自動化測試?selenium+webdriver-manager的安裝,實現你的第一個腳本

目錄 1. 什么是自動化測試&#xff1f; 回歸測試 自動化分類 2. web自動化測試 3. selenium 1. 什么是自動化測試&#xff1f; 通過自動化測試工具&#xff0c;編寫腳本&#xff0c;自動執行測試用例&#xff0c;主要用于回歸測試&#xff0c;性能測試等重復測試任務 常…

使用OpenCV和Python進行圖像掩膜與直方圖分析

文章目錄 引言1. 準備工作2. 加載并顯示原始圖像3. 創建掩膜3. 應用掩膜5. 計算并顯示直方圖6. 結果分析7. 總結 引言 在圖像處理中&#xff0c;掩膜(Mask)是一個非常重要的概念&#xff0c;它允許我們選擇性地處理圖像的特定區域。今天&#xff0c;我將通過一個實際的例子來展…

Genio 1200 Evaluation MT8395平臺安裝ubuntu

官網教程&#xff1a; Getting Started with Genio 1200 Evaluation Kit — Ubuntu on Genio documentation Windows PC工具&#xff1a; Setup Tool Environment (Windows) — IoT Yocto documentation 鏡像下載地址&#xff1a; Install Ubuntu on MediaTek Genio | Ubu…

如何畫好架構圖:架構思維的三大底層邏輯

&#x1f449;目錄 0 前言 1 宏觀 2 中觀 3 微觀 4 補充 俗話說&#xff0c;一圖勝千言。日常工作中&#xff0c;當我們要表達自己的設計思路的時候&#xff0c;會畫各式各樣的圖。但因為各自知識儲備的差異&#xff0c;思維的差異&#xff0c;不同類型的系統側重的架構設計點也…

Spring MVC擴展消息轉換器-->格式化時間信息

Spring MVC 的消息轉換器的作用&#xff1a;在 HTTP 請求/響應與 Java 對象之間進行轉換 可以自行擴展消息轉換器 一、創建對象映射規則 package com.sky.json;import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Objec…

Elasticsearch 的自動補全以及RestAPI的使用

Elasticsearch 提供了強大的自動補全 (Autocomplete) 功能,以下為一個基礎的自動補全DSL語句 {"suggest": {"my_suggestion": { // 自定義建議器名稱&#xff0c;可按需修改"text": "ap", // 用戶輸入的前綴&#xff08;如搜索框…

1.4、SDH網狀拓撲

鏈形網星形網樹形網環形網網孔形網 1.鏈形拓撲 結構&#xff1a; 節點像鏈條一樣首尾依次串聯連接。信號從一個節點傳到下一個節點&#xff0c;直至終點。 特點&#xff1a; 簡單經濟&#xff1a; 結構最簡單&#xff0c;成本最低&#xff0c;適用于沿線覆蓋&#xff08;如鐵…

如何在 ArcGIS 中使用 Microsoft Excel 文件_20250614

如何在 ArcGIS 中使用 Microsoft Excel 文件 軟件版本&#xff1a;win11; ArcGIS10.8; Office2024 1. 確認 ArcGIS 10.8 對 .xlsx 文件的支持 ArcGIS 10.8 支持 .xlsx 文件&#xff08;Excel 2007 及以上格式&#xff09;&#xff0c;但需要安裝 Microsoft Access Database …

Python----OpenCV(圖像處理——圖像的多種屬性、RGB與BGR色彩空間、HSB、HSV與HSL、ROI區域)

Python----計算機視覺處理&#xff08;opencv&#xff1a;像素&#xff0c;RGB顏色&#xff0c;圖像的存儲&#xff0c;opencv安裝&#xff0c;代碼展示&#xff09; Python----計算機視覺處理&#xff08;Opencv&#xff1a;圖片顏色識別&#xff1a;RGB顏色空間&#xff0c;…

java設計模式[1]之設計模式概覽

文章目錄 設計模式什么是設計模式為什么要學習設計模式設計模式的設計原則設計模式的分類 設計模式 什么是設計模式 設計模式是前人根據經驗的總結&#xff0c;是軟件開發中的最佳實踐&#xff0c;幫助開發者在面對復雜設計問題時提供有效的解決方案。設計模式不僅僅只是一種…