8 Commits

Author SHA1 Message Date
5711d611f2 修改打包配置 2025-09-26 12:42:04 +08:00
d3b5ca0033 优化代码 2025-09-21 21:19:44 +08:00
df5aa0b9c6 优化代码 2025-09-20 22:24:07 +08:00
08b4b8b206 优化代码 2025-09-20 21:43:36 +08:00
8b357fbb93 优化代码 2025-09-19 15:19:41 +08:00
a384bbfd16 修改AI面试相关内容 2025-09-17 21:36:09 +08:00
7f24d65d76 添加分类的controller 2025-09-14 22:21:03 +08:00
d14b46d007 修改代码 2025-09-11 22:33:53 +08:00
119 changed files with 3293 additions and 1197 deletions

0
.gitignore vendored Normal file → Executable file
View File

0
HELP.md Normal file → Executable file
View File

0
LICENSE Normal file → Executable file
View File

0
README.md Normal file → Executable file
View File

View File

@@ -1,135 +0,0 @@
<template>
<div class="dashboard-container">
<!-- 欢迎横幅 -->
<el-card shadow="never" class="welcome-banner">
<div class="welcome-content">
<div class="welcome-text">
<h2>欢迎回来</h2>
<p>准备好开始您的下一次模拟面试了吗在这里管理您的题库不断提升面试技巧</p>
</div>
<img src="/src/assets/dashboard-hero.svg" alt="仪表盘插图" class="welcome-illustration" />
</div>
</el-card>
<!-- 功能导航 -->
<div class="feature-grid">
<router-link to="/interview" class="feature-card-link">
<el-card shadow="hover" class="feature-card">
<div class="card-content">
<el-icon class="card-icon" style="background-color: #ecf5ff; color: #409eff;"><ChatLineRound /></el-icon>
<div class="text-content">
<h3>开始模拟面试</h3>
<p>上传简历与AI进行实战演练</p>
</div>
</div>
</el-card>
</router-link>
<router-link to="/question-bank" class="feature-card-link">
<el-card shadow="hover" class="feature-card">
<div class="card-content">
<el-icon class="card-icon" style="background-color: #f0f9eb; color: #67c23a;"><MessageBox /></el-icon>
<div class="text-content">
<h3>题库管理</h3>
<p>新增编辑和导入您的面试题库</p>
</div>
</div>
</el-card>
</router-link>
<router-link to="/history" class="feature-card-link">
<el-card shadow="hover" class="feature-card">
<div class="card-content">
<el-icon class="card-icon" style="background-color: #fdf6ec; color: #e6a23c;"><Finished /></el-icon>
<div class="text-content">
<h3>面试历史</h3>
<p>查看过往的面试记录与AI复盘报告</p>
</div>
</div>
</el-card>
</router-link>
</div>
</div>
</template>
<script setup>
// 导入Element Plus图标
import { ChatLineRound, MessageBox, Finished } from '@element-plus/icons-vue';
</script>
<style scoped>
/* 仪表盘容器 */
.dashboard-container {
padding: 10px;
}
/* 欢迎横幅 */
.welcome-banner {
border: none;
margin-bottom: 20px;
}
.welcome-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.welcome-text h2 {
font-size: 1.8em;
margin-top: 0;
color: #303133;
}
.welcome-text p {
color: #606266;
font-size: 1.1em;
}
.welcome-illustration {
width: 200px;
height: auto;
}
/* 功能网格布局 */
.feature-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
}
.feature-card-link {
text-decoration: none;
}
.feature-card .card-content {
display: flex;
align-items: center;
padding: 20px;
transition: transform 0.3s, box-shadow 0.3s;
}
.feature-card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}
.card-icon {
font-size: 32px;
padding: 15px;
border-radius: 50%;
margin-right: 20px;
}
.text-content h3 {
margin: 0 0 8px 0;
color: #303133;
font-size: 1.1em;
}
.text-content p {
margin: 0;
color: #909399;
font-size: 0.9em;
}
</style>

0
mvnw vendored Normal file → Executable file
View File

0
mvnw.cmd vendored Normal file → Executable file
View File

13
pom.xml Normal file → Executable file
View File

@@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.10-SNAPSHOT</version>
<version>3.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qingqiu</groupId>
@@ -43,6 +43,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- aop和aspect -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId> <!-- 用于 WebClient -->
@@ -145,7 +150,13 @@
</dependencyManagement>
<build>
<finalName>ai-interview</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.5.0</version>
</plugin>
<!-- maven 打包时跳过测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>

0
sql/.idea/.gitignore generated vendored Normal file → Executable file
View File

View File

View File

View File

@@ -1,7 +1,11 @@
package com.qingqiu.interview.ai.factory;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.ai.service.AIClientService;
public interface AIClientFactory {
AIClientService createAIClient();
// 支持的提供商
LLMProvider getSupportedProvider();
}

View File

@@ -1,24 +1,32 @@
package com.qingqiu.interview.ai.factory;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.ai.service.AIClientService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class AIClientManager {
private final Map<String, AIClientFactory> factories;
private final Map<LLMProvider, AIClientFactory> factories;
public AIClientManager(Map<String, AIClientFactory> factories) {
this.factories = factories;
public AIClientManager(List<AIClientFactory> strategies) {
this.factories = strategies.stream()
.collect(Collectors.toMap(
AIClientFactory::getSupportedProvider,
Function.identity()
));
}
public AIClientService getClient(String aiType) {
String factoryName = aiType + "ClientFactory";
AIClientFactory factory = factories.get(factoryName);
public AIClientService getClient(LLMProvider provider) {
// String factoryName = aiType + "ClientFactory";
AIClientFactory factory = factories.get(provider);
if (factory == null) {
throw new IllegalArgumentException("不支持的AI type: " + aiType);
throw new IllegalArgumentException("不支持的AI type: " + provider);
}
return factory.createAIClient();
}

View File

@@ -1,5 +1,6 @@
package com.qingqiu.interview.ai.factory;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.ai.service.AIClientService;
import com.qingqiu.interview.ai.service.impl.DeepSeekClientServiceImpl;
import com.qingqiu.interview.common.utils.SpringApplicationContextUtil;
@@ -11,4 +12,9 @@ public class DeepSeekClientFactory implements AIClientFactory{
public AIClientService createAIClient() {
return SpringApplicationContextUtil.getBean(DeepSeekClientServiceImpl.class);
}
@Override
public LLMProvider getSupportedProvider() {
return LLMProvider.DEEPSEEK;
}
}

View File

@@ -1,5 +1,6 @@
package com.qingqiu.interview.ai.factory;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.ai.service.AIClientService;
import com.qingqiu.interview.ai.service.impl.QwenClientServiceImpl;
import com.qingqiu.interview.common.utils.SpringApplicationContextUtil;
@@ -11,4 +12,9 @@ public class QwenClientFactory implements AIClientFactory{
public AIClientService createAIClient() {
return SpringApplicationContextUtil.getBean(QwenClientServiceImpl.class);
}
@Override
public LLMProvider getSupportedProvider() {
return LLMProvider.QWEN;
}
}

View File

View File

@@ -4,6 +4,7 @@ import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.ResponseFormat;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
@@ -42,6 +43,7 @@ public class QwenClientServiceImpl extends AIClientService {
.model(QWEN_PLUS_LATEST) // 可根据需要更换模型
.messages(messages)
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.responseFormat(ResponseFormat.builder().type(ResponseFormat.JSON_OBJECT).build())
.apiKey(apiKey)
.build();

View File

@@ -0,0 +1,15 @@
package com.qingqiu.interview.annotation;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 12:58
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AiChatLog {
}

View File

@@ -0,0 +1,71 @@
package com.qingqiu.interview.aspect;
import com.qingqiu.interview.dto.ChatDTO;
import com.qingqiu.interview.entity.AiSessionLog;
import com.qingqiu.interview.service.IAiSessionLogService;
import com.qingqiu.interview.vo.ChatVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* <h1>
* ai聊天的切面
* </h1>
*
* @author qingqiu
* @date 2025/9/18 13:00
*/
@Aspect
@Component
public class AiChatLogAspect {
@Resource
private IAiSessionLogService aiSessionLogService;
public AiChatLogAspect() {
}
@Pointcut("@annotation(com.qingqiu.interview.annotation.AiChatLog)")
public void logPointCut() {
}
@Around("logPointCut()")
@Transactional(rollbackFor = Exception.class)
public Object around(ProceedingJoinPoint point) throws Throwable {
Object[] args = point.getArgs();
ChatDTO arg = (ChatDTO) args[0];
if (StringUtils.isNoneBlank(arg.getSessionId())) {
AiSessionLog userSessionLog = new AiSessionLog();
userSessionLog
.setRole(arg.getRole())
.setDataType(arg.getDataType())
.setContent(arg.getContent())
.setToken(arg.getSessionId())
;
aiSessionLogService.save(userSessionLog);
}
Object result = point.proceed();
ChatVO chatVO = (ChatVO) result;
if (StringUtils.isNotBlank(chatVO.getSessionId())) {
AiSessionLog aiSessionLog = new AiSessionLog();
aiSessionLog
.setRole(chatVO.getRole())
.setContent(chatVO.getContent())
.setToken(chatVO.getSessionId())
;
aiSessionLogService.save(aiSessionLog);
}
return result;
}
}

View File

@@ -0,0 +1,17 @@
package com.qingqiu.interview.common.constants;
import java.math.BigDecimal;
/**
* <h1>公共常量</h1>
* @author huangpeng
* @date 2025/9/11 09:30
*/
public class CommonConstant {
public static final Integer ZERO = 0;
public static final Integer ONE = 1;
public static final Long ROOT_PARENT_ID = 0L;
public static final Integer MAX_TOKEN = 64000;
public static final BigDecimal DEFAULT_TRUNCATE_RATIO = new BigDecimal("0.1");
}

View File

@@ -1,4 +1,4 @@
package com.qingqiu.interview.dto;
package com.qingqiu.interview.common.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;

View File

@@ -0,0 +1,63 @@
package com.qingqiu.interview.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* <h1></h1>
*
* @author huangpeng
* @date 2025/9/11 09:49
*/
@Getter
@AllArgsConstructor
public enum CommonStateEnum {
/**
* 禁用状态
*/
DISABLED(0, "禁用"),
/**
* 启用状态
*/
ENABLED(1, "启用"),
;
/**
* 状态码
*/
private final Integer code;
private final String value;
/**
* 根据状态码获取枚举
*/
public static CommonStateEnum getByCode(Integer code) {
if (code == null) {
return null;
}
for (CommonStateEnum state : values()) {
if (state.getCode().equals(code)) {
return state;
}
}
return null;
}
/**
* 根据标识获取枚举
*/
public static CommonStateEnum getByValue(String value) {
if (value == null || value.isEmpty()) {
return null;
}
for (CommonStateEnum state : values()) {
if (state.getValue().equalsIgnoreCase(value)) {
return state;
}
}
return null;
}
}

View File

@@ -0,0 +1,33 @@
package com.qingqiu.interview.common.enums;
import lombok.Getter;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 16:43
*/
@Getter
public enum DocumentParserProvider {
PDF("pdf"),
MARKDOWN("md"),
;
private final String code;
DocumentParserProvider(String code) {
this.code = code;
}
public static DocumentParserProvider fromCode(String code) {
for (DocumentParserProvider provider : values()) {
if (provider.getCode().equals(code)) {
return provider;
}
}
throw new IllegalArgumentException("Unknown provider: " + code);
}
}

View File

@@ -0,0 +1,30 @@
package com.qingqiu.interview.common.enums;
import lombok.Getter;
@Getter
public enum LLMProvider {
OPEN_AI("openai"),
CLAUDE("claude"),
GEMINI("gemini"),
DEEPSEEK("deepSeek"),
OLLAMA("ollama"),
QWEN("qwen"),
;
private final String code;
LLMProvider(String code) {
this.code = code;
}
public static LLMProvider fromCode(String code) {
for (LLMProvider provider : values()) {
if (provider.getCode().equals(code)) {
return provider;
}
}
throw new IllegalArgumentException("Unknown provider: " + code);
}
}

View File

View File

View File

0
src/main/java/com/qingqiu/interview/common/res/R.java Normal file → Executable file
View File

View File

View File

View File

@@ -2,6 +2,10 @@ package com.qingqiu.interview.common.utils;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.tokenizers.Tokenizer;
import com.alibaba.dashscope.tokenizers.TokenizerFactory;
import java.util.List;
public class AIUtils {
@@ -23,4 +27,15 @@ public class AIUtils {
public static Message createSystemMessage(String prompt) {
return createMessage(Role.SYSTEM.getValue(), prompt);
}
/**
* 获取prompt的token数
* @param prompt 输入
* @return tokens
*/
public static Integer getPromptTokens(String prompt) {
Tokenizer tokenizer = TokenizerFactory.qwen();
List<Integer> integers = tokenizer.encodeOrdinary(prompt);
return integers.size();
}
}

View File

@@ -0,0 +1,63 @@
package com.qingqiu.interview.common.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TreeUtil {
/**
* 通用树形结构构建方法
*/
public static <T, ID> List<T> buildTree(List<T> list,
Function<T, ID> idGetter,
Function<T, ID> parentIdGetter,
Function<T, List<T>> childrenSetter,
ID rootParentId) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
// 按父ID分组
Map<ID, List<T>> parentMap = list.stream()
.collect(Collectors.groupingBy(parentIdGetter));
// 设置子节点
list.forEach(item -> {
List<T> children = parentMap.get(idGetter.apply(item));
if (children != null && !children.isEmpty()) {
childrenSetter.apply(item).addAll(children);
}
});
// 返回根节点
return parentMap.get(rootParentId);
}
/**
* 扁平化树形结构
*/
public static <T> List<T> flattenTree(List<T> tree, Function<T, List<T>> childrenGetter) {
List<T> result = new ArrayList<>();
flattenTreeRecursive(tree, childrenGetter, result);
return result;
}
private static <T> void flattenTreeRecursive(List<T> nodes,
Function<T, List<T>> childrenGetter,
List<T> result) {
if (nodes == null) return;
for (T node : nodes) {
result.add(node);
List<T> children = childrenGetter.apply(node);
if (children != null && !children.isEmpty()) {
flattenTreeRecursive(children, childrenGetter, result);
}
}
}
}

View File

View File

View File

View File

View File

@@ -1,10 +1,22 @@
package com.qingqiu.interview.controller;
import com.alibaba.dashscope.common.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.entity.AiSessionLog;
import com.qingqiu.interview.service.IAiSessionLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* ai会话记录 前端控制器
@@ -13,8 +25,22 @@ import org.springframework.web.bind.annotation.RestController;
* @author huangpeng
* @since 2025-08-30
*/
@Slf4j
@RestController
@RequestMapping("/ai-session-log")
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class AiSessionLogController {
private final IAiSessionLogService service;
@GetMapping("/list-by-session-id/{sessionId}")
public R<List<AiSessionLog>> list(@PathVariable String sessionId) {
return R.success(service.list(
new LambdaQueryWrapper<AiSessionLog>()
.eq(AiSessionLog::getToken, sessionId)
.ne(AiSessionLog::getRole, Role.SYSTEM.getValue())
));
}
}

View File

@@ -0,0 +1,36 @@
package com.qingqiu.interview.controller;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.dto.ChatDTO;
import com.qingqiu.interview.dto.InterviewStartRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* <h1>AI聊天控制器</h1>
*
* @author qingqiu
* @date 2025/9/18 12:11
*/
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
public class ChatController {
/**
* 创建聊天
* @return
*/
@PostMapping("/send")
public R<?> createChat(@RequestBody ChatDTO dto) {
return R.success();
}
@PostMapping("/interview/create")
public R<?> createInterview(@RequestParam("resume") MultipartFile resume,
@Validated @ModelAttribute InterviewStartRequest request) {
return R.success();
}
}

View File

@@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RestController;
* 仪表盘数据统计接口
*/
@RestController
@RequestMapping("/api/v1/dashboard")
@RequestMapping("/dashboard")
@RequiredArgsConstructor
public class DashboardController {

View File

@@ -1,58 +1,125 @@
package com.qingqiu.interview.controller;
import com.qingqiu.interview.dto.*;
import com.qingqiu.interview.entity.InterviewSession;
import com.qingqiu.interview.service.InterviewService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* 面试流程相关接口
*/
@RestController
@RequestMapping("/api/v1/interview")
@RequiredArgsConstructor
public class InterviewController {
private final InterviewService interviewService;
/**
* 开始新的面试会话
*/
@PostMapping("/start")
public ApiResponse<InterviewResponse> startInterview(
@RequestParam("resume") MultipartFile resume,
@Validated @ModelAttribute InterviewStartRequest request) throws IOException {
InterviewResponse response = interviewService.startInterview(resume, request);
return ApiResponse.success(response);
}
/**
* 继续面试会话(用户回答)
*/
@PostMapping("/chat")
public ApiResponse<InterviewResponse> continueInterview(@Validated @RequestBody ChatRequest request) {
InterviewResponse response = interviewService.continueInterview(request);
return ApiResponse.success(response);
}
/**
* 获取所有面试会话列表
*/
@PostMapping("/get-history-list")
public ApiResponse<java.util.List<InterviewSession>> getInterviewHistoryList() {
return ApiResponse.success(interviewService.getInterviewSessions());
}
/**
* 获取单次面试的详细复盘报告
*/
@PostMapping("/get-report-detail")
public ApiResponse<InterviewReportResponse> getInterviewReportDetail(@RequestBody SessionRequest request) {
return ApiResponse.success(interviewService.getInterviewReport(request.getSessionId()));
}
}
package com.qingqiu.interview.controller;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.dto.*;
import com.qingqiu.interview.entity.InterviewMessage;
import com.qingqiu.interview.entity.InterviewQuestionProgress;
import com.qingqiu.interview.entity.InterviewSession;
import com.qingqiu.interview.service.InterviewService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/19 16:13
*/
@Slf4j
@RestController
@RequestMapping("/interview")
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewController {
private final InterviewService interviewService;
/**
* 开始面试
*
* @return 包含会话ID的会话信息
*/
@PostMapping("/start")
public R<InterviewSession> start(@RequestPart("resume") MultipartFile resume,
@RequestPart("interviewStartDto") InterviewStartRequest request) {
// log.info("接受的数据: {}", JSONObject.toJSONString(request));
// return R.success();
try {
InterviewSession session = interviewService.startInterview(resume, request);
return R.success(session);
} catch (Exception e) {
log.error("开始面试失败", e);
return R.error("开始面试失败:" + e.getMessage());
}
}
/**
* 获取下一个问题
*
* @param sessionId 会话ID
* @return 下一个问题
*/
@GetMapping("/next-question/{sessionId}/{progressId}")
public R<InterviewMessage> getNextQuestion(@PathVariable String sessionId,
@PathVariable Long progressId) {
try {
InterviewMessage nextQuestion = interviewService.getNextQuestion(sessionId, progressId);
if (nextQuestion == null) {
return R.success(null, "所有问题已回答完毕!");
}
return R.success(nextQuestion);
} catch (Exception e) {
// log.error("获取下一题失败", e);
return R.error("获取下一题失败:" + e.getMessage());
}
}
/**
* 提交答案
*
* @param submitDto 包含进度ID和答案
* @return 对当前问题的评估
*/
@PostMapping("/submit-answer")
public R<InterviewQuestionProgress> submitAnswer(@RequestBody SubmitAnswerDTO submitDto) {
try {
InterviewQuestionProgress result = interviewService.submitAnswer(submitDto);
return R.success(result);
} catch (Exception e) {
// log.error("提交答案失败", e);
return R.error("提交答案失败:" + e.getMessage());
}
}
/**
* 结束面试并获取最终报告
*
* @param sessionId 会话ID
* @return 包含最终报告的会话信息
*/
@PostMapping("/{sessionId}/end")
public R<InterviewSession> endInterview(@PathVariable String sessionId) {
try {
InterviewSession finalSession = interviewService.endInterview(sessionId);
return R.success(finalSession);
} catch (Exception e) {
// log.error("结束面试失败", e);
return R.error("结束面试失败:" + e.getMessage());
}
}
@PostMapping("/get-history-list")
public R<List<InterviewSession>> getHistoryList() {
try {
List<InterviewSession> historyList = interviewService.list();
return R.success(historyList);
} catch (Exception e) {
// log.error("获取面试历史列表失败", e);
return R.error("获取面试历史列表失败:" + e.getMessage());
}
}
/**
* 获取单次面试的详细复盘报告
*/
@PostMapping("/get-report-detail/{sessionId}")
public R<InterviewReportResponse> getInterviewReportDetail(@PathVariable String sessionId) {
return R.success(interviewService.getInterviewReport(sessionId));
}
}

View File

@@ -0,0 +1,42 @@
package com.qingqiu.interview.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.entity.InterviewMessage;
import com.qingqiu.interview.service.InterviewMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/21 11:59
*/
@Slf4j
@RestController
@RequestMapping("/interview-message")
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewMessageController {
public final InterviewMessageService service;
@GetMapping("/list-by-session-id/{sessionId}")
public R<List<InterviewMessage>> listBySessionId(@PathVariable String sessionId) {
return R.success(
service.list(
new LambdaQueryWrapper<InterviewMessage>()
.eq(InterviewMessage::getSessionId, sessionId)
.orderByAsc(InterviewMessage::getCreatedTime)
)
);
}
}

View File

@@ -19,7 +19,7 @@ import org.springframework.web.bind.annotation.RestController;
* @since 2025-08-30
*/
@RestController
@RequestMapping("/api/v1/interview-question-progress")
@RequestMapping("/interview-question-progress")
@RequiredArgsConstructor
public class InterviewQuestionProgressController {

View File

@@ -0,0 +1,162 @@
package com.qingqiu.interview.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.dto.QuestionCategoryDTO;
import com.qingqiu.interview.dto.QuestionCategoryPageParams;
import com.qingqiu.interview.entity.QuestionCategory;
import com.qingqiu.interview.service.IQuestionCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/question-category")
@RequiredArgsConstructor
public class QuestionCategoryController {
@Lazy
private final IQuestionCategoryService questionCategoryService;
/**
* 获取分类树列表
*/
@GetMapping("/tree-list")
public R<List<QuestionCategory>> getTreeList() {
List<QuestionCategory> list = questionCategoryService.getTreeList();
return R.success(list);
}
@GetMapping("/question-tree-list")
public R<List<QuestionCategory>> getQuestionTreeList() {
// List<QuestionCategory> list = questionCategoryService.getQuestionTreeList();
return R.success();
}
/**
* 获取分类选项
*/
@GetMapping("/options")
public R<List<QuestionCategory>> getOptions() {
try {
List<QuestionCategory> options = questionCategoryService.getOptions();
return R.success(options);
} catch (Exception e) {
log.error("获取分类选项失败", e);
return R.error("获取分类选项失败");
}
}
/**
* 获取分类详情
*/
@GetMapping("/{id}")
public R<QuestionCategory> getDetail(@PathVariable Long id) {
try {
QuestionCategory category = questionCategoryService.getCategoryDetail(id);
return R.success(category);
} catch (Exception e) {
log.error("获取分类详情失败", e);
return R.error("获取分类详情失败");
}
}
/**
* 分页查询分类
*/
@GetMapping("/page")
public R<Page<QuestionCategory>> getPage(QuestionCategoryPageParams query) {
try {
Page<QuestionCategory> pageR = questionCategoryService.getCategoryPage(query);
return R.success(pageR);
} catch (Exception e) {
log.error("分页查询分类失败", e);
return R.error("分页查询分类失败");
}
}
/**
* 创建分类
*/
@PostMapping
public R<Long> create(@Validated @RequestBody QuestionCategoryDTO dto) {
try {
Long id = questionCategoryService.createCategory(dto);
return R.success(id);
} catch (RuntimeException e) {
log.error("创建分类失败", e);
return R.error(e.getMessage());
} catch (Exception e) {
log.error("创建分类失败", e);
return R.error("创建分类失败");
}
}
/**
* 更新分类
*/
@PostMapping("/update")
public R<Void> update(@RequestBody QuestionCategoryDTO dto) {
try {
questionCategoryService.updateCategory(dto);
return R.success();
} catch (RuntimeException e) {
log.error("更新分类失败", e);
return R.error(e.getMessage());
} catch (Exception e) {
log.error("更新分类失败", e);
return R.error("更新分类失败");
}
}
/**
* 删除分类
*/
@DeleteMapping("/{id}")
public R<Void> delete(@PathVariable Long id) {
try {
questionCategoryService.deleteCategory(id);
return R.success();
} catch (RuntimeException e) {
log.error("删除分类失败", e);
return R.error(e.getMessage());
} catch (Exception e) {
log.error("删除分类失败", e);
return R.error("删除分类失败");
}
}
/**
* 更新分类状态
*/
@PatchMapping("/{id}/state")
public R<Void> updateState(@PathVariable Long id, @RequestParam Integer state) {
try {
questionCategoryService.updateState(id, state);
return R.success();
} catch (Exception e) {
log.error("更新分类状态失败", e);
return R.error("更新分类状态失败");
}
}
/**
* 搜索分类
*/
@GetMapping("/search")
public R<List<QuestionCategory>> search(@RequestParam String name) {
try {
List<QuestionCategory> res = questionCategoryService.searchByName(name);
return R.success(res);
} catch (Exception e) {
log.error("搜索分类失败", e);
return R.error("搜索分类失败");
}
}
}

View File

@@ -3,21 +3,24 @@ package com.qingqiu.interview.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingqiu.interview.common.res.R;
import com.qingqiu.interview.dto.ApiResponse;
import com.qingqiu.interview.dto.QuestionOptionsDTO;
import com.qingqiu.interview.dto.QuestionPageParams;
import com.qingqiu.interview.entity.Question;
import com.qingqiu.interview.service.QuestionService;
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/**
* 题库管理相关接口
*/
@RestController
@RequestMapping("/api/v1/question")
@RequestMapping("/question")
@RequiredArgsConstructor
public class QuestionController {
@@ -76,4 +79,9 @@ public class QuestionController {
questionService.useAiCheckQuestionData();
return R.success();
}
@PostMapping("/tree-list-category")
public R<List<QuestionAndCategoryTreeListVO>> getTreeListCategory(@RequestBody QuestionOptionsDTO dto) {
return R.success(questionService.getTreeListCategory(dto));
}
}

View File

View File

@@ -0,0 +1,28 @@
package com.qingqiu.interview.dto;
import com.qingqiu.interview.common.enums.LLMProvider;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 12:54
*/
@Data
@Accessors(chain = true)
public class ChatDTO {
/** 会话id */
private String sessionId;
/** 调用模型 */
private String aiModel = LLMProvider.DEEPSEEK.getCode();
/** 输入内容 */
private String content;
/** 0 普通会话 1 面试会话 */
private Integer dataType;
/** 角色类型user/assistant/system */
private String role;
}

View File

View File

View File

View File

View File

@@ -1,15 +1,29 @@
package com.qingqiu.interview.dto;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.util.List;
@Data
public class InterviewStartRequest {
@NotBlank(message = "候选人姓名不能为空")
private String candidateName;
private List<QuestionAndCategoryTreeListVO> selectedNodes;
@NotBlank(message = "面试类型不能为空")
private String model;
/** 选择的AI模型 */
private String aiModel = LLMProvider.QWEN.getCode();
/** 生成的面试题目数量 */
private Integer totalQuestions = 10;
// 简历文件通过MultipartFile单独传递
}

View File

@@ -0,0 +1,38 @@
package com.qingqiu.interview.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* <h1></h1>
*
* @author huangpeng
* @date 2025/9/11 09:39
*/
@Data
public class QuestionCategoryDTO {
private Long id;
@NotBlank(message = "分类名称不能为空")
private String name;
@NotNull(message = "父级分类ID不能为空")
private Long parentId;
@NotNull(message = "排序不能为空")
private Integer sort;
@NotNull(message = "状态不能为空")
private Integer state;
private String ancestor;
private Integer level;
/**
* 父分类名称(用于前端显示)
*/
private String parentName;
}

View File

@@ -0,0 +1,48 @@
package com.qingqiu.interview.dto;
import com.qingqiu.interview.common.dto.PageBaseParams;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <h1></h1>
*
* @author huangpeng
* @date 2025/9/11 09:40
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class QuestionCategoryPageParams extends PageBaseParams {
/**
* 分类名称(模糊查询)
*/
private String name;
/**
* 状态0禁用1启用
*/
private Integer state;
/**
* 父级分类ID
*/
private Long parentId;
/**
* 层级
*/
private Integer level;
/**
* 是否包含子分类
*/
private Boolean includeChildren = false;
/**
* 是否只返回启用状态的分类
*/
private Boolean onlyEnabled = false;
}

View File

@@ -0,0 +1,17 @@
package com.qingqiu.interview.dto;
import lombok.Data;
import java.util.List;
@Data
public class QuestionOptionsDTO {
/** 分类id */
private List<Long> categoryIds;
/** 难度 */
private String difficulty;
}

View File

@@ -1,5 +1,6 @@
package com.qingqiu.interview.dto;
import com.qingqiu.interview.common.dto.PageBaseParams;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@@ -8,7 +9,9 @@ import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class QuestionPageParams extends PageBaseParams{
public class QuestionPageParams extends PageBaseParams {
private String content;
private Long categoryId;
}

View File

@@ -1,5 +1,6 @@
package com.qingqiu.interview.dto;
import com.qingqiu.interview.common.dto.PageBaseParams;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@@ -7,6 +8,6 @@ import lombok.experimental.Accessors;
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class QuestionProgressPageParams extends PageBaseParams{
public class QuestionProgressPageParams extends PageBaseParams {
private String questionName;
}

View File

View File

View File

@@ -0,0 +1,43 @@
package com.qingqiu.interview.dto;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serial;
import java.io.Serializable;
/**
* <h1>
* 开始面试请求的数据传输对象
* </h1>
*
* @author qingqiu
* @date 2025/9/19 16:03
*/
@Data
@Accessors(chain = true)
public class StartInterviewDTO implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 候选人姓名
*/
private String candidateName;
/**
* 简历完整内容或简历文件URL
*/
private String resumeContent;
/**
* 指定使用的AI模型
*/
private String aiModel;
/**
* 计划提问总数
*/
private Integer totalQuestions;
}

View File

@@ -0,0 +1,33 @@
package com.qingqiu.interview.dto;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serial;
import java.io.Serializable;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/19 16:04
*/
@Data
@Accessors(chain = true)
public class SubmitAnswerDTO implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private String sessionId;
/**
* 当前问题的进度ID (interview_question_progress.id)
*/
private Long progressId;
/**
* 用户的回答内容
*/
private String answer;
}

View File

@@ -5,6 +5,7 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
@@ -22,6 +23,7 @@ import java.time.LocalDateTime;
@TableName("ai_session_log")
public class AiSessionLog implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
@@ -32,6 +34,11 @@ public class AiSessionLog implements Serializable {
*/
private String role;
/**
* 数据类型 0 普通会话 1 面试会话
*/
private Integer dataType;
/**
* 输入内容
*/
@@ -54,5 +61,8 @@ public class AiSessionLog implements Serializable {
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedTime;
@TableLogic
private Integer deleted;
}

View File

View File

@@ -28,8 +28,8 @@ public class InterviewMessage {
@TableField("content")
private String content;
@TableField("question_id")
private Long questionId;
@TableField("question_progress_id")
private Long questionProgressId;
@TableField("message_order")
private Integer messageOrder;

View File

@@ -33,6 +33,15 @@ public class InterviewQuestionProgress {
@TableField("question_content")
private String questionContent;
/** 问题序号 */
private Integer questionIndex;
/** 答题耗时(秒) */
private Long timeTaken;
/** 详细评估信息 */
private String evaluationDetails;
/**
* 面试会话ID
*/

View File

@@ -33,9 +33,19 @@ public class InterviewSession implements Serializable {
@TableField("extracted_skills")
private String extractedSkills;
@TableField("interview_type")
private String interviewType;
@TableField("estimated_duration")
private Integer estimatedDuration;
@TableField("current_question_id")
private Long currentQuestionId;
@TableField("ai_model")
private String aiModel;
@TableField("model")
private String model;
@TableField("status")
private String status;

View File

@@ -19,8 +19,11 @@ public class Question {
@TableField("content")
private String content;
@TableField("category")
private String category;
@TableField("category_id")
private Long categoryId;
@TableField("category_name")
private String categoryName;
@TableField("difficulty")
private String difficulty;

View File

@@ -1,14 +1,14 @@
package com.qingqiu.interview.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 题型分类
@@ -25,7 +25,7 @@ public class QuestionCategory implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
@TableId(type = IdType.AUTO)
private Long id;
/**
@@ -33,16 +33,60 @@ public class QuestionCategory implements Serializable {
*/
private String name;
/**
* 上级id
*/
private Long parentId;
/**
* 层级
*/
private Integer level;
/**
* 上级序列
*/
private String ancestor;
/**
* 排序
*/
private Integer sort;
/**
* 状态 0 禁用 1 启用
*/
private Integer state;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createdTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedTime;
@TableLogic
private Integer deleted;
/**
* 子分类列表(非数据库字段)
*/
@TableField(exist = false)
private List<QuestionCategory> children;
/**
* 子分类数量(非数据库字段)
*/
@TableField(exist = false)
private Integer childrenCount;
/**
* 父分类名称(非数据库字段,用于显示)
*/
@TableField(exist = false)
private String parentName;
}

View File

View File

View File

View File

@@ -2,6 +2,9 @@ package com.qingqiu.interview.mapper;
import com.qingqiu.interview.entity.QuestionCategory;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
@@ -12,5 +15,5 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
* @since 2025-09-08
*/
public interface QuestionCategoryMapper extends BaseMapper<QuestionCategory> {
List<QuestionCategory> batchFindByAncestorIdsUnion(@Param("searchIds") List<Long> searchIds);
}

View File

@@ -1,6 +1,9 @@
package com.qingqiu.interview.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingqiu.interview.dto.DashboardStatsResponse;
import com.qingqiu.interview.dto.QuestionPageParams;
import com.qingqiu.interview.entity.Question;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -18,6 +21,9 @@ public interface QuestionMapper extends BaseMapper<Question> {
Question selectByContent(@Param("content") String content);
List<com.qingqiu.interview.dto.DashboardStatsResponse.CategoryStat> countByCategory();
List<DashboardStatsResponse.CategoryStat> countByCategory();
Page<Question> queryPage(@Param("page") Page<Question> page, @Param("params") QuestionPageParams params);
}

View File

@@ -0,0 +1,29 @@
package com.qingqiu.interview.service;
import com.qingqiu.interview.dto.ChatDTO;
import com.qingqiu.interview.dto.InterviewStartRequest;
import com.qingqiu.interview.vo.ChatVO;
import org.springframework.web.multipart.MultipartFile;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 12:45
*/
public interface ChatService {
/**
* 创建普通会话
* @return sessionId
*/
ChatVO createChat(ChatDTO dto);
/**
* 创建面试会话
* @param resume 简历
* @param request 面试信息
* @return sessionId
*/
String createInterviewChat(MultipartFile resume, InterviewStartRequest request);
}

View File

View File

View File

@@ -15,4 +15,6 @@ import com.qingqiu.interview.entity.InterviewQuestionProgress;
*/
public interface IInterviewQuestionProgressService extends IService<InterviewQuestionProgress> {
Page<InterviewQuestionProgress> pageList(QuestionProgressPageParams params);
InterviewQuestionProgress getNextQuestion(String sessionId);
}

View File

@@ -1,7 +1,12 @@
package com.qingqiu.interview.service;
import com.qingqiu.interview.entity.QuestionCategory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qingqiu.interview.dto.QuestionCategoryDTO;
import com.qingqiu.interview.dto.QuestionCategoryPageParams;
import com.qingqiu.interview.entity.QuestionCategory;
import java.util.List;
/**
* <p>
@@ -12,5 +17,59 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2025-09-08
*/
public interface IQuestionCategoryService extends IService<QuestionCategory> {
/**
* 获取分类树列表
*/
List<QuestionCategory> getTreeList();
/**
* 获取分类选项(用于下拉选择)
*/
List<QuestionCategory> getOptions();
/**
* 创建分类
*/
Long createCategory(QuestionCategoryDTO dto);
/**
* 更新分类
*/
void updateCategory(QuestionCategoryDTO dto);
/**
* 删除分类
*/
void deleteCategory(Long id);
/**
* 更新分类状态
*/
void updateState(Long id, Integer state);
/**
* 获取分类详情
*/
QuestionCategory getCategoryDetail(Long id);
/**
* 分页查询分类
*/
Page<QuestionCategory> getCategoryPage(QuestionCategoryPageParams query);
/**
* 根据名称搜索分类
*/
List<QuestionCategory> searchByName(String name);
/**
* 检查分类名称是否重复
*/
boolean checkNameExists(String name, Long parentId, Long excludeId);
List<QuestionCategory> batchFindByAncestorIdsUnion(List<Long> searchIds);
}

View File

@@ -0,0 +1,61 @@
package com.qingqiu.interview.service;
import com.alibaba.fastjson2.JSONObject;
import com.qingqiu.interview.entity.InterviewQuestionProgress;
import com.qingqiu.interview.entity.InterviewSession;
import com.qingqiu.interview.entity.Question;
import java.util.List;
/**
* <h1>
* 面试接入AI的接口
* </h1>
*
* @author qingqiu
* @date 2025/9/19 16:48
*/
public interface InterviewAiService {
/**
* 从简历内容中提取技能列表
*
* @param resumeContent 简历文本
* @return 包含技能列表的JSON对象
*/
JSONObject extractSkillsFromResume(String resumeContent);
/**
* 根据技能动态生成面试题目
*
* @param skills 技能列表
* @param resumeContent 简历内容
* @param count 需要生成的题目数量
* @return 包含问题列表的JSON对象
*/
JSONObject generateQuestionsOfAi(String sessionId, List<String> skills, String resumeContent, int count);
JSONObject generateQuestionOfLocal(String sessionId, List<Question> questions, List<String> skills, String resumeContent, int count);
/**
* 评估用户的回答
*
* @param question 问题内容
* @param userAnswer 用户的回答
* @param context 可选的上下文(之前的问答历史)
* @return 包含评估结果的JSON对象
*/
JSONObject evaluateAnswer(String sessionId, String question, String userAnswer, List<InterviewQuestionProgress> context);
/**
* 生成最终的面试评估报告
*
* @param session 面试会话信息
* @param progressList 整个面试的问答记录
* @return 包含最终报告的JSON对象
*/
JSONObject generateFinalReport(InterviewSession session, List<InterviewQuestionProgress> progressList);
String generateFirstQuestion(String sessionId, String candidateName, String questionContent);
}

View File

@@ -0,0 +1,17 @@
package com.qingqiu.interview.service;
import com.qingqiu.interview.dto.InterviewStartRequest;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 16:37
*/
public interface InterviewChatService {
void startInterview(MultipartFile resume, InterviewStartRequest request) throws IOException;
}

View File

@@ -0,0 +1,13 @@
package com.qingqiu.interview.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qingqiu.interview.entity.InterviewMessage;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/21 12:00
*/
public interface InterviewMessageService extends IService<InterviewMessage> {
}

View File

@@ -1,654 +1,61 @@
package com.qingqiu.interview.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingqiu.interview.dto.*;
import com.qingqiu.interview.entity.*;
import com.qingqiu.interview.mapper.*;
import com.qingqiu.interview.service.llm.LlmService;
import com.qingqiu.interview.service.parser.DocumentParser;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.qingqiu.interview.common.constants.QwenModelConstant.QWEN_MAX;
@Slf4j
@Service
@RequiredArgsConstructor
public class InterviewService {
private final LlmService llmService; // Changed to a single service
private final List<DocumentParser> documentParserList;
private final QuestionMapper questionMapper;
private final InterviewSessionMapper sessionMapper;
private final InterviewMessageMapper messageMapper;
private final InterviewEvaluationMapper evaluationMapper;
private final InterviewQuestionProgressMapper questionProgressMapper;
private final ObjectMapper objectMapper;
private Map<String, DocumentParser> documentParsers;
private static final int MAX_QUESTIONS_PER_INTERVIEW = 10;
@PostConstruct
public void init() {
this.documentParsers = documentParserList.stream()
.collect(Collectors.toMap(DocumentParser::getSupportedType, Function.identity()));
}
/**
* 开始新的面试会话
*/
@Transactional(rollbackFor = Exception.class)
public InterviewResponse startInterview(MultipartFile resume, InterviewStartRequest request) throws IOException {
log.info("开始新面试会话,候选人: {}, AI模型: qwen-max", request.getCandidateName());
// 1. 解析简历
String resumeContent = parseResume(resume);
// 2. 创建会话 并发送AI请求 让其从题库中智能抽题
String sessionId = UUID.randomUUID().toString();
List<Question> selectedQuestions = selectQuestionsByAi(resumeContent, sessionId);
if (selectedQuestions.isEmpty()) {
throw new IllegalStateException("AI未能成功选取题目请检查AI服务或题库。");
}
// 生成面试问题进度数据
if (CollectionUtil.isNotEmpty(selectedQuestions)) {
for (Question question : selectedQuestions) {
InterviewQuestionProgress progress =
new InterviewQuestionProgress()
.setSessionId(sessionId)
.setQuestionId(question.getId())
.setQuestionContent(question.getContent())
.setStatus(InterviewQuestionProgress.Status.DEFAULT.name())
.setTotalQuestions(selectedQuestions.size())
.setScore(BigDecimal.ZERO)
.setAiModel(QWEN_MAX)
.setCandidateName(request.getCandidateName());
questionProgressMapper.insert(progress);
}
}
// 3. 保存AI选择的题目ID列表
List<Long> selectedQuestionIds = selectedQuestions.stream().map(Question::getId).collect(Collectors.toList());
String selectedQuestionIdsJson = objectMapper.writeValueAsString(selectedQuestionIds);
InterviewSession session = createSession(sessionId, request, resumeContent, selectedQuestionIdsJson);
session.setTotalQuestions(selectedQuestions.size()); // 更新会话中的总问题数
sessionMapper.updateById(session); // 更新数据库
// 4. 生成第一个问题
Question firstQuestion = selectedQuestions.get(0);
String firstQuestionContent = generateFirstQuestion(session, firstQuestion, sessionId);
// 激活问题
questionProgressMapper.update(
new LambdaUpdateWrapper<InterviewQuestionProgress>()
.set(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.ACTIVE.name())
.eq(InterviewQuestionProgress::getQuestionId, firstQuestion.getId())
.eq(InterviewQuestionProgress::getSessionId, sessionId)
);
// 5. 保存消息记录
saveMessage(sessionId, InterviewMessage.MessageType.QUESTION.name(),
InterviewMessage.Sender.AI.name(), firstQuestionContent, firstQuestion.getId(), 1);
// 6. 返回响应
return new InterviewResponse()
.setSessionId(sessionId)
.setMessage(firstQuestionContent)
.setMessageType(InterviewMessage.MessageType.QUESTION.name())
.setSender(InterviewMessage.Sender.AI.name())
.setCurrentQuestionIndex(1)
.setCurrentQuestionId(firstQuestion.getId())
.setTotalQuestions(selectedQuestions.size())
.setStatus(InterviewSession.Status.ACTIVE.name());
}
/**
* 处理用户回答并生成下一个问题
*/
@Transactional(rollbackFor = Exception.class)
public InterviewResponse continueInterview(ChatRequest request) {
log.info("继续面试会话: {}", request.getSessionId());
InterviewSession session = sessionMapper.selectBySessionId(request.getSessionId());
if (session == null) {
throw new IllegalArgumentException("会话不存在: " + request.getSessionId());
}
if (!InterviewSession.Status.ACTIVE.name().equals(session.getStatus())) {
throw new IllegalStateException("会话已结束");
}
// 1. 保存用户回答
int nextOrder = messageMapper.selectMaxOrderBySessionId(request.getSessionId()) + 1;
saveMessage(request.getSessionId(), InterviewMessage.MessageType.ANSWER.name(),
InterviewMessage.Sender.USER.name(), request.getUserAnswer(), null, nextOrder);
// 检查是否结束面试
InterviewQuestionProgress progress = questionProgressMapper.selectOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, request.getSessionId())
.orderByDesc(InterviewQuestionProgress::getCreatedTime)
.last("limit 1")
);
if (Objects.nonNull(progress) && Objects.equals(progress.getQuestionId(), request.getCurrentQuestionId())) {
}
// 2. 评估回答
Long currentQuestionId = evaluateAnswer(session, request.getUserAnswer());
// 比对返回的id是否与当前id一致
if (currentQuestionId.equals(0L)) {
return finishInterview(session);
}
InterviewQuestionProgress nextQuestionProgress = questionProgressMapper.selectOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, request.getSessionId())
.eq(InterviewQuestionProgress::getQuestionId, currentQuestionId)
.orderByDesc(InterviewQuestionProgress::getCreatedTime)
.last("limit 1")
);
// 将ai返回的内容拼装返回给页面
// 查询数据
InterviewQuestionProgress currentQuestionData = questionProgressMapper.selectOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, request.getSessionId())
.eq(InterviewQuestionProgress::getQuestionId, request.getCurrentQuestionId())
.orderByDesc(InterviewQuestionProgress::getCreatedTime)
.last("limit 1")
);
StringBuilder sb = new StringBuilder();
if (Objects.nonNull(currentQuestionData)) {
if (StringUtils.isNotBlank(currentQuestionData.getFeedback())) {
sb.append(currentQuestionData.getFeedback()).append("\n");
}
if (StringUtils.isNotBlank(currentQuestionData.getSuggestions())) {
sb.append(currentQuestionData.getSuggestions()).append("\n");
}
if (StringUtils.isNotBlank(currentQuestionData.getAiAnswer())) {
sb.append(currentQuestionData.getAiAnswer()).append("\n");
}
}
if (!currentQuestionId.equals(request.getCurrentQuestionId())) {
// 5. 生成并保存AI的提问消息
String nextQuestionContent = String.format("好的,下一个问题是:%s", nextQuestionProgress.getQuestionContent());
sb.append(nextQuestionContent);
int messageOrder = messageMapper.selectMaxOrderBySessionId(session.getSessionId()) + 1;
saveMessage(session.getSessionId(), InterviewMessage.MessageType.QUESTION.name(),
InterviewMessage.Sender.AI.name(), nextQuestionContent, currentQuestionId, messageOrder);
}
// 6. 返回响应
return new InterviewResponse()
.setSessionId(session.getSessionId())
.setMessage(sb.toString())
.setMessageType(InterviewMessage.MessageType.QUESTION.name())
.setSender(InterviewMessage.Sender.AI.name())
.setCurrentQuestionIndex(session.getCurrentQuestionIndex())
.setTotalQuestions(session.getTotalQuestions())
.setCurrentQuestionId(currentQuestionId)
.setStatus(InterviewSession.Status.ACTIVE.name());
}
/**
* 导入题库使用AI自动分类
*/
/**
* 获取会话历史
*/
public SessionHistoryResponse getSessionHistory(String sessionId) {
InterviewSession session = sessionMapper.selectBySessionId(sessionId);
if (session == null) {
throw new IllegalArgumentException("会话不存在: " + sessionId);
}
List<InterviewMessage> messages = messageMapper.selectBySessionIdOrderByOrder(sessionId);
List<SessionHistoryResponse.MessageDto> messageDtos = messages.stream()
.map(msg -> new SessionHistoryResponse.MessageDto()
.setMessageType(msg.getMessageType())
.setSender(msg.getSender())
.setContent(msg.getContent())
.setMessageOrder(msg.getMessageOrder())
.setCreatedTime(msg.getCreatedTime()))
.collect(Collectors.toList());
return new SessionHistoryResponse()
.setSessionId(sessionId)
.setCandidateName(session.getCandidateName())
.setAiModel(session.getAiModel())
.setStatus(session.getStatus())
.setTotalQuestions(session.getTotalQuestions())
.setCurrentQuestionIndex(session.getCurrentQuestionIndex())
.setCreatedTime(session.getCreatedTime())
.setMessages(messageDtos);
}
private String parseResume(MultipartFile resume) throws IOException {
String fileExtension = getFileExtension(resume.getOriginalFilename());
DocumentParser parser = documentParsers.get(fileExtension);
if (parser == null) {
throw new IllegalArgumentException("不支持的简历文件类型: " + fileExtension);
}
return parser.parse(resume.getInputStream());
}
private List<Question> selectQuestionsByAi(String resumeContent, String sessionId) throws JsonProcessingException {
// 1. 获取全部题库
List<Question> allQuestions = questionMapper.selectList(null);
String questionBankJson = objectMapper.writeValueAsString(allQuestions);
// 2. 构建发送给AI的提示
String prompt = String.format("""
你是一位专业的面试官。请根据以下候选人的简历内容,从提供的题库中,精心挑选出 %d 道最相关的题目进行面试。
要求:
1. 题目必须严格从【题库JSON】中选择。
2. 挑选的题目应根据候选人的简历内容来抽取。
3. 返回一个只包含所选题目ID的JSON数组格式为{"question_ids": [1, 5, 23, ...]}。
4. 不要返回任何多余的代码包括markdown形式的代码我只需要JSON对象请严格按照api接口形式返回
5. 不要返回任何额外的解释或文字只返回JSON对象。
6. 严格按照前后端分离的接口形式返回JSON数据给我不要返回"```json```"
7. 请保证返回数据的完整性不要返回不完整的数据否则我的JSON解析会报错
【候选人简历】:
%s
【题库JSON】:
%s
""", MAX_QUESTIONS_PER_INTERVIEW, resumeContent, questionBankJson);
// 3. 调用AI服务
String aiResponse = llmService.chat(prompt);
log.info("AI抽题响应: {}", aiResponse);
// 4. 解析AI返回的题目ID
List<Long> selectedIds = new ArrayList<>();
try {
JsonNode rootNode = objectMapper.readTree(aiResponse);
JsonNode idsNode = rootNode.get("question_ids");
if (idsNode != null && idsNode.isArray()) {
for (JsonNode idNode : idsNode) {
selectedIds.add(idNode.asLong());
}
}
} catch (JsonProcessingException e) {
log.error("解析AI返回的题目ID列表失败", e);
return Collections.emptyList(); // 解析失败则返回空列表
}
if (selectedIds.isEmpty()) {
return Collections.emptyList();
}
// 5. 根据ID从数据库中获取完整的题目信息并保持AI选择的顺序
List<Question> finalQuestions = questionMapper.selectBatchIds(selectedIds);
finalQuestions.sort(Comparator.comparing(q -> selectedIds.indexOf(q.getId()))); // 保持AI返回的顺序
return finalQuestions;
}
private InterviewSession createSession(String sessionId, InterviewStartRequest request,
String resumeContent, String selectedQuestionIdsJson) {
InterviewSession session = new InterviewSession()
.setSessionId(sessionId)
.setCandidateName(request.getCandidateName())
.setResumeContent(resumeContent)
.setSelectedQuestionIds(selectedQuestionIdsJson)
.setAiModel("qwen-max") // Hardcoded to qwen-max
.setStatus(InterviewSession.Status.ACTIVE.name())
.setCurrentQuestionIndex(0);
sessionMapper.insert(session);
return session;
}
private String generateFirstQuestion(InterviewSession session, Question question, String sessionId) {
String prompt = String.format("""
你是一位专业的技术面试官。现在要开始面试,候选人是 %s。
第一个问题是:%s
请以友好但专业的语气提出这个问题,可以适当添加一些引导性的话语。
""", session.getCandidateName(), question.getContent());
return this.llmService.chat(prompt, sessionId);
}
private void saveMessage(String sessionId, String messageType, String sender,
String content, Long questionId, int order) {
InterviewMessage message = new InterviewMessage()
.setSessionId(sessionId)
.setMessageType(messageType)
.setSender(sender)
.setContent(content)
.setQuestionId(questionId)
.setMessageOrder(order);
messageMapper.insert(message);
}
/**
* 评估答案
*
* @param session 会话数据
* @param userAnswer 用户回答
* @return 当前问题id
*/
private Long evaluateAnswer(InterviewSession session, String userAnswer) {
// 根据会话id查询当前会话所有问题
List<InterviewQuestionProgress> interviewQuestionProgresses = questionProgressMapper.selectList(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, session.getSessionId())
.orderByAsc(InterviewQuestionProgress::getCreatedTime)
);
if (CollectionUtil.isEmpty(interviewQuestionProgresses)) {
throw new RuntimeException("当前会话没有任何可询问的问题!");
}
// 1. 获取当前正在回答的问题
InterviewQuestionProgress currentQuestionProgress = null;
for (InterviewQuestionProgress interviewQuestionProgress : interviewQuestionProgresses) {
if (interviewQuestionProgress.getStatus().equals(InterviewQuestionProgress.Status.ACTIVE.name())) {
currentQuestionProgress = interviewQuestionProgress;
break;
}
}
if (Objects.isNull(currentQuestionProgress)) {
throw new RuntimeException("当前没有正在回答的问题");
}
Long currentQuestionId = currentQuestionProgress.getQuestionId();
List<String> questionIds = interviewQuestionProgresses.stream()
.map(data -> {
return data.getQuestionId().toString();
})
.collect(Collectors.toList());
String join = String.join(",", questionIds);
// 2. 构建评估提示
String prompt = String.format("""
你是一位资深的技术面试官。请根据以下问题和候选人的回答,进行一次专业的评估。
要求:
1. 对回答的质量进行打分分数范围为1-5分。
2. 给出简洁、专业的评语。
3. 提出具体的改进建议以及你认为应该回答的答案。
4. 以严格的JSON格式返回不要包含任何额外的解释文字。格式如下
{
"score": 4.5,
"feedback": "回答基本正确,但可以更深入...",
"suggestions": "可以补充关于XXX方面的知识点...",
"answer": "关于当前问题您应该这样回答xxx",
"currentQuestionId": xxx
}
5. 不要返回任何多余字符请严格按照api接口格式的JSON数据进行返回不要包含"```json```"
6. 如果你认为面试人对当前问题回答不完美可以继续对当前问题进行补充提问但不要修改currentQuestionId
7. 如果你认为面试人对当前问题回答已经比较好了或者面试人回答不上来了请你根据questionIds数据顺序选择下一个问题并修改currentQuestionId进行返回
8. 如果所有问题都已回答完成请将currentQuestionId设置为0
{
"questionIds": %s,
"currentQuestionId": %s
}
【面试问题】:
%s
【候选人回答】:
%s
""", join, currentQuestionProgress.getQuestionId(), currentQuestionProgress.getQuestionContent(), userAnswer);
// 3. 调用AI进行评估
String aiResponse = llmService.chat(prompt, session.getSessionId());
log.info("AI评估响应: {}", aiResponse);
// 4. 解析AI响应并存储评估结果
try {
JsonNode rootNode = objectMapper.readTree(aiResponse);
InterviewEvaluation evaluation = new InterviewEvaluation()
.setSessionId(session.getSessionId())
.setQuestionId(currentQuestionId)
.setUserAnswer(userAnswer)
.setScore(new java.math.BigDecimal(rootNode.get("score").asText()))
.setAiFeedback(rootNode.get("feedback").asText())
.setEvaluationCriteria(rootNode.get("suggestions").asText()); // 暂时复用这个字段存建议
JsonNode currentQuestionId1 = rootNode.get("currentQuestionId");
JsonNode aiAnswerNode = rootNode.get("answer");
if (Objects.nonNull(currentQuestionId1)) {
String text = currentQuestionId1.asText();
if (StringUtils.isNoneBlank(text)) {
currentQuestionProgress
.setScore(new BigDecimal(rootNode.get("score").asText()))
.setSuggestions(rootNode.get("suggestions").asText())
.setFeedback(rootNode.get("feedback").asText())
.setAiAnswer(Objects.nonNull(aiAnswerNode) ? aiAnswerNode.asText() : null)
.setUserAnswer(userAnswer)
;
if (!StrUtil.equals(text, currentQuestionProgress.getQuestionId().toString())) {
currentQuestionProgress.setStatus(InterviewQuestionProgress.Status.COMPLETED.name());
questionProgressMapper.updateById(currentQuestionProgress);
questionProgressMapper.update(
new LambdaUpdateWrapper<InterviewQuestionProgress>()
.set(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.ACTIVE.name())
.eq(InterviewQuestionProgress::getSessionId, session.getSessionId())
.eq(InterviewQuestionProgress::getQuestionId, Long.valueOf(text))
);
} else if (text.equals("0")) {
currentQuestionProgress.setStatus(InterviewQuestionProgress.Status.COMPLETED.name());
questionProgressMapper.updateById(currentQuestionProgress);
}
currentQuestionId = Long.valueOf(text);
}
}
evaluationMapper.insert(evaluation);
log.info("成功存储对问题ID {} 的评估结果", currentQuestionId);
return currentQuestionId;
} catch (Exception e) {
log.error("解析或存储AI评估结果失败", e);
throw new RuntimeException("解析或存储AI评估结果失败");
}
}
private InterviewResponse finishInterview(InterviewSession session) {
// 1. 获取本次面试的所有评估数据
List<InterviewEvaluation> evaluations = evaluationMapper.selectBySessionId(session.getSessionId());
// 2. 构建生成最终报告的提示
String prompt = buildFinalReportPrompt(session, evaluations);
// 3. 调用AI生成报告
String finalReportJson = llmService.chat(prompt, session.getSessionId());
log.info("AI生成的最终面试报告: {}", finalReportJson);
// 4. 更新会话状态和最终报告
session.setStatus(InterviewSession.Status.COMPLETED.name());
session.setFinalReport(finalReportJson);
sessionMapper.updateById(session);
// 5. 返回结束信息
return new InterviewResponse()
.setSessionId(session.getSessionId())
.setMessage("面试已结束感谢您的参与AI正在生成您的面试报告请稍后在面试历史中查看。")
.setMessageType(InterviewMessage.MessageType.SYSTEM.name())
.setSender(InterviewMessage.Sender.SYSTEM.name())
.setCurrentQuestionId(null)
.setStatus(InterviewSession.Status.COMPLETED.name());
}
private String buildFinalReportPrompt(InterviewSession session, List<InterviewEvaluation> evaluations) {
StringBuilder historyBuilder = new StringBuilder();
for (InterviewEvaluation eval : evaluations) {
Question q = questionMapper.selectById(eval.getQuestionId());
historyBuilder.append(String.format("\n【问题】: %s\n【回答】: %s\n【AI单题反馈】: %s\n【AI单题建议】: %s\n【AI单题评分】: %s/5.0\n",
q.getContent(), eval.getUserAnswer(), eval.getAiFeedback(), eval.getEvaluationCriteria(), eval.getScore()));
}
return String.format("""
你是一位资深的HR和技术总监。请根据以下候选人的简历、完整的面试问答历史和AI对每一题的初步评估给出一份全面、专业、有深度的最终面试报告。
要求:
1. **综合评价**: 对候选人的整体表现给出一个总结性的评语,点出其核心亮点和主要不足。
2. **技术能力评估**: 分点阐述候选人在不同技术领域如Java基础, Spring, 数据库等)的掌握程度。
3. **改进建议**: 给出3-5条具体的、可操作的学习和改进建议。
4. **综合得分**: 给出一个1-100分的最终综合得分。
5. **录用建议**: 给出明确的录用建议(如:强烈推荐、推荐、待考虑、不推荐)。
6. 以严格的JSON格式返回不要包含任何额外的解释文字。格式如下
{
"overallScore": 85,
"overallFeedback": "候选人Java基础扎实但在高并发场景下的经验有所欠缺...",
"technicalAssessment": {
"Java基础": "掌握良好,对集合框架理解深入。",
"Spring框架": "熟悉基本使用,但对底层原理理解不足。",
"数据库": "能够编写常规SQL但在索引优化方面知识欠缺。"
},
"suggestions": [
"深入学习Spring AOP和事务管理的实现原理。",
"系统学习MySQL索引优化和查询性能分析。",
"通过实际项目积累高并发处理经验。"
],
"hiringRecommendation": "推荐"
}
【候选人简历摘要】:
%s
【面试问答与评估历史】:
%s
""", session.getResumeContent(), historyBuilder.toString());
}
private InterviewResponse generateNextQuestion(InterviewSession session) {
try {
// 1. 解析出AI选择的题目ID列表
List<Long> selectedQuestionIds = objectMapper.readValue(session.getSelectedQuestionIds(), new com.fasterxml.jackson.core.type.TypeReference<List<Long>>() {
});
// 2. 获取下一个问题的索引
int nextQuestionIndex = session.getCurrentQuestionIndex(); // 数据库中存的是已回答问题的数量
if (nextQuestionIndex >= selectedQuestionIds.size()) {
return finishInterview(session); // 如果没有更多问题,则结束面试
}
// 3. 获取下一个问题的ID并从数据库查询
Long nextQuestionId = selectedQuestionIds.get(nextQuestionIndex);
Question nextQuestion = questionMapper.selectById(nextQuestionId);
if (nextQuestion == null) {
log.error("无法找到ID为 {} 的问题,跳过此问题。", nextQuestionId);
// 更新会话状态并尝试下一个问题
session.setCurrentQuestionIndex(nextQuestionIndex + 1);
sessionMapper.updateById(session);
return generateNextQuestion(session); // 递归调用以获取再下一个问题
}
// 4. 更新会话状态(当前问题索引+1
session.setCurrentQuestionIndex(nextQuestionIndex + 1);
sessionMapper.updateById(session);
// 5. 生成并保存AI的提问消息
String questionContent = String.format("好的,下一个问题是:%s", nextQuestion.getContent());
int messageOrder = messageMapper.selectMaxOrderBySessionId(session.getSessionId()) + 1;
saveMessage(session.getSessionId(), InterviewMessage.MessageType.QUESTION.name(),
InterviewMessage.Sender.AI.name(), questionContent, nextQuestion.getId(), messageOrder);
// 6. 返回响应
return new InterviewResponse()
.setSessionId(session.getSessionId())
.setMessage(questionContent)
.setMessageType(InterviewMessage.MessageType.QUESTION.name())
.setSender(InterviewMessage.Sender.AI.name())
.setCurrentQuestionIndex(session.getCurrentQuestionIndex())
.setTotalQuestions(session.getTotalQuestions())
.setStatus(InterviewSession.Status.ACTIVE.name());
} catch (JsonProcessingException e) {
log.error("解析会话中的题目ID列表失败", e);
return finishInterview(session); // 解析失败则直接结束面试
}
}
/**
* 获取所有面试会话列表
*/
public List<InterviewSession> getInterviewSessions() {
log.info("Fetching all interview sessions");
return sessionMapper.selectList(null); // 实际中可能需要分页
}
/**
* 获取详细的面试复盘报告
*/
public InterviewReportResponse getInterviewReport(String sessionId) {
log.info("Fetching interview report for session id: {}", sessionId);
InterviewSession session = sessionMapper.selectBySessionId(sessionId);
if (session == null) {
throw new IllegalArgumentException("找不到ID为 " + sessionId + " 的面试会话。");
}
List<InterviewEvaluation> evaluations = evaluationMapper.selectBySessionId(sessionId);
List<InterviewReportResponse.QuestionDetail> questionDetails = evaluations.stream().map(eval -> {
Question question = questionMapper.selectById(eval.getQuestionId());
InterviewReportResponse.QuestionDetail detail = new InterviewReportResponse.QuestionDetail();
detail.setQuestionId(eval.getQuestionId());
detail.setQuestionContent(question != null ? question.getContent() : "题目已不存在");
detail.setUserAnswer(eval.getUserAnswer());
detail.setAiFeedback(eval.getAiFeedback());
detail.setSuggestions(eval.getEvaluationCriteria());
detail.setScore(eval.getScore());
return detail;
}).collect(Collectors.toList());
InterviewReportResponse report = new InterviewReportResponse();
report.setSessionDetails(session);
report.setQuestionDetails(questionDetails);
List<InterviewMessage> interviewMessages = messageMapper.selectList(
new LambdaQueryWrapper<InterviewMessage>()
.eq(InterviewMessage::getSessionId, sessionId)
);
// 获取当前面试的 问题
InterviewQuestionProgress progress = questionProgressMapper.selectOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, sessionId)
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.ACTIVE.name())
.last("LIMIT 1")
);
if (Objects.nonNull(progress)) {
report.setCurrentQuestionId(progress.getQuestionId());
}
report.setMessages(interviewMessages);
return report;
}
private String getFileExtension(String fileName) {
if (fileName == null || fileName.lastIndexOf('.') == -1) {
return "";
}
return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
}
}
package com.qingqiu.interview.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qingqiu.interview.dto.InterviewReportResponse;
import com.qingqiu.interview.dto.InterviewStartRequest;
import com.qingqiu.interview.dto.SubmitAnswerDTO;
import com.qingqiu.interview.entity.InterviewMessage;
import com.qingqiu.interview.entity.InterviewQuestionProgress;
import com.qingqiu.interview.entity.InterviewSession;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/19 16:05
*/
public interface InterviewService extends IService<InterviewSession> {
/**
* 开始一场新的面试
*
* @param file 简历文件
* @param dto 开始面试的请求参数
* @return 创建的面试会话
*/
InterviewSession startInterview(MultipartFile file, InterviewStartRequest dto) throws IOException;
/**
* 获取下一个问题
*
* @param sessionId 会话ID
* @return 下一个问题 或 null如果没有更多问题
*/
InterviewMessage getNextQuestion(String sessionId, Long progressId);
/**
* 提交答案并获取AI评估
*
* @param submitAnswerDTO 提交答案的请求参数
* @return 对当前问题的评估和反馈
*/
InterviewQuestionProgress submitAnswer(SubmitAnswerDTO submitAnswerDTO);
/**
* 结束面试并生成最终报告
*
* @param sessionId 会话ID
* @return 包含最终报告的面试会话信息
*/
InterviewSession endInterview(String sessionId);
/**
* 获取面试报告
* @param sessionId
* @return
*/
InterviewReportResponse getInterviewReport(String sessionId);
}

View File

@@ -82,7 +82,7 @@ public class QuestionClassificationService {
for (JsonNode questionNode : questionsNode) {
Question question = new Question()
.setContent(getTextValue(questionNode, "content"))
.setCategory(getTextValue(questionNode, "category"))
.setCategoryName(getTextValue(questionNode, "category"))
.setDifficulty(getTextValue(questionNode, "difficulty"))
.setTags(getTextValue(questionNode, "tags"));
@@ -112,7 +112,7 @@ public class QuestionClassificationService {
private boolean isValidQuestion(Question question) {
return question.getContent() != null && !question.getContent().trim().isEmpty()
&& question.getCategory() != null && !question.getCategory().trim().isEmpty();
&& question.getCategoryName() != null && !question.getCategoryName().trim().isEmpty();
}
private List<Question> fallbackParsing(String content) {
@@ -126,7 +126,7 @@ public class QuestionClassificationService {
if (!line.isEmpty() && line.length() > 10) { // 过滤太短的内容
Question question = new Question()
.setContent(line)
.setCategory("未分类")
.setCategoryName("未分类")
.setDifficulty("Medium")
.setTags("待分类");
questions.add(question);

View File

@@ -1,177 +1,39 @@
package com.qingqiu.interview.service;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qingqiu.interview.dto.QuestionOptionsDTO;
import com.qingqiu.interview.dto.QuestionPageParams;
import com.qingqiu.interview.entity.Question;
import com.qingqiu.interview.mapper.QuestionMapper;
import com.qingqiu.interview.service.llm.LlmService;
import com.qingqiu.interview.service.parser.DocumentParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class QuestionService {
public interface QuestionService extends IService<Question> {
private final QuestionMapper questionMapper;
private final QuestionClassificationService classificationService;
private final List<DocumentParser> documentParserList; // This will be injected by Spring
private final LlmService llmService;
Page<Question> getQuestionPage(QuestionPageParams params);
void addQuestion(Question question);
void updateQuestion(Question question);
void deleteQuestion(Long id);
void importQuestionsFromFile(MultipartFile file) throws IOException;
void useAiCheckQuestionData();
List<QuestionAndCategoryTreeListVO> getTreeListCategory(QuestionOptionsDTO dto);
/**
* 分页查询题库
*/
public Page<Question> getQuestionPage(QuestionPageParams params) {
log.info("分页查询题库,当前页: {}, 每页数量: {}", params.getCurrent(), params.getSize());
return questionMapper.selectPage(
Page.of(params.getCurrent(), params.getSize()),
new LambdaQueryWrapper<Question>()
.like(StringUtils.isNotBlank(params.getContent()), Question::getContent, params.getContent())
.orderByDesc(Question::getCreatedTime)
);
}
/**
* 新增题目,并进行重复校验
*/
public void addQuestion(Question question) {
validateQuestion(question.getContent(), null);
log.info("新增题目: {}", question.getContent());
questionMapper.insert(question);
}
/**
* 更新题目,并进行重复校验
*/
public void updateQuestion(Question question) {
validateQuestion(question.getContent(), question.getId());
log.info("更新题目ID: {}", question.getId());
questionMapper.updateById(question);
}
/**
* 删除题目
*/
public void deleteQuestion(Long id) {
log.info("删除题目ID: {}", id);
questionMapper.deleteById(id);
}
/**
* AI批量导入题库并进行去重
*/
public void importQuestionsFromFile(MultipartFile file) throws IOException {
log.info("开始从文件导入题库: {}", file.getOriginalFilename());
String fileExtension = getFileExtension(file.getOriginalFilename());
DocumentParser parser = documentParserList.stream()
.filter(p -> p.getSupportedType().equals(fileExtension))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("不支持的文件类型: " + fileExtension));
String content = parser.parse(file.getInputStream());
List<Question> questionsFromAi = classificationService.classifyQuestions(content);
int newQuestionsCount = 0;
for (Question question : questionsFromAi) {
try {
validateQuestion(question.getContent(), null);
questionMapper.insert(question);
newQuestionsCount++;
} catch (IllegalArgumentException e) {
log.warn("跳过重复题目: {}", question.getContent());
}
}
log.info("成功导入 {} 个新题目,跳过 {} 个重复题目。", newQuestionsCount, questionsFromAi.size() - newQuestionsCount);
}
/**
* 调用AI检查题库中的数据是否重复
*/
@Transactional(rollbackFor = Exception.class)
public void useAiCheckQuestionData() {
// 查询数据库
List<Question> questions = questionMapper.selectList(
new LambdaQueryWrapper<Question>()
.orderByDesc(Question::getCreatedTime)
);
// 组装prompt
if (CollectionUtil.isEmpty(questions)) {
return;
}
String prompt = getPrompt(questions);
log.info("发送内容: {}", prompt);
// 验证token上下文长度
Integer promptTokens = llmService.getPromptTokens(prompt);
log.info("当前prompt长度: {}", promptTokens);
String chat = llmService.chat(prompt);
// 调用AI
log.info("AI返回内容: {}", chat);
JSONObject parse = JSONObject.parse(chat);
JSONArray questionsIds = parse.getJSONArray("questions");
List<Long> list = questionsIds.toList(Long.class);
questionMapper.delete(
new LambdaQueryWrapper<Question>()
.notIn(Question::getId, list)
);
}
@NotNull
private static String getPrompt(List<Question> questions) {
JSONArray jsonArray = new JSONArray();
for (Question question : questions) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", question.getId());
jsonObject.put("content", question.getContent());
jsonArray.add(jsonObject);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", jsonArray);
return String.format("""
请对以下数据进行重复校验如果题目内容相似请只保留1条数据并返回对应数据的id。请严格按照以下JSON格式返回结果
{
"questions": [1, 2, 3, .....]
}
分类规则:
1. 只返回JSON不要其他解释文字
2. 请严格按照API接口形式返回不要返回任何额外的文字内容包括'```json```'!!!!
3. 请严格按照网络接口的形式返回JSON数据
数据如下:
%s
""", jsonObject.toJSONString());
}
/**
* 校验题目内容是否重复
* 根据技能和难度从本地题库随机选择题目
*
* @param content 题目内容
* @param currentId 当前题目ID更新时传入用于排除自身
* @param skills 技能列表
* @param difficulty 难度
* @param count 题目数量
* @return 题目列表
*/
private void validateQuestion(String content, Long currentId) {
Question existingQuestion = questionMapper.selectByContent(content);
if (existingQuestion != null && (currentId == null || !existingQuestion.getId().equals(currentId))) {
throw new IllegalArgumentException("题目内容已存在,请勿重复添加。");
}
}
private String getFileExtension(String fileName) {
if (fileName == null || fileName.lastIndexOf('.') == -1) {
return "";
}
return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
}
List<Question> selectLocalQuestions(List<String> skills, String difficulty, int count);
}

View File

@@ -0,0 +1,95 @@
package com.qingqiu.interview.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingqiu.interview.ai.factory.AIClientManager;
import com.qingqiu.interview.annotation.AiChatLog;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.common.utils.AIUtils;
import com.qingqiu.interview.dto.ChatDTO;
import com.qingqiu.interview.dto.InterviewStartRequest;
import com.qingqiu.interview.entity.AiSessionLog;
import com.qingqiu.interview.service.ChatService;
import com.qingqiu.interview.service.IAiSessionLogService;
import com.qingqiu.interview.vo.ChatVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.qingqiu.interview.common.constants.CommonConstant.DEFAULT_TRUNCATE_RATIO;
import static com.qingqiu.interview.common.constants.CommonConstant.MAX_TOKEN;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 12:56
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
private final AIClientManager aiClientManager;
private final IAiSessionLogService aiSessionLogService;
@Override
@AiChatLog
public ChatVO createChat(ChatDTO dto) {
LLMProvider llmProvider = LLMProvider.fromCode(dto.getAiModel());
List<Message> messages = new ArrayList<>();
AtomicInteger tokens = new AtomicInteger();
// 如果会话id不为空 则从数据库中获取会话记录
if (dto.getSessionId() != null) {
List<AiSessionLog> list = aiSessionLogService.list(
new LambdaQueryWrapper<AiSessionLog>()
.eq(AiSessionLog::getToken, dto.getSessionId())
.eq(AiSessionLog::getDataType, dto.getDataType())
.orderByAsc(AiSessionLog::getCreatedTime)
);
if (CollectionUtil.isNotEmpty(list)) {
messages.addAll(list.stream().map(data -> {
tokens.getAndAdd(AIUtils.getPromptTokens(data.getContent()));
return AIUtils.createMessage(data.getRole(), data.getContent());
}).toList());
}
}
messages.add(AIUtils.createMessage(dto.getRole(), dto.getContent()));
List<Message> finalMessage = new ArrayList<>();
// 剪切 10%的消息
if (tokens.get() > MAX_TOKEN) {
BigDecimal size = new BigDecimal(String.valueOf(messages.size()));
size = size.multiply(DEFAULT_TRUNCATE_RATIO).setScale(0, RoundingMode.HALF_UP);
for (int i = size.intValue(); i < messages.size(); i++) {
finalMessage.add(messages.get(i));
}
} else {
finalMessage = messages;
}
String res = aiClientManager.getClient(llmProvider).chatCompletion(finalMessage);
return ChatVO.builder()
.role(Role.ASSISTANT.getValue())
.sessionId(dto.getSessionId())
.content(res)
.build();
}
@Override
public String createInterviewChat(MultipartFile resume, InterviewStartRequest request) {
return "";
}
}

View File

@@ -0,0 +1,227 @@
package com.qingqiu.interview.service.impl;
import com.alibaba.dashscope.common.Role;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qingqiu.interview.common.constants.CommonConstant;
import com.qingqiu.interview.dto.ChatDTO;
import com.qingqiu.interview.entity.InterviewQuestionProgress;
import com.qingqiu.interview.entity.InterviewSession;
import com.qingqiu.interview.entity.Question;
import com.qingqiu.interview.service.ChatService;
import com.qingqiu.interview.service.InterviewAiService;
import com.qingqiu.interview.vo.ChatVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/19 16:49
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewAiServiceImpl implements InterviewAiService {
private final ChatService chatService;
@Override
public JSONObject extractSkillsFromResume(String resumeContent) {
String prompt = "你是一位资深的IT技术招聘专家。" +
"请仔细阅读以下简历内容,并提取出其中所有的关键技术技能。" +
"请严格按照以下JSON格式返回不要添加任何额外的解释或说明\n" +
"{\"skills\": [\"技能1\", \"技能2\", \"...\"]}\n\n" +
"简历内容如下:\n" + resumeContent;
ChatDTO chatDTO = new ChatDTO()
.setContent(prompt)
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE);
ChatVO chatVO = chatService.createChat(chatDTO);
return JSONObject.parse(chatVO.getContent());
}
@Override
public JSONObject generateQuestionsOfAi(String sessionId, List<String> skills, String resumeContent, int count) {
String skillsStr = String.join(", ", skills);
String prompt = String.format(
"你是一位专业的软件开发岗位技术面试官。" +
"请根据候选人的以下技术栈、项目经历、简历内容,生成 %d 道有深度和广度的面试题。" +
"题目应覆盖候选人的主要技术领域,并能考察其解决问题的能力。" +
"请严格按照以下JSON格式返回question数组中必须包含 %d 个问题对象:\n" +
"{\"questions\": [{\"id\": \"ai-gen-1\", \"content\": \"问题1内容...\"}, {\"id\": \"ai-gen-2\", \"content\": \"问题2内容...\"}]}\n\n" +
"候选人技术栈:%s\n" +
"候选人简历:%s",
count, count, skillsStr, resumeContent
);
ChatDTO chatDTO = new ChatDTO()
.setSessionId(sessionId)
.setContent(prompt)
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE);
ChatVO chatVO = chatService.createChat(chatDTO);
return JSON.parseObject(chatVO.getContent());
}
@Override
public JSONObject generateQuestionOfLocal(String sessionId, List<Question> questions, List<String> skills, String resumeContent, int count) {
String skillsStr = String.join(", ", skills);
// 2. 构建发送给AI的提示
String prompt = String.format("""
你是一位专业的面试官。请根据以下候选人的技术栈、项目经历、简历内容,从提供的题库中,精心挑选出 %d 道最相关的题目进行面试。
题目应覆盖候选人的主要技术领域,并能考察其解决问题的能力。
要求:
1. 题目必须严格从【题库JSON】中选择。
2. 挑选的题目应根据候选人的简历内容来抽取。
3. 返回一个只包含所选题目ID的JSON数组格式为{"question_ids": [1, 5, 23, ...]}。
4. 不要返回任何多余的代码包括markdown形式的代码我只需要JSON对象请严格按照api接口形式返回
5. 不要返回任何额外的解释或文字只返回JSON对象。
6. 严格按照前后端分离的接口形式返回JSON数据给我不要返回"```json```"
7. 请保证返回数据的完整性不要返回不完整的数据否则我的JSON解析会报错
【候选人技术栈】:
%s
【候选人简历】:
[%s]
【题库JSON】:
%s
""", count, skillsStr, resumeContent, JSONObject.toJSONString(questions));
ChatDTO chatDTO = new ChatDTO()
.setSessionId(sessionId)
.setContent(prompt)
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE);
ChatVO chatVO = chatService.createChat(chatDTO);
return JSON.parseObject(chatVO.getContent());
}
@Override
public JSONObject evaluateAnswer(String sessionId, String question, String userAnswer, List<InterviewQuestionProgress> context) {
// 构建上下文历史
String history = context.stream()
.map(p -> String.format("Q: %s\nA: %s", p.getQuestionContent(), p.getUserAnswer()))
.collect(Collectors.joining("\n---\n"));
String prompt = "你是一位资深的技术面试官,以严格和深入著称。" +
"你需要评估候选人对以下问题的回答。请注意:\n" +
"1. 如果回答模糊、不完整或有错误你可以提出一个具体的追问问题followUpQuestion来深入考察此时'continueAsking'应为true。\n" +
"2. 如果回答得很好,则'continueAsking'为false'followUpQuestion'为空字符串。\n" +
"3. 'score'范围为0-100分。\n" +
"4. 'feedback'和'suggestions'需要给出专业、有建设性的意见。\n" +
"5. 追问最好有限制不要无限制的向下追问注意追问是支线而非主线追问至多3个问题之后必须切回主线\n" +
"请严格按照以下JSON格式返回不要有任何额外说明\n" +
"{\"feedback\": \"...\", \"suggestions\": \"...\", \"aiAnswer\": \"...\", \"score\": 85.5, \"continueAsking\": false, \"followUpQuestion\": \"...\"}\n\n" +
"面试历史上下文:\n" + history + "\n\n" +
"当前问题:\n" + question + "\n\n" +
"候选人回答:\n" + userAnswer;
ChatDTO chatDTO = new ChatDTO()
.setSessionId(sessionId)
.setContent(prompt)
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE);
ChatVO chatVO = chatService.createChat(chatDTO);
return JSON.parseObject(chatVO.getContent());
}
@Override
public JSONObject generateFinalReport(InterviewSession session, List<InterviewQuestionProgress> progressList) {
// String transcript = progressList.stream()
// .map(p -> String.format("问题: %s\n回答: %s\nAI评分: %.1f\nAI反馈: %s\n",
// p.getQuestionContent(), p.getUserAnswer(), p.getScore(), p.getFeedback()))
// .collect(Collectors.joining("\n-----------------\n"));
// String prompt = "你是一位经验丰富的招聘经理。" +
// "请根据以下完整的面试记录,为候选人生成一份综合评估报告。" +
// "报告需要包括一个总分overallScore简明扼要的总结summary以及候选人的优点strengths和待提升点weaknesses。" +
// "请严格按照以下JSON格式返回\n" +
// "{\"overallScore\": 88.0, \"summary\": \"...\", \"strengths\": [\"...\"], \"weaknesses\": [\"...\"]}\n\n" +
// "候选人姓名:" + session.getCandidateName() + "\n" +
// "面试完整记录:\n" + transcript;
String prompt = buildFinalReportPrompt(session, progressList);
ChatDTO chatDTO = new ChatDTO()
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE)
.setContent(prompt);
ChatVO chatVO = chatService.createChat(chatDTO);
return JSON.parseObject(chatVO.getContent());
}
private String buildFinalReportPrompt(InterviewSession session, List<InterviewQuestionProgress> progressList) {
StringBuilder historyBuilder = new StringBuilder();
for (InterviewQuestionProgress progress : progressList) {
historyBuilder.append(
String.format("\n【问题】: %s\n【回答】: %s\n【AI单题反馈】: %s\n【AI单题建议】: %s\n【AI单题评分】: %s/5.0\n",
progress.getQuestionContent(),
progress.getUserAnswer(),
progress.getFeedback(),
progress.getSuggestions(),
progress.getScore()
)
);
}
return String.format("""
你是一位资深的HR和技术总监。请根据以下候选人的简历、完整的面试问答历史和AI对每一题的初步评估给出一份全面、专业、有深度的最终面试报告。
要求:
1. **综合评价**: 对候选人的整体表现给出一个总结性的评语,点出其核心亮点和主要不足。
2. **技术能力评估**: 分点阐述候选人在不同技术领域如Java基础, Spring, 数据库等)的掌握程度。
3. **改进建议**: 给出3-5条具体的、可操作的学习和改进建议。
4. **综合得分**: 给出一个1-100分的最终综合得分。
5. **录用建议**: 给出明确的录用建议(如:强烈推荐、推荐、待考虑、不推荐)。
6. 以严格的JSON格式返回不要包含任何额外的解释文字。格式如下
{
"overallScore": 85,
"overallFeedback": "候选人Java基础扎实但在高并发场景下的经验有所欠缺...",
"technicalAssessment": {
"Java基础": "掌握良好,对集合框架理解深入。",
"Spring框架": "熟悉基本使用,但对底层原理理解不足。",
"数据库": "能够编写常规SQL但在索引优化方面知识欠缺。"
},
"suggestions": [
"深入学习Spring AOP和事务管理的实现原理。",
"系统学习MySQL索引优化和查询性能分析。",
"通过实际项目积累高并发处理经验。"
],
"hiringRecommendation": "推荐"
}
【候选人简历摘要】:
%s
【面试问答与评估历史】:
%s
""", session.getResumeContent(), historyBuilder.toString());
}
@Override
public String generateFirstQuestion(String sessionId, String candidateName, String questionContent) {
String prompt = String.format("""
你是一位专业的技术面试官。现在要开始面试,候选人是 %s。
第一个问题是:%s
请以友好但专业的语气提出这个问题,可以适当添加一些引导性的话语。
""", candidateName, questionContent);
ChatDTO chatDTO = new ChatDTO()
.setSessionId(sessionId)
.setRole(Role.SYSTEM.getValue())
.setDataType(CommonConstant.ONE)
.setContent(prompt);
ChatVO chatVO = chatService.createChat(chatDTO);
return chatVO.getContent();
}
}

View File

@@ -0,0 +1,50 @@
package com.qingqiu.interview.service.impl;
import cn.hutool.core.io.file.FileNameUtil;
import com.qingqiu.interview.common.constants.AIStrategyConstant;
import com.qingqiu.interview.common.enums.DocumentParserProvider;
import com.qingqiu.interview.dto.InterviewStartRequest;
import com.qingqiu.interview.service.InterviewChatService;
import com.qingqiu.interview.service.parser.DocumentParser;
import com.qingqiu.interview.service.parser.DocumentParserManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 16:38
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewChatServiceImpl implements InterviewChatService {
private final DocumentParserManager documentParserManager;
@Override
public void startInterview(MultipartFile resume, InterviewStartRequest request) throws IOException {
log.info("开始新面试会话,当前模式: {}, 候选人: {}, 默认AI模型: {}", request.getModel(), request.getCandidateName(), AIStrategyConstant.QWEN);
// 1. 解析简历
String resumeContent = parseResume(resume);
// 判断是否使用本地题库
if (request.getModel().equals("local")) {
}
}
private String parseResume(MultipartFile resume) throws IOException {
// 获取文件扩展名
String extName = FileNameUtil.extName(resume.getOriginalFilename());
// 1. 获取简历解析器
DocumentParser parser = documentParserManager.getParser(DocumentParserProvider.fromCode(extName));
// 2. 解析简历
return parser.parse(resume.getInputStream());
}
}

View File

@@ -0,0 +1,23 @@
package com.qingqiu.interview.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingqiu.interview.entity.InterviewMessage;
import com.qingqiu.interview.mapper.InterviewMessageMapper;
import com.qingqiu.interview.service.InterviewMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/21 12:00
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewMessageServiceImpl extends ServiceImpl<InterviewMessageMapper, InterviewMessage> implements InterviewMessageService {
}

View File

@@ -9,8 +9,10 @@ import com.qingqiu.interview.mapper.InterviewQuestionProgressMapper;
import com.qingqiu.interview.service.IInterviewQuestionProgressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Objects;
/**
* <p>
@@ -40,4 +42,37 @@ public class InterviewQuestionProgressServiceImpl extends ServiceImpl<InterviewQ
.orderByDesc(InterviewQuestionProgress::getCreatedTime)
);
}
@Override
@Transactional(rollbackFor = Exception.class)
public InterviewQuestionProgress getNextQuestion(String sessionId) {
// 查找状态为“进行中”的问题
InterviewQuestionProgress activeQuestion = baseMapper.selectOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, sessionId)
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.ACTIVE.name())
.orderByAsc(InterviewQuestionProgress::getId)
.last("LIMIT 1")
);
if (Objects.nonNull(activeQuestion)) {
return activeQuestion;
}
// 1. 查找第一个处于“默认”状态的问题
LambdaQueryWrapper<InterviewQuestionProgress> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(InterviewQuestionProgress::getSessionId, sessionId)
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.DEFAULT.name())
.orderByAsc(InterviewQuestionProgress::getId) // 按插入顺序
.last("LIMIT 1");
InterviewQuestionProgress nextQuestion = baseMapper.selectOne(queryWrapper);
if (nextQuestion == null) {
// 没有更多的问题了
return null;
}
// 2. 将问题状态更新为“进行中”
nextQuestion.setStatus(InterviewQuestionProgress.Status.ACTIVE.name());
baseMapper.updateById(nextQuestion);
return nextQuestion;
}
}

View File

@@ -0,0 +1,414 @@
package com.qingqiu.interview.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingqiu.interview.common.enums.DocumentParserProvider;
import com.qingqiu.interview.common.ex.ApiException;
import com.qingqiu.interview.dto.InterviewReportResponse;
import com.qingqiu.interview.dto.InterviewStartRequest;
import com.qingqiu.interview.dto.SubmitAnswerDTO;
import com.qingqiu.interview.entity.*;
import com.qingqiu.interview.mapper.InterviewEvaluationMapper;
import com.qingqiu.interview.mapper.InterviewMessageMapper;
import com.qingqiu.interview.mapper.InterviewSessionMapper;
import com.qingqiu.interview.service.IInterviewQuestionProgressService;
import com.qingqiu.interview.service.InterviewAiService;
import com.qingqiu.interview.service.InterviewService;
import com.qingqiu.interview.service.QuestionService;
import com.qingqiu.interview.service.parser.DocumentParser;
import com.qingqiu.interview.service.parser.DocumentParserManager;
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/19 16:07
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class InterviewServiceImpl extends ServiceImpl<InterviewSessionMapper, InterviewSession> implements InterviewService {
private final QuestionService questionService;
private final IInterviewQuestionProgressService progressService;
private final InterviewEvaluationMapper evaluationMapper;
private final InterviewMessageMapper messageMapper;
private final InterviewAiService aiService;
private final DocumentParserManager documentParserManager;
@Override
@Transactional(rollbackFor = Exception.class)
public InterviewSession startInterview(MultipartFile file, InterviewStartRequest dto) throws IOException {
// 1. 创建并保存会话主记录
String sessionId = UUID.randomUUID().toString().replace("-", "");
String resumeContent = parseResume(file);
InterviewSession session = new InterviewSession();
session.setSessionId(sessionId);
session.setCandidateName(dto.getCandidateName());
session.setResumeContent(resumeContent);
session.setAiModel(dto.getAiModel());
session.setStatus(InterviewSession.Status.ACTIVE.name());
session.setTotalQuestions(dto.getTotalQuestions());
session.setModel(dto.getModel());
this.baseMapper.insert(session); // 先插入以获取ID
// 2. 调用AI服务从简历提取技能
JSONObject skillsJson = aiService.extractSkillsFromResume(resumeContent);
// ---> 解析AI返回的JSON数据获取技能列表 <---
List<String> skills = skillsJson.getList("skills", String.class);
session.setExtractedSkills(skillsJson.toJSONString());
// 3. 准备面试问题(本地 + AI生成
if (dto.getModel().equals("local")) {
localGenerateQuestions(session, skills, dto.getSelectedNodes());
} else {
aiGenerateQuestions(session, skills);
}
// 4. 更新会话信息
this.baseMapper.updateById(session);
InterviewQuestionProgress nextQuestion = progressService.getNextQuestion(sessionId);
aiService.generateFirstQuestion(session.getSessionId(), session.getCandidateName(), nextQuestion.getQuestionContent());
saveMessage(sessionId,
InterviewMessage.MessageType.QUESTION.name(),
InterviewMessage.Sender.AI.name(),
nextQuestion.getQuestionContent(),
nextQuestion.getId()
);
return session;
}
private void aiGenerateQuestions(InterviewSession session, List<String> skills) {
List<InterviewQuestionProgress> progressList = new ArrayList<>();
JSONObject aiQuestionsJson = aiService.generateQuestionsOfAi(
session.getSessionId(),
skills,
session.getResumeContent(),
session.getTotalQuestions()
);
// ---> 解析AI返回的JSON数据获取问题列表 <---
JSONArray questions = aiQuestionsJson.getJSONArray("questions");
if (questions != null) {
questions.forEach(item -> {
JSONObject q = (JSONObject) item;
InterviewQuestionProgress progress = new InterviewQuestionProgress();
progress.setSessionId(session.getSessionId());
progress.setQuestionId(0L); // AI生成的问题没有本地ID
// ---> 解析单个问题内容 <---
progress.setQuestionContent(q.getString("content"));
progress.setStatus(InterviewQuestionProgress.Status.DEFAULT.name());
progressList.add(progress);
});
}
// 批量保存问题进度
if (CollectionUtil.isNotEmpty(progressList)) {
progressList.forEach(progressService::save);
}
}
private void localGenerateQuestions(InterviewSession session,
List<String> skills,
List<QuestionAndCategoryTreeListVO> selectedNodes) {
List<Question> localQuestionDataList = new ArrayList<>();
// 如果用户选择了题目 则使用用户选择的题目 否则直接使用全部的题目
if (CollectionUtil.isNotEmpty(selectedNodes)) {
List<QuestionAndCategoryTreeListVO> question = selectedNodes.stream()
.filter(node -> node.getType().equals("question"))
.toList();
if (CollectionUtil.isNotEmpty(question)) {
localQuestionDataList = question.stream()
.map(node -> {
return new Question().setId(node.getId()).setContent(node.getName());
}).toList();
}
}
if (CollectionUtil.isEmpty(localQuestionDataList)) {
localQuestionDataList = questionService.list(
new LambdaQueryWrapper<Question>()
.select(Question::getId, Question::getContent)
);
}
// ai调用返回的内容进行提取
JSONObject jsonObject = aiService.generateQuestionOfLocal(
session.getSessionId(),
localQuestionDataList,
skills,
session.getResumeContent(),
session.getTotalQuestions()
);
JSONArray questionIds = jsonObject.getJSONArray("question_ids");
List<Long> list = questionIds.toList(Long.class);
// 查询返回的内容 并将其保存为问题进度的相关数据
List<Question> questionList = questionService.list(
new LambdaQueryWrapper<Question>()
.in(Question::getId, list)
);
List<InterviewQuestionProgress> progressList = new ArrayList<>();
questionList.forEach(q -> {
InterviewQuestionProgress progress = new InterviewQuestionProgress();
progress.setSessionId(session.getSessionId());
progress.setQuestionId(q.getId());
progress.setQuestionContent(q.getContent());
progress.setStatus(InterviewQuestionProgress.Status.DEFAULT.name());
progressList.add(progress);
});
// 批量保存问题进度
if (CollectionUtil.isNotEmpty(progressList)) {
progressList.forEach(progressService::save);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public InterviewMessage getNextQuestion(String sessionId, Long progressId) {
// 获取下一个问题
InterviewQuestionProgress nextQuestion = progressService.getNextQuestion(sessionId);
if (Objects.isNull(nextQuestion)) {
return null;
}
// 判断是否在interview_message中存在
InterviewMessage interviewMessage = messageMapper.selectOne(
new LambdaQueryWrapper<InterviewMessage>()
.eq(InterviewMessage::getQuestionProgressId, nextQuestion.getId())
.orderByAsc(InterviewMessage::getId)
.last("LIMIT 1")
);
if (Objects.isNull(interviewMessage)) {
InterviewQuestionProgress prevQuestion = progressService.getById(progressId);
// 格式化返回的内容
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotBlank(prevQuestion.getFeedback())) {
sb.append(prevQuestion.getFeedback()).append("\n");
}
if (StringUtils.isNotBlank(prevQuestion.getSuggestions())) {
sb.append(prevQuestion.getSuggestions()).append("\n");
}
if (StringUtils.isNotBlank(prevQuestion.getAiAnswer())) {
sb.append(prevQuestion.getAiAnswer()).append("\n");
}
sb.append(nextQuestion.getQuestionContent());
interviewMessage = saveMessage(sessionId,
InterviewMessage.MessageType.QUESTION.name(),
InterviewMessage.Sender.AI.name(),
sb.toString(),
nextQuestion.getId()
);
}
return interviewMessage;
}
@Override
@Transactional(rollbackFor = Exception.class)
public InterviewQuestionProgress submitAnswer(SubmitAnswerDTO dto) {
// 1. 查询当前正在进行的这个问题
InterviewQuestionProgress currentProgress = progressService.getById(dto.getProgressId());
if (Objects.isNull(currentProgress) || !InterviewQuestionProgress.Status.ACTIVE.name().equals(currentProgress.getStatus())) {
throw new ApiException("问题进度不存在或已处理");
}
currentProgress.setUserAnswer(dto.getAnswer());
// 存储消息
saveMessage(dto.getSessionId(),
InterviewMessage.MessageType.ANSWER.name(),
InterviewMessage.Sender.USER.name(),
dto.getAnswer(),
currentProgress.getId()
);
// 2. 调用AI服务评估回答
List<InterviewQuestionProgress> context = progressService.list(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, currentProgress.getSessionId())
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.COMPLETED.name())
.orderByAsc(InterviewQuestionProgress::getId)
);
JSONObject evalResult = aiService.evaluateAnswer(
currentProgress.getSessionId(),
currentProgress.getQuestionContent(),
dto.getAnswer(),
context
);
// 3. ---> 解析AI返回的JSON评估结果并存入数据库 <---
currentProgress.setFeedback(evalResult.getString("feedback"));
currentProgress.setSuggestions(evalResult.getString("suggestions"));
currentProgress.setAiAnswer(evalResult.getString("aiAnswer"));
currentProgress.setScore(evalResult.getBigDecimal("score"));
currentProgress.setStatus(InterviewQuestionProgress.Status.COMPLETED.name());
progressService.updateById(currentProgress);
// 4. 将单题评估结果存入 evaluation 表用于分析
saveEvaluationRecord(currentProgress, evalResult);
// 5. ---> 解析AI的是否追问判断并处理追问逻辑 <---
if (evalResult.getBooleanValue("continueAsking", false)) {
// 创建一个新的、状态为ACTIVE的追问问题
InterviewQuestionProgress followUp = new InterviewQuestionProgress();
followUp.setSessionId(currentProgress.getSessionId());
followUp.setQuestionId(0L); // 追问问题没有本地ID
followUp.setQuestionContent(evalResult.getString("followUpQuestion"));
followUp.setStatus(InterviewQuestionProgress.Status.ACTIVE.name()); // 直接设为激活状态,作为下一个问题
progressService.save(followUp);
return followUp; // 将这个新的追问问题返回给前端
}
return currentProgress;
}
private void saveEvaluationRecord(InterviewQuestionProgress progress, JSONObject evalResult) {
InterviewEvaluation evaluation = new InterviewEvaluation();
evaluation.setSessionId(progress.getSessionId());
evaluation.setQuestionId(progress.getQuestionId());
evaluation.setUserAnswer(progress.getUserAnswer());
// ---> 解析AI评估结果并存入分析表 <---
evaluation.setAiFeedback(evalResult.getString("feedback"));
evaluation.setScore(evalResult.getBigDecimal("score"));
evaluationMapper.insert(evaluation);
}
@Override
public InterviewSession endInterview(String sessionId) {
InterviewSession session = this.getOne(new LambdaQueryWrapper<InterviewSession>()
.eq(InterviewSession::getSessionId, sessionId));
if (session == null) throw new RuntimeException("会话不存在");
List<InterviewQuestionProgress> completedProgresses = progressService.list(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, sessionId)
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.COMPLETED.name())
);
if (CollectionUtil.isEmpty(completedProgresses)) {
session.setStatus(InterviewSession.Status.COMPLETED.name());
this.baseMapper.updateById(session);
return session;
}
// 2. 调用AI服务生成最终报告
JSONObject finalReportJson = aiService.generateFinalReport(session, completedProgresses);
// 3. ---> 解析AI返回的最终报告JSON更新会话状态 <---
session.setStatus(InterviewSession.Status.COMPLETED.name());
session.setScore(finalReportJson.getBigDecimal("overallScore"));
session.setFinalReport(finalReportJson.toJSONString());
this.baseMapper.updateById(session);
return session;
}
/**
* 获取详细的面试复盘报告
*/
@Override
public InterviewReportResponse getInterviewReport(String sessionId) {
log.info("Fetching interview report for session id: {}", sessionId);
InterviewSession session = getOne(
new LambdaQueryWrapper<InterviewSession>()
.eq(InterviewSession::getSessionId, sessionId)
.last("LIMIT 1")
);
if (session == null) {
throw new IllegalArgumentException("找不到ID为 " + sessionId + " 的面试会话。");
}
List<InterviewQuestionProgress> progressList = progressService.list(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, sessionId)
.orderByAsc(InterviewQuestionProgress::getUpdatedTime)
);
List<InterviewReportResponse.QuestionDetail> questionDetails = progressList.stream().map(progress -> {
InterviewReportResponse.QuestionDetail detail = new InterviewReportResponse.QuestionDetail();
detail.setQuestionId(progress.getQuestionId());
detail.setQuestionContent(progress.getQuestionContent());
detail.setUserAnswer(progress.getUserAnswer());
detail.setAiFeedback(progress.getFeedback());
detail.setSuggestions(progress.getSuggestions());
detail.setScore(progress.getScore());
return detail;
}).collect(Collectors.toList());
InterviewReportResponse report = new InterviewReportResponse();
report.setSessionDetails(session);
report.setQuestionDetails(questionDetails);
List<InterviewMessage> interviewMessages = messageMapper.selectList(
new LambdaQueryWrapper<InterviewMessage>()
.eq(InterviewMessage::getSessionId, sessionId)
);
// 获取当前面试的 问题
InterviewQuestionProgress progress = progressService.getOne(
new LambdaQueryWrapper<InterviewQuestionProgress>()
.eq(InterviewQuestionProgress::getSessionId, sessionId)
.eq(InterviewQuestionProgress::getStatus, InterviewQuestionProgress.Status.ACTIVE.name())
.last("LIMIT 1")
);
if (Objects.nonNull(progress)) {
report.setCurrentQuestionId(progress.getQuestionId());
}
report.setMessages(interviewMessages);
return report;
}
private String parseResume(MultipartFile resume) throws IOException {
// 获取文件扩展名
String extName = FileNameUtil.extName(resume.getOriginalFilename());
// 1. 获取简历解析器
DocumentParser parser = documentParserManager.getParser(DocumentParserProvider.fromCode(extName));
// 2. 解析简历
return parser.parse(resume.getInputStream());
}
private InterviewMessage saveMessage(String sessionId, String messageType, String sender,
String content, Long questionId) {
int nextOrder = messageMapper.selectMaxOrderBySessionId(sessionId) + 1;
InterviewMessage message = new InterviewMessage()
.setSessionId(sessionId)
.setMessageType(messageType)
.setSender(sender)
.setContent(content)
.setQuestionProgressId(questionId)
.setMessageOrder(nextOrder);
messageMapper.insert(message);
return message;
}
}

View File

@@ -1,10 +1,30 @@
package com.qingqiu.interview.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingqiu.interview.common.constants.CommonConstant;
import com.qingqiu.interview.common.enums.CommonStateEnum;
import com.qingqiu.interview.dto.QuestionCategoryDTO;
import com.qingqiu.interview.dto.QuestionCategoryPageParams;
import com.qingqiu.interview.entity.Question;
import com.qingqiu.interview.entity.QuestionCategory;
import com.qingqiu.interview.mapper.QuestionCategoryMapper;
import com.qingqiu.interview.service.IQuestionCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingqiu.interview.service.QuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>
@@ -14,7 +34,288 @@ import org.springframework.stereotype.Service;
* @author huangpeng
* @since 2025-09-08
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class QuestionCategoryServiceImpl extends ServiceImpl<QuestionCategoryMapper, QuestionCategory> implements IQuestionCategoryService {
private final QuestionService questionService;
@Override
public List<QuestionCategory> getTreeList() {
List<QuestionCategory> allCategories = getAllValidCategories();
return buildCategoryTree(allCategories);
}
@Override
public List<QuestionCategory> getOptions() {
List<QuestionCategory> allCategories = getAllValidCategories();
return allCategories.stream()
.filter(category -> CommonStateEnum.ENABLED.getCode().equals(category.getState()))
.sorted(Comparator.comparingInt(QuestionCategory::getSort))
.collect(Collectors.toList());
}
@Override
@Transactional(rollbackFor = Exception.class)
public Long createCategory(QuestionCategoryDTO dto) {
// 检查名称是否重复
if (checkNameExists(dto.getName(), dto.getParentId(), null)) {
throw new RuntimeException("同一层级下分类名称不能重复");
}
validateParentCategory(dto.getParentId());
QuestionCategory category = new QuestionCategory();
BeanUtils.copyProperties(dto, category);
calculateLevelAndPath(category, dto.getParentId());
// 保存分类
save(category);
// 更新路径需要ID
updateCategoryPathAfterSave(category, dto.getParentId());
log.info("创建分类成功:{}", category);
return category.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCategory(QuestionCategoryDTO dto) {
QuestionCategory category = getById(dto.getId());
if (category == null) {
throw new RuntimeException("分类不存在");
}
// 检查名称是否重复(排除自身)
if (checkNameExists(dto.getName(), category.getParentId(), dto.getId())) {
throw new RuntimeException("同一层级下分类名称不能重复");
}
// 检查是否修改了父分类
// if (!category.getParentId().equals(dto.getParentId())) {
// throw new RuntimeException("不支持直接修改父分类,请使用移动分类功能");
// }
BeanUtils.copyProperties(dto, category);
category.setUpdatedTime(LocalDateTime.now());
updateById(category);
log.info("更新分类成功:{}", category);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCategory(Long id) {
// 1. 查找所有需要删除的分类ID包括子分类
List<Long> categoryIdsToDelete = getAllCategoryIdsToDelete(id);
if (CollectionUtil.isEmpty(categoryIdsToDelete)) {
return;
}
// 2. 删除所有相关分类
this.removeByIds(categoryIdsToDelete);
// 3. 删除关联的题目数据
questionService.remove(
new LambdaQueryWrapper<Question>()
.in(Question::getCategoryId, categoryIdsToDelete)
);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateState(Long id, Integer state) {
QuestionCategory category = new QuestionCategory();
category.setId(id);
category.setState(state);
category.setUpdatedTime(LocalDateTime.now());
updateById(category);
log.info("更新分类状态成功id={}, state={}", id, state);
}
@Override
public QuestionCategory getCategoryDetail(Long id) {
QuestionCategory category = getById(id);
if (category != null && !CommonConstant.ONE.equals(category.getDeleted())) {
// 设置父分类名称
if (!CommonConstant.ROOT_PARENT_ID.equals(category.getParentId())) {
QuestionCategory parent = getById(category.getParentId());
if (parent != null) {
category.setParentName(parent.getName());
}
}
return category;
}
return null;
}
@Override
public Page<QuestionCategory> getCategoryPage(QuestionCategoryPageParams query) {
return page(
Page.of(query.getCurrent(), query.getSize()),
new LambdaQueryWrapper<QuestionCategory>()
.like(StringUtils.hasText(query.getName()), QuestionCategory::getName, query.getName())
.eq(QuestionCategory::getState, query.getState())
.or(Objects.nonNull(query.getParentId()), wrapper -> {
wrapper.eq(QuestionCategory::getParentId, query.getParentId())
.or()
.apply("find_in_set({0}, ancestor)", query.getParentId())
;
})
.orderByDesc(QuestionCategory::getSort)
.orderByDesc(QuestionCategory::getCreatedTime)
);
}
@Override
public List<QuestionCategory> searchByName(String name) {
if (!StringUtils.hasText(name)) {
return Collections.emptyList();
}
List<QuestionCategory> allCategories = getAllValidCategories();
return allCategories.stream()
.filter(category -> category.getName().toLowerCase().contains(name.toLowerCase()))
.sorted(Comparator.comparingInt(QuestionCategory::getSort))
.collect(Collectors.toList());
}
@Override
public boolean checkNameExists(String name, Long parentId, Long excludeId) {
List<QuestionCategory> allCategories = getAllValidCategories();
return allCategories.stream()
.filter(category -> category.getName().equals(name))
.filter(category -> parentId.equals(category.getParentId()))
.anyMatch(category -> excludeId == null || !excludeId.equals(category.getId()));
}
@Override
public List<QuestionCategory> batchFindByAncestorIdsUnion(List<Long> searchIds) {
return baseMapper.batchFindByAncestorIdsUnion(searchIds);
}
// ============ 私有方法 ============
private List<QuestionCategory> getAllValidCategories() {
// LambdaQueryWrapper<QuestionCategory> wrapper = new LambdaQueryWrapper<>();
// wrapper.eq(QuestionCategory::getDeleted, CommonConstant.ZERO)
// .orderByAsc(QuestionCategory::getSort);
return list(
new LambdaQueryWrapper<QuestionCategory>()
.orderByDesc(QuestionCategory::getSort)
.orderByDesc(QuestionCategory::getCreatedTime)
);
}
private List<QuestionCategory> buildCategoryTree(List<QuestionCategory> categories) {
if (CollectionUtil.isEmpty(categories)) {
return Collections.emptyList();
}
// 按父ID分组
Map<Long, List<QuestionCategory>> parentIdMap = categories.stream()
.collect(Collectors.groupingBy(QuestionCategory::getParentId));
// 设置子节点并计算子节点数量
categories.forEach(category -> {
List<QuestionCategory> children = parentIdMap.get(category.getId());
if (!CollectionUtil.isEmpty(children)) {
category.setChildren(children);
category.setChildrenCount(children.size());
children.sort(Comparator.comparingInt(QuestionCategory::getSort));
} else {
category.setChildrenCount(0);
}
});
// 返回根节点
return parentIdMap.getOrDefault(CommonConstant.ROOT_PARENT_ID, Collections.emptyList());
}
private void validateParentCategory(Long parentId) {
if (!CommonConstant.ROOT_PARENT_ID.equals(parentId)) {
QuestionCategory parentCategory = getById(parentId);
if (parentCategory == null || CommonConstant.ONE.equals(parentCategory.getDeleted())) {
throw new RuntimeException("父分类不存在或已被删除");
}
if (CommonStateEnum.DISABLED.getCode().equals(parentCategory.getState())) {
throw new RuntimeException("父分类已被禁用,无法创建子分类");
}
}
}
private void calculateLevelAndPath(QuestionCategory category, Long parentId) {
if (CommonConstant.ROOT_PARENT_ID.equals(parentId)) {
category.setLevel(1);
} else {
QuestionCategory parentCategory = getById(parentId);
category.setLevel(parentCategory.getLevel() + 1);
if (category.getLevel() > 5) {
throw new RuntimeException("分类层级过深最多支持5级分类");
}
}
}
@Transactional(rollbackFor = Exception.class)
public void updateCategoryPathAfterSave(QuestionCategory category, Long parentId) {
if (!CommonConstant.ROOT_PARENT_ID.equals(parentId)) {
QuestionCategory parentCategory = getById(parentId);
String newPath = parentCategory.getAncestor() + "," + category.getId();
category.setAncestor(newPath);
updateById(category);
} else {
category.setAncestor(String.valueOf(category.getId()));
updateById(category);
}
}
private List<QuestionCategory> findDescendants(List<QuestionCategory> allCategories, Long parentId) {
List<QuestionCategory> descendants = new ArrayList<>();
allCategories.stream()
.filter(category -> parentId.equals(category.getParentId()))
.forEach(category -> {
descendants.add(category);
descendants.addAll(findDescendants(allCategories, category.getId()));
});
return descendants;
}
/**
* 递归获取所有需要删除的分类ID包括子分类
*
* @param parentId 父分类ID
* @return 所有需要删除的分类ID列表
*/
private List<Long> getAllCategoryIdsToDelete(Long parentId) {
List<Long> result = new ArrayList<>();
result.add(parentId);
// 查找直接子分类
List<QuestionCategory> children = this.list(
new LambdaQueryWrapper<QuestionCategory>()
.eq(QuestionCategory::getParentId, parentId)
);
// 递归查找所有子分类
for (QuestionCategory child : children) {
result.addAll(getAllCategoryIdsToDelete(child.getId()));
}
return result;
}
}

View File

@@ -0,0 +1,396 @@
package com.qingqiu.interview.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingqiu.interview.common.enums.LLMProvider;
import com.qingqiu.interview.common.constants.CommonConstant;
import com.qingqiu.interview.common.utils.TreeUtil;
import com.qingqiu.interview.dto.QuestionOptionsDTO;
import com.qingqiu.interview.dto.QuestionPageParams;
import com.qingqiu.interview.entity.Question;
import com.qingqiu.interview.entity.QuestionCategory;
import com.qingqiu.interview.mapper.QuestionMapper;
import com.qingqiu.interview.service.IQuestionCategoryService;
import com.qingqiu.interview.service.QuestionClassificationService;
import com.qingqiu.interview.service.QuestionService;
import com.qingqiu.interview.service.llm.LlmService;
import com.qingqiu.interview.service.parser.DocumentParser;
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
private final QuestionMapper questionMapper;
private final QuestionClassificationService classificationService;
private final List<DocumentParser> documentParserList; // This will be injected by Spring
private final LlmService llmService;
private final IQuestionCategoryService questionCategoryService;
/**
* 分页查询题库
*/
@Override
public Page<Question> getQuestionPage(QuestionPageParams params) {
log.info("分页查询题库,当前页: {}, 每页数量: {}", params.getCurrent(), params.getSize());
return questionMapper.queryPage(
Page.of(params.getCurrent(), params.getSize()),
params
);
}
/**
* 新增题目,并进行重复校验
*/
@Override
public void addQuestion(Question question) {
validateQuestion(question.getContent(), null);
log.info("新增题目: {}", question.getContent());
questionMapper.insert(question);
}
/**
* 更新题目,并进行重复校验
*/
@Override
public void updateQuestion(Question question) {
validateQuestion(question.getContent(), question.getId());
log.info("更新题目ID: {}", question.getId());
questionMapper.updateById(question);
}
/**
* 删除题目
*/
@Override
public void deleteQuestion(Long id) {
log.info("删除题目ID: {}", id);
questionMapper.deleteById(id);
}
/**
* AI批量导入题库并进行去重
*/
@Override
public void importQuestionsFromFile(MultipartFile file) throws IOException {
log.info("开始从文件导入题库: {}", file.getOriginalFilename());
String fileExtension = getFileExtension(file.getOriginalFilename());
DocumentParser parser = documentParserList.stream()
.filter(p -> p.getSupportedType().equals(fileExtension))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("不支持的文件类型: " + fileExtension));
String content = parser.parse(file.getInputStream());
List<Question> questionsFromAi = classificationService.classifyQuestions(content);
int newQuestionsCount = 0;
for (Question question : questionsFromAi) {
try {
validateQuestion(question.getContent(), null);
questionMapper.insert(question);
newQuestionsCount++;
} catch (IllegalArgumentException e) {
log.warn("跳过重复题目: {}", question.getContent());
}
}
log.info("成功导入 {} 个新题目,跳过 {} 个重复题目。", newQuestionsCount, questionsFromAi.size() - newQuestionsCount);
}
/**
* 调用AI检查题库中的数据是否重复
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void useAiCheckQuestionData() {
// 查询数据库
List<Question> questions = questionMapper.selectList(
new LambdaQueryWrapper<Question>()
.orderByDesc(Question::getCreatedTime)
);
// 组装prompt
if (CollectionUtil.isEmpty(questions)) {
return;
}
String prompt = getPrompt(questions);
log.info("发送内容: {}", prompt);
// 验证token上下文长度
Integer promptTokens = llmService.getPromptTokens(prompt);
log.info("当前prompt长度: {}", promptTokens);
String chat = llmService.chat(prompt, LLMProvider.DEEPSEEK);
// 调用AI
log.info("AI返回内容: {}", chat);
JSONObject parse = JSONObject.parse(chat);
JSONArray questionsIds = parse.getJSONArray("questions");
List<Long> list = questionsIds.toList(Long.class);
questionMapper.delete(
new LambdaQueryWrapper<Question>()
.notIn(Question::getId, list)
);
}
@NotNull
private static String getPrompt(List<Question> questions) {
JSONArray jsonArray = new JSONArray();
for (Question question : questions) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", question.getId());
jsonObject.put("content", question.getContent());
jsonArray.add(jsonObject);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", jsonArray);
return String.format("""
你是一个数据清洗与去重专家。你的任务是从以下文本列表中,识别出语义相同或高度相似的条目,并为每一组相似条目筛选出一个最规范、最简洁的代表性版本。
【去重规则】
1. **语义核心优先**:忽略无关的修饰词、标点符号、后缀(如“:2”、大小写和空格。
2. **合并同类项**:将表达同一主题或问题的文本归为一组。
3. **选择标准**:从每一组中,选出那个最完整、最简洁、且没有多余符号(如序号、特殊后缀)的版本作为代表。如果两个版本质量相当,优先选择更短的那个。
4. **保留原意**:确保选出的代表版本没有改变原文本的核心含义。
请按照下述格式返回,已被剔除掉的数据无需返回
{
"questions": [1, 2, 3, .....]
}
分类规则:
1. 只返回JSON不要其他解释文字
2. 请严格按照API接口形式返回不要返回任何额外的文字内容包括'```json```'!!!!
3. 请严格按照网络接口的形式返回JSON数据
【请处理以下数据列表】:
%s
""", jsonObject.toJSONString());
}
/**
* 校验题目内容是否重复
*
* @param content 题目内容
* @param currentId 当前题目ID更新时传入用于排除自身
*/
private void validateQuestion(String content, Long currentId) {
Question existingQuestion = questionMapper.selectByContent(content);
if (existingQuestion != null && (!existingQuestion.getId().equals(currentId))) {
throw new IllegalArgumentException("题目内容已存在,请勿重复添加。");
}
}
private String getFileExtension(String fileName) {
if (fileName == null || fileName.lastIndexOf('.') == -1) {
return "";
}
return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
}
@Override
public List<QuestionAndCategoryTreeListVO> getTreeListCategory(QuestionOptionsDTO dto) {
if (StringUtils.isNoneBlank(dto.getDifficulty()) && dto.getDifficulty().equals("ALL")) {
dto.setDifficulty(null);
}
// 获取分类树列表
List<QuestionCategory> treeList = questionCategoryService.getTreeList();
List<QuestionCategory> questionCategories = new ArrayList<>();
if (CollectionUtil.isNotEmpty(dto.getCategoryIds())) {
questionCategories = questionCategoryService.batchFindByAncestorIdsUnion(dto.getCategoryIds());
if (CollectionUtil.isNotEmpty(questionCategories)) {
treeList = TreeUtil.buildTree(
questionCategories,
QuestionCategory::getId,
QuestionCategory::getParentId,
QuestionCategory::getChildren,
CommonConstant.ROOT_PARENT_ID
);
}
}
// 获取所有题目列表
List<Question> questionList = list(
new LambdaQueryWrapper<Question>()
.in(CollectionUtil.isNotEmpty(dto.getCategoryIds()), Question::getCategoryId,
dto.getCategoryIds())
.eq(StringUtils.isNotBlank(dto.getDifficulty()), Question::getDifficulty, dto.getDifficulty())
.eq(Question::getDeleted, 0)
);
// 转换为VO对象并整合题目数据
List<QuestionAndCategoryTreeListVO> voList = convertToVOListWithQuestions(treeList, questionList);
// 设置根节点的题目总数
if (CollectionUtil.isNotEmpty(voList)) {
Integer i = calcCount(voList);
log.info("根节点题目总数: {}", i);
QuestionAndCategoryTreeListVO rootVO = new QuestionAndCategoryTreeListVO();
rootVO.setId(0L);
rootVO.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
rootVO.setName("全部题目");
rootVO.setType("root");
rootVO.setChildren(voList);
rootVO.setCount(i);
return List.of(rootVO);
}
return voList;
}
@Override
public List<Question> selectLocalQuestions(List<String> skills, String difficulty, int count) {
// TODO: 实现更智能的选题逻辑,例如:
// 1. 根据技能(skills)匹配题目的`tags`或`category_name`。
// 2. 使用`difficulty`进行筛选。
// 3. 随机选取`count`道题目。
// 4. 此处仅为简单示例,随机获取指定数量的题目。
LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.last("ORDER BY RAND() LIMIT " + count);
return this.baseMapper.selectList(queryWrapper);
}
/**
* 将QuestionCategory列表转换为QuestionAndCategoryTreeListVO列表并整合题目数据
*
* @param categoryList 分类列表
* @param questionList 题目列表
* @return QuestionAndCategoryTreeListVO列表
*/
private List<QuestionAndCategoryTreeListVO> convertToVOListWithQuestions(
List<QuestionCategory> categoryList,
List<Question> questionList) {
if (CollectionUtil.isEmpty(categoryList)) {
return List.of();
}
// 按分类ID分组题目数据
Map<Long, List<Question>> questionsByCategoryId = questionList.stream()
.filter(Objects::nonNull)
.filter(question -> question.getCategoryId() != null)
.collect(Collectors.groupingBy(Question::getCategoryId));
return categoryList.stream()
.map(category -> convertToVOWithQuestions(category, questionsByCategoryId))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
/**
* 将单个QuestionCategory转换为QuestionAndCategoryTreeListVO并整合题目数据
*
* @param category 分类对象
* @param questionsByCategoryId 按分类ID分组的题目数据
* @return QuestionAndCategoryTreeListVO对象
*/
private QuestionAndCategoryTreeListVO convertToVOWithQuestions(
QuestionCategory category,
Map<Long, List<Question>> questionsByCategoryId) {
if (category == null) {
return null;
}
// 创建VO对象
QuestionAndCategoryTreeListVO vo = new QuestionAndCategoryTreeListVO();
// 复制基本属性
vo.setId(category.getId());
vo.setName(category.getName());
vo.setType("category");
vo.setCount(0);
vo.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
// 处理子节点(包括子分类和题目)
List<QuestionAndCategoryTreeListVO> childrenVOs = new ArrayList<>();
// 先处理子分类
if (CollectionUtil.isNotEmpty(category.getChildren())) {
for (QuestionCategory childCategory : category.getChildren()) {
QuestionAndCategoryTreeListVO childVO = convertToVOWithQuestions(childCategory, questionsByCategoryId);
if (childVO != null) {
childrenVOs.add(childVO);
}
}
}
// 再处理当前分类下的题目
List<Question> questionsInCategory = questionsByCategoryId.getOrDefault(category.getId(), List.of());
if (CollectionUtil.isNotEmpty(questionsInCategory)) {
for (Question question : questionsInCategory) {
QuestionAndCategoryTreeListVO questionVO = convertQuestionToVO(question);
if (questionVO != null) {
childrenVOs.add(questionVO);
}
}
}
// 设置子节点
if (CollectionUtil.isNotEmpty(childrenVOs)) {
vo.setChildren(childrenVOs);
}
return vo;
}
/**
* 将Question转换为QuestionAndCategoryTreeListVO
*
* @param question 题目对象
* @return QuestionAndCategoryTreeListVO对象
*/
private QuestionAndCategoryTreeListVO convertQuestionToVO(Question question) {
if (question == null) {
return null;
}
QuestionAndCategoryTreeListVO vo = new QuestionAndCategoryTreeListVO();
vo.setId(question.getId());
// 使用题目内容作为名称,可以根据需要修改
vo.setName(question.getContent());
// 题目下面没有子节点
vo.setChildren(List.of());
vo.setType("question");
vo.setCount(0); // 题目节点没有子节点count设为0
vo.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
return vo;
}
private Integer calcCount(List<QuestionAndCategoryTreeListVO> voList) {
Integer count = 0;
if (CollectionUtil.isNotEmpty(voList)) {
for (QuestionAndCategoryTreeListVO vo : voList) {
Integer currCount = 0;
if (vo.getType().equals("question")) {
count++;
currCount++;
}
if (CollectionUtil.isNotEmpty(vo.getChildren())) {
Integer i = calcCount(vo.getChildren());
count += i;
currCount += i;
}
vo.setCount(currCount);
}
}
return count;
}
}

View File

@@ -0,0 +1,40 @@
package com.qingqiu.interview.service.impl.parser;
import com.qingqiu.interview.common.enums.DocumentParserProvider;
import com.qingqiu.interview.service.parser.DocumentParser;
import com.qingqiu.interview.service.parser.DocumentParserManager;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @author qingqiu
* @date 2025/9/18 16:45
*/
@Service
public class DocumentParserManagerImpl implements DocumentParserManager {
private final Map<DocumentParserProvider, DocumentParser> factories;
public DocumentParserManagerImpl(List<DocumentParser> strategies) {
this.factories = strategies.stream()
.collect(Collectors.toMap(
DocumentParser::getSupportedProvider,
Function.identity()
));
}
@Override
public DocumentParser getParser(DocumentParserProvider provider) {
DocumentParser parser = factories.get(provider);
if (parser == null) {
throw new IllegalArgumentException("不支持的AI type: " + provider);
}
return parser;
}
}

Some files were not shown because too many files have changed in this diff Show More