Compare commits
7 Commits
dev
...
alibaba-re
| Author | SHA1 | Date | |
|---|---|---|---|
| 80dcb23bbc | |||
| 5fb4ed754c | |||
| fac1346104 | |||
| 5711d611f2 | |||
| d3b5ca0033 | |||
| df5aa0b9c6 | |||
| 08b4b8b206 |
134
pom.xml
134
pom.xml
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.4.5</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.qingqiu</groupId>
|
||||
@@ -13,6 +13,7 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>AI-Interview</name>
|
||||
<description>AI-Interview</description>
|
||||
<!-- TODO: 考虑删除空的元数据元素 -->
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
@@ -28,6 +29,9 @@
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<spring-ai.version>1.0.0</spring-ai.version>
|
||||
<spring-ai-alibaba.version>1.0.0.2</spring-ai-alibaba.version>
|
||||
<spring-boot.version>3.4.5</spring-boot.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- MyBatis-Plus -->
|
||||
@@ -53,26 +57,58 @@
|
||||
<artifactId>spring-boot-starter-webflux</artifactId> <!-- 用于 WebClient -->
|
||||
</dependency>
|
||||
|
||||
<!-- <!– Spring AI Dependencies –>-->
|
||||
<!-- TODO: 考虑删除已注释的依赖 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.ai</groupId>-->
|
||||
<!-- <artifactId>spring-ai-openai-spring-boot-starter</artifactId>-->
|
||||
<!-- <exclusions>-->
|
||||
<!-- <exclusion>-->
|
||||
<!-- <groupId>com.alibaba.cloud.ai</groupId>-->
|
||||
<!-- <artifactId>spring-ai-alibaba-autoconfigure</artifactId>-->
|
||||
<!-- </exclusion>-->
|
||||
<!-- <exclusion>-->
|
||||
<!-- <groupId>org.springframework.ai</groupId>-->
|
||||
<!-- <artifactId>spring-ai-core</artifactId>-->
|
||||
<!-- </exclusion>-->
|
||||
<!-- </exclusions>-->
|
||||
<!-- <version>1.0.0-SNAPSHOT</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>dashscope-sdk-java</artifactId>
|
||||
<version>2.21.5</version>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-model-openai</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud.ai</groupId>
|
||||
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- TODO: 检查内存相关依赖是否都需要 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud.ai</groupId>
|
||||
<artifactId>spring-ai-alibaba-starter-memory</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud.ai</groupId>
|
||||
<artifactId>spring-ai-alibaba-starter-memory-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud.ai</groupId>
|
||||
<artifactId>spring-ai-alibaba-starter-memory-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>5.2.0</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- 集成redis依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- TODO: 考虑删除已注释的依赖 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.alibaba</groupId>-->
|
||||
<!-- <artifactId>dashscope-sdk-java</artifactId>-->
|
||||
<!-- <version>2.21.5</version>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
@@ -129,16 +165,28 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
<!-- <dependencies>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.ai</groupId>-->
|
||||
<!-- <artifactId>spring-ai-bom</artifactId>-->
|
||||
<!-- <version>1.0.0-M5</version> <!– 或最新版本 –>-->
|
||||
<!-- <type>pom</type>-->
|
||||
<!-- <scope>import</scope>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- </dependencies>-->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud.ai</groupId>
|
||||
<artifactId>spring-ai-alibaba-bom</artifactId>
|
||||
<version>${spring-ai-alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bom</artifactId>
|
||||
<version>${spring-ai.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-bom</artifactId>
|
||||
@@ -147,10 +195,19 @@
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<finalName>ai-interview</finalName>
|
||||
<plugins>
|
||||
<!-- TODO: 检查Spring Boot插件版本是否与父POM一致 -->
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
</plugin>
|
||||
<!-- TODO: 考虑在正式环境中启用测试 -->
|
||||
<!-- maven 打包时跳过测试 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -161,33 +218,6 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.qingqiu.interview.ai.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Message implements Serializable {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String role;
|
||||
|
||||
private String content;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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<LLMProvider, AIClientFactory> factories;
|
||||
|
||||
public AIClientManager(List<AIClientFactory> strategies) {
|
||||
this.factories = strategies.stream()
|
||||
.collect(Collectors.toMap(
|
||||
AIClientFactory::getSupportedProvider,
|
||||
Function.identity()
|
||||
));
|
||||
}
|
||||
|
||||
public AIClientService getClient(LLMProvider provider) {
|
||||
// String factoryName = aiType + "ClientFactory";
|
||||
AIClientFactory factory = factories.get(provider);
|
||||
if (factory == null) {
|
||||
throw new IllegalArgumentException("不支持的AI type: " + provider);
|
||||
}
|
||||
return factory.createAIClient();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class DeepSeekClientFactory implements AIClientFactory{
|
||||
@Override
|
||||
public AIClientService createAIClient() {
|
||||
return SpringApplicationContextUtil.getBean(DeepSeekClientServiceImpl.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LLMProvider getSupportedProvider() {
|
||||
return LLMProvider.DEEPSEEK;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class QwenClientFactory implements AIClientFactory{
|
||||
@Override
|
||||
public AIClientService createAIClient() {
|
||||
return SpringApplicationContextUtil.getBean(QwenClientServiceImpl.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LLMProvider getSupportedProvider() {
|
||||
return LLMProvider.QWEN;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.qingqiu.interview.ai.service;
|
||||
|
||||
import com.alibaba.dashscope.common.Message;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AIClientService {
|
||||
public abstract String chatCompletion(String prompt);
|
||||
|
||||
public String chatCompletion(List<Message> messages) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.qingqiu.interview.ai.service.impl;
|
||||
|
||||
import com.alibaba.dashscope.common.Message;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.qingqiu.interview.ai.service.AIClientService;
|
||||
import com.qingqiu.interview.common.service.HttpService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.qingqiu.interview.common.utils.AIUtils.createUserMessage;
|
||||
|
||||
/**
|
||||
* deepseek 接入
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DeepSeekClientServiceImpl extends AIClientService {
|
||||
|
||||
private final HttpService httpService;
|
||||
|
||||
@Value("${deepseek.api-url}")
|
||||
private String apiUrl;
|
||||
|
||||
@Value("${deepseek.api-key}")
|
||||
private String apiKey;
|
||||
|
||||
|
||||
@Override
|
||||
public String chatCompletion(String prompt) {
|
||||
return chatCompletion(Collections.singletonList(createUserMessage(prompt)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chatCompletion(List<Message> messages) {
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("type", "json_object");
|
||||
Map<String, Object> requestBody = Map.of(
|
||||
"model", "deepseek-chat",
|
||||
"messages", messages,
|
||||
"max_tokens", 8192,
|
||||
"response_format", Map.of("type", "json_object")
|
||||
);
|
||||
String res = httpService.postWithAuth(
|
||||
apiUrl,
|
||||
requestBody,
|
||||
String.class,
|
||||
"Bearer " + apiKey
|
||||
).block();
|
||||
if (StringUtils.isNotBlank(res)) {
|
||||
JSONObject jsonRes = JSONObject.parse(res);
|
||||
JSONArray choices = jsonRes.getJSONArray("choices");
|
||||
JSONObject resContent = choices.getJSONObject(0);
|
||||
JSONObject message = resContent.getJSONObject("message");
|
||||
return message.getString("content");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.qingqiu.interview.ai.service.impl;
|
||||
|
||||
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;
|
||||
import com.qingqiu.interview.ai.service.AIClientService;
|
||||
import com.qingqiu.interview.common.res.ResultCode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static com.qingqiu.interview.common.constants.QwenModelConstant.QWEN_PLUS_LATEST;
|
||||
import static com.qingqiu.interview.common.utils.AIUtils.createUserMessage;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class QwenClientServiceImpl extends AIClientService {
|
||||
|
||||
@Value("${dashscope.api-key}")
|
||||
private String apiKey;
|
||||
|
||||
private final Generation generation;
|
||||
|
||||
@Override
|
||||
public String chatCompletion(String prompt) {
|
||||
return chatCompletion(Collections.singletonList(createUserMessage(prompt)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chatCompletion(List<Message> messages) {
|
||||
|
||||
GenerationParam param = GenerationParam.builder()
|
||||
.model(QWEN_PLUS_LATEST) // 可根据需要更换模型
|
||||
.messages(messages)
|
||||
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
|
||||
.responseFormat(ResponseFormat.builder().type(ResponseFormat.JSON_OBJECT).build())
|
||||
.apiKey(apiKey)
|
||||
.build();
|
||||
|
||||
GenerationResult result = null;
|
||||
try {
|
||||
result = generation.call(param);
|
||||
return result.getOutput().getChoices().get(0).getMessage().getContent();
|
||||
} catch (NoApiKeyException e) {
|
||||
log.error("没有api key,请先确认配置!");
|
||||
throw new com.qingqiu.interview.common.ex.ApiException(ResultCode.INTERNAL);
|
||||
} catch (ApiException | InputRequiredException e) {
|
||||
log.error("调用AI服务失败", e);
|
||||
throw new com.qingqiu.interview.common.ex.ApiException(ResultCode.INTERNAL);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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 {
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.qingqiu.interview.aspect;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* <h1>
|
||||
* ai聊天的切面
|
||||
* </h1>
|
||||
*
|
||||
* @author qingqiu
|
||||
* @date 2025/9/18 13:00
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class AiChatLogAspect {
|
||||
|
||||
public AiChatLogAspect() {
|
||||
|
||||
}
|
||||
|
||||
@Pointcut("@annotation(com.qingqiu.interview.annotation.AiChatLog)")
|
||||
public void logPointCut() {
|
||||
}
|
||||
|
||||
@Around("logPointCut()")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
Object result = point.proceed();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.qingqiu.interview.common.constants;
|
||||
|
||||
/**
|
||||
* 聊天相关常量类
|
||||
* 定义了聊天功能中使用的各种常量值
|
||||
*/
|
||||
public class ChatConstant {
|
||||
|
||||
/**
|
||||
* MySQL聊天记录存储的Bean名称
|
||||
*/
|
||||
public static final String MYSQL_CHAT_MEMORY_BEAN_NAME = "mysql-chat-memory";
|
||||
|
||||
/**
|
||||
* Redis聊天记录存储的Bean名称
|
||||
*/
|
||||
public static final String REDIS_CHAT_MEMORY_BEAN_NAME = "redis-chat-memory";
|
||||
|
||||
/**
|
||||
* 聊天记录最大保存消息数
|
||||
*/
|
||||
public static final Integer MAX_MESSAGES = 100;
|
||||
|
||||
/**
|
||||
* DashScope聊天模型的Bean名称
|
||||
*/
|
||||
public static final String DASH_SCOPE_CHAT_MODEL_BEAN_NAME = "dash-scope-chat-model";
|
||||
public static final String OPEN_AI_CHAT_MODEL_BEAN_NAME = "open-ai-chat-model";
|
||||
|
||||
/**
|
||||
* DashScope聊天客户端的Bean名称
|
||||
*/
|
||||
public static final String DASH_SCOPE_CHAT_CLIENT_BEAN_NAME = "dash-scope-chat-client";
|
||||
|
||||
/**
|
||||
* OpenAI聊天客户端的Bean名称
|
||||
*/
|
||||
public static final String OPEN_AI_CHAT_CLIENT_BEAN_NAME = "open-ai-chat-client";
|
||||
|
||||
/**
|
||||
* 最大补全token数量
|
||||
*/
|
||||
public static final Integer MAX_COMPLETION_TOKENS = 8192;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.qingqiu.interview.dto;
|
||||
package com.qingqiu.interview.common.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
@@ -1,41 +0,0 @@
|
||||
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 {
|
||||
|
||||
public static Message createMessage(String role, String content) {
|
||||
return Message.builder()
|
||||
.role(role)
|
||||
.content(content)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Message createUserMessage(String prompt) {
|
||||
return createMessage(Role.USER.getValue(), prompt);
|
||||
}
|
||||
|
||||
public static Message createAIMessage(String prompt) {
|
||||
return createMessage(Role.ASSISTANT.getValue(), prompt);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package com.qingqiu.interview.common.utils;
|
||||
|
||||
import org.springframework.ai.chat.messages.SystemMessage;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.chat.prompt.PromptTemplate;
|
||||
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 提示模板工具类
|
||||
*/
|
||||
public class PromptTemplateUtils {
|
||||
|
||||
/**
|
||||
* 获取提取技能的提示
|
||||
*
|
||||
* @param resumeContent 简历内容
|
||||
* @return 提示
|
||||
*/
|
||||
public static Prompt getExtractSkillsPrompt(String resumeContent) {
|
||||
SystemMessage systemMessage = new SystemMessage("""
|
||||
你是一位资深的技术面试官,以严格和深入著称。
|
||||
你需要从提供的简历内容中,提取出所有与职位相关的技能。
|
||||
请按照以下JSON格式返回:
|
||||
{"skills": ["技能1", "技能2", "..."]}
|
||||
""");
|
||||
UserMessage userMessage = new UserMessage(resumeContent);
|
||||
return new Prompt(List.of(userMessage, systemMessage));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取AI面试官的提示
|
||||
*
|
||||
* @param params 参数
|
||||
* @return 提示
|
||||
*/
|
||||
public static Prompt getAiInterviewerPrompt(Map<String, Object> params) {
|
||||
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("""
|
||||
你是一位经验丰富的软件开发技术面试官,具备以下特质:
|
||||
|
||||
## 专业能力
|
||||
- 拥有10年以上软件开发和团队管理经验
|
||||
- 熟悉各种主流技术栈和架构模式
|
||||
- 擅长通过技术面试评估候选人的真实能力
|
||||
- 能够设计多层次、递进式的面试问题
|
||||
|
||||
## 面试原则
|
||||
1. **精准匹配**: 问题必须紧密结合岗位要求和候选人背景
|
||||
2. **层次递进**: 从基础概念到深度应用,从理论到实践
|
||||
3. **场景化考察**: 基于真实项目场景设计问题
|
||||
4. **全面评估**: 涵盖技术深度、问题解决能力、系统思维
|
||||
## 本岗位招聘要求
|
||||
[{jobRequirements}]
|
||||
|
||||
## 输出要求
|
||||
- 严格按照指定的JSON格式输出
|
||||
- 不得包含任何JSON格式之外的内容
|
||||
- 不得添加代码块标记(```json)或其他解释性文字
|
||||
- 确保生成的问题数量与要求完全一致
|
||||
""");
|
||||
PromptTemplate userPromptTemplate = new PromptTemplate("""
|
||||
请根据岗位招聘要求设计 {count} 道技术面试题。
|
||||
|
||||
## 候选人信息
|
||||
|
||||
### 技术栈
|
||||
{skills}
|
||||
|
||||
### 简历内容
|
||||
{resume}
|
||||
|
||||
## 面试题设计要求
|
||||
|
||||
### 覆盖维度
|
||||
1. **基础理论** (20%): 核心概念、原理机制
|
||||
2. **项目实践** (40%): 具体项目中的技术难点和解决方案
|
||||
3. **系统设计** (20%): 架构思维、技术选型、性能优化
|
||||
4. **问题解决** (20%): 调试能力、故障排查、代码优化
|
||||
|
||||
### 难度分布
|
||||
- 基础题 (30%): 验证核心技能掌握情况
|
||||
- 进阶题 (50%): 考察深度理解和实际应用
|
||||
- 高阶题 (20%): 评估架构能力和创新思维
|
||||
|
||||
### 问题类型
|
||||
- **概念阐述**: "请解释..."、"什么是..."
|
||||
- **场景分析**: "在你的XX项目中..."、"如果遇到XX问题..."
|
||||
- **方案设计**: "如何设计..."、"请给出..."
|
||||
- **比较选择**: "XX和YY的区别..."、"为什么选择..."
|
||||
|
||||
## 输出格式
|
||||
必须严格按照以下JSON格式输出,不得有任何偏差:
|
||||
|
||||
{jsonRes}
|
||||
|
||||
请立即开始生成面试题:
|
||||
""");
|
||||
String s = """
|
||||
{
|
||||
"questions": [
|
||||
{
|
||||
"id": "ai-gen-1",
|
||||
"content": "问题内容..."
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
params.put("jsonRes", s);
|
||||
return new Prompt(List.of(userPromptTemplate.createMessage(params), systemPromptTemplate.createMessage(params)));
|
||||
}
|
||||
|
||||
public static Prompt getLocalInterviewPrompt(Map<String, Object> params) {
|
||||
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("""
|
||||
你是一位资深的技术面试专家。
|
||||
## 你的专业背景
|
||||
- 10年+ 软件开发和技术管理经验
|
||||
- 熟悉前端、后端、全栈、嵌入式、移动端、DevOps、大数据、AI等各技术领域
|
||||
- 精通各种技术栈的深度和广度评估
|
||||
- 擅长根据岗位特点和候选人背景进行精准匹配
|
||||
## 通用岗位分类及评估重点
|
||||
### 后端开发岗位
|
||||
- 重点:框架熟练度、数据库设计、API设计、性能优化、并发处理
|
||||
- 核心技能:编程语言基础、框架应用、系统设计、问题排查
|
||||
### 前端开发岗位
|
||||
- 重点:UI/UX实现、性能优化、跨浏览器兼容、现代框架使用
|
||||
- 核心技能:HTML/CSS/JS、框架应用、工程化、用户体验
|
||||
### 全栈开发岗位
|
||||
- 重点:前后端技术栈、系统架构、DevOps流程
|
||||
- 核心技能:多技术栈掌握、系统整合、项目管理
|
||||
### 架构师岗位
|
||||
- 重点:系统设计、技术选型、性能调优、团队技术规划
|
||||
- 核心技能:架构设计、技术决策、团队领导、业务理解
|
||||
## 筛选策略框架
|
||||
### 匹配维度权重
|
||||
1. **技术栈匹配度** (35%): 候选人技能与岗位要求的重合度
|
||||
2. **项目经验相关性** (30%): 过往项目与岗位场景的匹配度
|
||||
3. **技能深度评估** (20%): 根据经验年限判断技能掌握深度
|
||||
4. **发展潜力考量** (15%): 学习能力和技术视野的考察
|
||||
## 本岗位招聘要求
|
||||
[{jobRequirements}]
|
||||
|
||||
## 输出规范
|
||||
- 必须输出标准JSON格式:{jsonRes}
|
||||
- 不得包含任何解释、注释或代码块标记
|
||||
- 确保所选题目ID真实存在于题库中
|
||||
- 保证题目数量与要求完全一致
|
||||
""");
|
||||
|
||||
PromptTemplate userPromptTemplate = new PromptTemplate("""
|
||||
请根据岗位招聘要求,从题库中筛选筛选 {count} 道技术面试题。
|
||||
## 候选人档案
|
||||
### 技术栈
|
||||
{skills}
|
||||
### 简历内容
|
||||
{resume}
|
||||
## 筛选要求
|
||||
请根据以上信息,结合你的专业框架,从题库中筛选出最能评估该候选人是否适合此岗位的面试题。
|
||||
### 重点考虑因素
|
||||
1. 岗位核心技术要求与候选人技能的匹配度
|
||||
2. 候选人项目经验与岗位应用场景的关联性
|
||||
3. 题目难度与候选人经验水平的适配性
|
||||
4. 题目类型的多样性(理论+实践+设计)
|
||||
"""
|
||||
);
|
||||
params.put("jsonRes",
|
||||
"""
|
||||
{
|
||||
"questions": [
|
||||
{
|
||||
"id": "1",
|
||||
"content": "问题内容..."
|
||||
},
|
||||
{
|
||||
"id": "3",
|
||||
"content": "问题内容..."
|
||||
}
|
||||
...
|
||||
]
|
||||
}
|
||||
"""
|
||||
);
|
||||
return new Prompt(List.of(
|
||||
userPromptTemplate.createMessage(params),
|
||||
systemPromptTemplate.createMessage(params)
|
||||
));
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static Prompt getEvaluatePrompt(Map<String, Object> params) {
|
||||
// SystemMessage systemMessage = new SystemMessage("""
|
||||
// 你是一位经验丰富的高级技术面试官,以公正、严谨、深入的评估风格著称。
|
||||
// ## 你的专业特质
|
||||
// - 拥有15年+ 技术开发和面试经验
|
||||
// - 善于通过追问挖掘候选人的真实技术水平
|
||||
// - 能够准确识别标准答案、实际经验和深度理解的区别
|
||||
// - 注重考察解决问题的思路和实际应用能力
|
||||
//
|
||||
// """);
|
||||
|
||||
PromptTemplate promptTemplate = new PromptTemplate("""
|
||||
请对候选人的回答进行专业评估。
|
||||
## 评估维度及权重
|
||||
### 技术准确性 (30%)
|
||||
- 概念理解的正确性
|
||||
- 技术细节的准确程度
|
||||
- 是否存在明显错误或误解
|
||||
### 深度与广度 (25%)
|
||||
- 知识的深入程度
|
||||
- 相关技术的关联理解
|
||||
- 是否能举一反三
|
||||
### 实践经验 (25%)
|
||||
- 是否有真实项目经验支撑
|
||||
- 能否结合具体场景说明
|
||||
- 对技术选型和权衡的理解
|
||||
### 表达能力 (20%)
|
||||
- 逻辑清晰度
|
||||
- 表达的完整性
|
||||
- 专业术语使用的准确性
|
||||
## 评分标准
|
||||
### 优秀 (85-100分)
|
||||
- 回答准确、深入、有见解
|
||||
- 能结合实际项目经验
|
||||
- 表达清晰、逻辑严密
|
||||
- 展现出深度思考和实践能力
|
||||
### 良好 (70-84分)
|
||||
- 回答基本正确,有一定深度
|
||||
- 有实际应用经验
|
||||
- 表达较为清晰
|
||||
- 个别地方可能需要补充
|
||||
### 及格 (60-69分)
|
||||
- 回答基本正确但较浅显
|
||||
- 缺乏深入理解或实践经验
|
||||
- 表达尚可但不够完整
|
||||
- 需要进一步考察
|
||||
### 不及格 (0-59分)
|
||||
- 回答错误或严重不完整
|
||||
- 基础概念理解有误
|
||||
- 表达混乱或逻辑不清
|
||||
- 明显缺乏相关经验
|
||||
## 追问策略
|
||||
### 何时追问
|
||||
1. **概念模糊**: 候选人给出的概念定义不够准确或完整
|
||||
2. **缺少细节**: 回答过于宽泛,缺乏具体的技术细节
|
||||
3. **经验质疑**: 怀疑候选人是否有真实的项目经验
|
||||
4. **深度探索**: 基础回答正确,想考察更深层次的理解
|
||||
### 追问类型
|
||||
1. **澄清追问**: "你刚才提到XX,能具体解释一下吗?"
|
||||
2. **场景追问**: "在实际项目中,你是如何处理XX问题的?"
|
||||
3. **对比追问**: "XX和YY有什么区别?你会如何选择?"
|
||||
4. **深度追问**: "如果遇到XX情况,你会如何优化?"
|
||||
### 追问限制
|
||||
- 单个问题最多追问3次
|
||||
- 追问应该递进深入,不重复
|
||||
- 追问后必须给出综合评估
|
||||
- 避免过度纠缠细节,影响整体面试节奏
|
||||
## 当前问题
|
||||
{question}
|
||||
|
||||
## 候选人回答
|
||||
{candidateAnswer}
|
||||
|
||||
## 评估任务
|
||||
|
||||
### 请分析以下方面
|
||||
1. **技术准确性**: 回答是否正确,有无技术错误
|
||||
2. **完整性**: 是否涵盖了问题的关键要点
|
||||
3. **深度**: 是否展现了深入的理解和思考
|
||||
4. **实践性**: 是否结合了实际项目经验
|
||||
5. **表达质量**: 逻辑是否清晰,表达是否准确
|
||||
|
||||
### 追问决策逻辑
|
||||
- 如果回答存在明显不足,制定一个精准的追问来深入考察
|
||||
- 如果已经追问过2次,本次必须结束追问(continueAsking: false)
|
||||
- 追问应该针对性强,避免过于宽泛
|
||||
- 优先考察核心技术能力,避免偏离主题
|
||||
|
||||
### AI标准答案要求
|
||||
请提供一个简洁、准确的技术答案作为参考,突出关键要点。
|
||||
|
||||
## 输出格式要求
|
||||
严格按照以下JSON格式输出,确保字段完整且格式正确:
|
||||
|
||||
{jsonRes}
|
||||
|
||||
开始评估:
|
||||
""");
|
||||
params.put(
|
||||
"jsonRes",
|
||||
"""
|
||||
{
|
||||
"feedback": "对回答的具体评价,指出优点和不足",
|
||||
"suggestions": "具体的改进建议和学习方向",
|
||||
"aiAnswer": "简洁准确的标准答案要点",
|
||||
"score": 75.5,
|
||||
"continueAsking": true,
|
||||
"followUpQuestion": "具体的追问问题(如果不追问则为空字符串)"
|
||||
}
|
||||
"""
|
||||
);
|
||||
return new Prompt(List.of(
|
||||
promptTemplate.createMessage(params)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最终报告
|
||||
*
|
||||
* @param params 参数
|
||||
* @return 提示
|
||||
*/
|
||||
public static Prompt getFinalReportPrompt(Map<String, Object> params) {
|
||||
// SystemMessage systemMessage = new SystemMessage("""
|
||||
// 你是一位资深的技术面试官和HR专家,具备丰富的候选人评估经验。你的职责是:
|
||||
//
|
||||
// ## 核心职能:
|
||||
// - 基于面试数据进行客观、全面的技术能力评估
|
||||
// - 提供标准化的面试结果分析和建议
|
||||
// - 支持招聘决策制定
|
||||
//
|
||||
// ## 评估原则:
|
||||
// 1. **客观性**:基于实际表现数据,避免主观推测
|
||||
// 2. **全面性**:覆盖技术能力、沟通表达、问题解决等维度
|
||||
// 3. **标准化**:使用统一的评分体系和输出格式
|
||||
// 4. **实用性**:提供可执行的改进建议和明确的录用建议
|
||||
//
|
||||
// ## 输出要求:
|
||||
// 严格按照JSON格式输出,不得包含任何markdown标记或额外解释:
|
||||
//
|
||||
// {
|
||||
// "overallScore": <1-100整数>,
|
||||
// "overallFeedback": "<综合评价,客观描述候选人整体表现,150-200字>",
|
||||
// "technicalAssessment": {
|
||||
// "Java基础": "掌握良好,对集合框架理解深入。",
|
||||
// "Spring框架": "熟悉基本使用,但对底层原理理解不足。",
|
||||
// "数据库": "能够编写常规SQL,但在索引优化方面知识欠缺。",
|
||||
// "<技术领域1>": "<该领域的具体评估>",
|
||||
// ...
|
||||
// },
|
||||
// "strengthsAndWeaknesses": {
|
||||
// "strengths": ["<具体优势1>", "<具体优势2>", "<具体优势3>"],
|
||||
// "weaknesses": ["<具体不足1>", "<具体不足2>", "<具体不足3>"]
|
||||
// },
|
||||
// "suggestions": [
|
||||
// "<具体可执行的改进建议1>",
|
||||
// "<具体可执行的改进建议2>",
|
||||
// "<具体可执行的改进建议3>",
|
||||
// "<具体可执行的改进建议4>",
|
||||
// "<具体可执行的改进建议5>"
|
||||
// ],
|
||||
// "hiringRecommendation": "<强烈推荐|推荐|待考虑|不推荐>",
|
||||
// "hiringReason": "<录用建议的具体理由,50-80字>"
|
||||
// }
|
||||
//
|
||||
// ## 评分标准:
|
||||
// - 90-100分:技术优秀,表达清晰,思维敏捷,超出岗位要求
|
||||
// - 80-89分:技术良好,基本满足岗位要求,有培养潜力
|
||||
// - 70-79分:技术一般,需要指导和培养
|
||||
// - 60-69分:技术较弱,存在明显知识盲区
|
||||
// - 60分以下:技术不足,不符合岗位要求
|
||||
// """);
|
||||
|
||||
PromptTemplate promptTemplate = new PromptTemplate("""
|
||||
请根据以下候选人信息和面试记录,生成标准化的面试评估报告:
|
||||
## 核心职能:
|
||||
- 基于面试数据进行客观、全面的技术能力评估
|
||||
- 提供标准化的面试结果分析和建议
|
||||
- 支持招聘决策制定
|
||||
|
||||
## 评估原则:
|
||||
1. **客观性**:基于实际表现数据,避免主观推测
|
||||
2. **全面性**:覆盖技术能力、沟通表达、问题解决等维度
|
||||
3. **标准化**:使用统一的评分体系和输出格式
|
||||
4. **实用性**:提供可执行的改进建议和明确的录用建议
|
||||
|
||||
## 输出要求:
|
||||
严格按照JSON格式输出,不得包含任何markdown标记或额外解释:
|
||||
|
||||
{jsonRes}
|
||||
|
||||
## 评分标准:
|
||||
- 90-100分:技术优秀,表达清晰,思维敏捷,超出岗位要求
|
||||
- 80-89分:技术良好,基本满足岗位要求,有培养潜力
|
||||
- 70-79分:技术一般,需要指导和培养
|
||||
- 60-69分:技术较弱,存在明显知识盲区
|
||||
- 60分以下:技术不足,不符合岗位要求
|
||||
|
||||
## 候选人简历信息:
|
||||
{resume}
|
||||
|
||||
## 完整面试记录:
|
||||
{history}
|
||||
|
||||
请开始评估并输出JSON格式的报告。
|
||||
""");
|
||||
params.put("jsonRes", """
|
||||
{
|
||||
"overallScore": <1-100整数>,
|
||||
"overallFeedback": "<综合评价,客观描述候选人整体表现,150-200字>",
|
||||
"technicalAssessment": {
|
||||
"Java基础": "掌握良好,对集合框架理解深入。",
|
||||
"Spring框架": "熟悉基本使用,但对底层原理理解不足。",
|
||||
"数据库": "能够编写常规SQL,但在索引优化方面知识欠缺。",
|
||||
"<技术领域1>": "<该领域的具体评估>",
|
||||
...
|
||||
},
|
||||
"strengthsAndWeaknesses": {
|
||||
"strengths": ["<具体优势1>", "<具体优势2>", "<具体优势3>"],
|
||||
"weaknesses": ["<具体不足1>", "<具体不足2>", "<具体不足3>"]
|
||||
},
|
||||
"suggestions": [
|
||||
"<具体可执行的改进建议1>",
|
||||
"<具体可执行的改进建议2>",
|
||||
"<具体可执行的改进建议3>",
|
||||
"<具体可执行的改进建议4>",
|
||||
"<具体可执行的改进建议5>"
|
||||
],
|
||||
"hiringRecommendation": "<强烈推荐|推荐|待考虑|不推荐>",
|
||||
"hiringReason": "<录用建议的具体理由,50-80字>"
|
||||
}
|
||||
""");
|
||||
return new Prompt(List.of(
|
||||
promptTemplate.createMessage(params)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,12 @@ import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringApplicationContextUtil implements ApplicationContextAware {
|
||||
public class SpringApplicationContextUtils implements ApplicationContextAware {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringApplicationContextUtil.applicationContext = applicationContext;
|
||||
SpringApplicationContextUtils.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> beanClass) {
|
||||
2
src/main/java/com/qingqiu/interview/common/utils/TreeUtil.java → src/main/java/com/qingqiu/interview/common/utils/TreeUtils.java
Executable file → Normal file
2
src/main/java/com/qingqiu/interview/common/utils/TreeUtil.java → src/main/java/com/qingqiu/interview/common/utils/TreeUtils.java
Executable file → Normal file
@@ -7,7 +7,7 @@ import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TreeUtil {
|
||||
public class TreeUtils {
|
||||
|
||||
/**
|
||||
* 通用树形结构构建方法
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.qingqiu.interview.common.utils;
|
||||
|
||||
public class UUIDUtils {
|
||||
|
||||
public static String getUUID() {
|
||||
return java.util.UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.qingqiu.interview.common.utils;
|
||||
|
||||
|
||||
import io.netty.channel.ChannelOption;
|
||||
import org.springframework.http.client.ReactorClientHttpRequestFactory;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description:
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-06 20:04
|
||||
**/
|
||||
public class WebClientUtils {
|
||||
|
||||
/**
|
||||
* 创建全局默认的WebClient Bean实例
|
||||
* 配置了连接超时和响应超时时间
|
||||
*
|
||||
* @return WebClient实例
|
||||
*/
|
||||
public static WebClient.Builder getWebClientBuilder() {
|
||||
HttpClient httpClient = HttpClient.create()
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000) // 连接超时
|
||||
.responseTimeout(Duration.ofMillis(30000)); // 读取超时
|
||||
|
||||
return WebClient.builder()
|
||||
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
||||
;
|
||||
}
|
||||
|
||||
public static RestClient.Builder getRestClientBuilder() {
|
||||
return RestClient.builder()
|
||||
.requestFactory(
|
||||
new ReactorClientHttpRequestFactory(
|
||||
HttpClient.create()
|
||||
.responseTimeout(Duration.ofMinutes(30))
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
import com.alibaba.cloud.ai.memory.jdbc.MysqlChatMemoryRepository;
|
||||
import com.alibaba.cloud.ai.memory.redis.RedisChatMemoryRepository;
|
||||
import com.qingqiu.interview.common.constants.ChatConstant;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import static com.qingqiu.interview.common.constants.ChatConstant.MAX_MESSAGES;
|
||||
|
||||
/**
|
||||
* 聊天记忆相关配置
|
||||
*/
|
||||
@Configuration
|
||||
public class ChatMemoryConfig {
|
||||
|
||||
@Value("${spring.ai.memory.redis.host}")
|
||||
private String redisHost;
|
||||
@Value("${spring.ai.memory.redis.port}")
|
||||
private int redisPort;
|
||||
@Value("${spring.ai.memory.redis.password}")
|
||||
private String redisPassword;
|
||||
@Value("${spring.ai.memory.redis.timeout}")
|
||||
private int redisTimeout;
|
||||
|
||||
@Resource
|
||||
private DataSource dataSource;
|
||||
|
||||
|
||||
@Bean
|
||||
public MysqlChatMemoryRepository mysqlChatMemoryRepository() {
|
||||
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
return MysqlChatMemoryRepository.mysqlBuilder()
|
||||
.jdbcTemplate(jdbcTemplate)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean(name = ChatConstant.MYSQL_CHAT_MEMORY_BEAN_NAME)
|
||||
public MessageWindowChatMemory mysqlChatMemory(MysqlChatMemoryRepository mysqlChatMemoryRepository) {
|
||||
return MessageWindowChatMemory.builder()
|
||||
.chatMemoryRepository(mysqlChatMemoryRepository)
|
||||
.maxMessages(MAX_MESSAGES)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisChatMemoryRepository redisChatMemoryRepository() {
|
||||
return RedisChatMemoryRepository.builder()
|
||||
.host(redisHost)
|
||||
.port(redisPort)
|
||||
// 若没有设置密码则注释该项
|
||||
.password(redisPassword)
|
||||
.timeout(redisTimeout)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = ChatConstant.REDIS_CHAT_MEMORY_BEAN_NAME)
|
||||
public MessageWindowChatMemory redisChatMemory(RedisChatMemoryRepository redisChatMemoryRepository) {
|
||||
return MessageWindowChatMemory.builder()
|
||||
.chatMemoryRepository(redisChatMemoryRepository)
|
||||
.maxMessages(MAX_MESSAGES)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
22
src/main/java/com/qingqiu/interview/config/CorsConfig.java
Normal file
22
src/main/java/com/qingqiu/interview/config/CorsConfig.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").
|
||||
allowedOriginPatterns("*") //允许跨域的域名,可以用*表示允许任何域名使用
|
||||
// allowedOrigins("*"). //在Springboot2.4对应Spring5.3后在设置allowCredentials(true)的基础上不能直接使用通配符设置allowedOrigins,而是需要指定特定的URL。如果需要设置通配符,需要通过allowedOriginPatterns指定
|
||||
.allowedMethods("GET", "POST", "DELETE", "PUT") //允许任何方法(post、get等)
|
||||
.allowedHeaders("*") //允许任何请求头
|
||||
.allowCredentials(true) //带上cookie信息
|
||||
.exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,14 +1,120 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
import com.alibaba.dashscope.aigc.generation.Generation;
|
||||
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
|
||||
import com.alibaba.cloud.ai.dashscope.api.DashScopeResponseFormat;
|
||||
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
|
||||
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
|
||||
import com.qingqiu.interview.common.constants.ChatConstant;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
import static com.qingqiu.interview.common.utils.WebClientUtils.getRestClientBuilder;
|
||||
import static com.qingqiu.interview.common.utils.WebClientUtils.getWebClientBuilder;
|
||||
|
||||
/**
|
||||
* DashScope相关配置类
|
||||
* 主要配置阿里云百炼平台(DashScope)和OpenAI的大模型服务
|
||||
* 包括API客户端、聊天模型和聊天客户端的配置
|
||||
*
|
||||
* @author qingqiu
|
||||
*/
|
||||
@Configuration
|
||||
public class DashScopeConfig {
|
||||
|
||||
// 从配置文件中读取DashScope API密钥
|
||||
@Value("${spring.ai.dashscope.api-key}")
|
||||
private String dashScopeApiKey;
|
||||
|
||||
@Value("${spring.ai.dashscope.chat.options.model}")
|
||||
private String dashScopeChatModelName;
|
||||
|
||||
|
||||
|
||||
@Resource(name = ChatConstant.MYSQL_CHAT_MEMORY_BEAN_NAME)
|
||||
private MessageWindowChatMemory mysqlChatMemory;
|
||||
|
||||
/**
|
||||
* 创建DashScopeApi Bean实例
|
||||
* 配置了HTTP客户端连接参数,包括连接超时和响应超时时间
|
||||
*
|
||||
* @return DashScopeApi实例
|
||||
*/
|
||||
@Bean
|
||||
public Generation generation() {
|
||||
return new Generation();
|
||||
public DashScopeApi dashScopeApi() {
|
||||
return DashScopeApi.builder()
|
||||
.apiKey(dashScopeApiKey)
|
||||
.restClientBuilder(getRestClientBuilder())
|
||||
.webClientBuilder(getWebClientBuilder())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建DashScope聊天模型Bean实例
|
||||
* 配置了最大token数、使用的模型以及返回格式为JSON对象
|
||||
*
|
||||
* @return ChatModel实例
|
||||
*/
|
||||
@Bean(name = ChatConstant.DASH_SCOPE_CHAT_MODEL_BEAN_NAME)
|
||||
public ChatModel dashScopeChatModel() {
|
||||
return DashScopeChatModel.builder()
|
||||
.dashScopeApi(dashScopeApi())
|
||||
.defaultOptions(
|
||||
DashScopeChatOptions.builder()
|
||||
.withMaxToken(ChatConstant.MAX_COMPLETION_TOKENS)
|
||||
.withModel(dashScopeChatModelName)
|
||||
.withResponseFormat(
|
||||
DashScopeResponseFormat.builder()
|
||||
.type(DashScopeResponseFormat.Type.JSON_OBJECT)
|
||||
.build()
|
||||
)
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建默认的聊天客户端Bean实例(使用DashScope模型)
|
||||
* 添加了日志记录功能
|
||||
*
|
||||
* @return ChatClient实例
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public ChatClient chatClient() {
|
||||
return ChatClient
|
||||
.builder(dashScopeChatModel())
|
||||
.defaultAdvisors(
|
||||
new SimpleLoggerAdvisor()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建基于MySQL存储聊天历史的DashScope聊天客户端Bean实例
|
||||
* 配置了消息内存管理和日志记录功能
|
||||
*
|
||||
* @return ChatClient实例
|
||||
*/
|
||||
@Bean(name = ChatConstant.DASH_SCOPE_CHAT_CLIENT_BEAN_NAME)
|
||||
public ChatClient dashScopeChatClient() {
|
||||
return ChatClient
|
||||
.builder(dashScopeChatModel())
|
||||
.defaultAdvisors(
|
||||
MessageChatMemoryAdvisor.builder(mysqlChatMemory).build(),
|
||||
new SimpleLoggerAdvisor()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONReader;
|
||||
import com.alibaba.fastjson2.JSONWriter;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.SerializationException;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class Fastjson2RedisSerializer<T> implements RedisSerializer<T> {
|
||||
// 默认编码
|
||||
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
|
||||
|
||||
// 泛型类型,用于反序列化
|
||||
private final Class<T> clazz;
|
||||
|
||||
public Fastjson2RedisSerializer(Class<T> clazz) {
|
||||
super();
|
||||
this.clazz = clazz;
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化:将对象转换为字节数组
|
||||
*/
|
||||
@Override
|
||||
public byte[] serialize(T t) throws SerializationException {
|
||||
if (t == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
try {
|
||||
// 使用 Fastjson2 序列化对象,并写入字节数组
|
||||
// 配置写入特性:WriteClassName 确保反序列化时能识别类型,如果不需要,可以移除。
|
||||
return JSON.toJSONBytes(t, JSONWriter.Feature.WriteClassName);
|
||||
} catch (Exception ex) {
|
||||
throw new SerializationException("Could not serialize object with Fastjson2", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化:将字节数组转换为对象
|
||||
*/
|
||||
@Override
|
||||
public T deserialize(byte[] bytes) throws SerializationException {
|
||||
if (bytes == null || bytes.length <= 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// 使用 Fastjson2 反序列化字节数组
|
||||
// 配置读取特性:SupportAutoType,确保可以正确读取带有类名信息的JSON
|
||||
return JSON.parseObject(bytes, clazz, JSONReader.Feature.SupportAutoType);
|
||||
} catch (Exception ex) {
|
||||
throw new SerializationException("Could not deserialize object with Fastjson2", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
100
src/main/java/com/qingqiu/interview/config/OpenAiChatConfig.java
Normal file
100
src/main/java/com/qingqiu/interview/config/OpenAiChatConfig.java
Normal file
@@ -0,0 +1,100 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
|
||||
import com.qingqiu.interview.common.constants.ChatConstant;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
|
||||
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
|
||||
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatOptions;
|
||||
import org.springframework.ai.openai.api.OpenAiApi;
|
||||
import org.springframework.ai.openai.api.ResponseFormat;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
import static com.qingqiu.interview.common.utils.WebClientUtils.getRestClientBuilder;
|
||||
import static com.qingqiu.interview.common.utils.WebClientUtils.getWebClientBuilder;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description: openai聊天配置
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-06 20:03
|
||||
**/
|
||||
@Configuration
|
||||
public class OpenAiChatConfig {
|
||||
|
||||
|
||||
@Value("${spring.ai.openai.chat.options.model}")
|
||||
private String openAiChatModelName;
|
||||
|
||||
@Value("${spring.ai.openai.base-url}")
|
||||
private String openAiBaseUrl;
|
||||
|
||||
@Value("${spring.ai.openai.api-key}")
|
||||
private String openAiApiKey;
|
||||
|
||||
@Resource(name = ChatConstant.MYSQL_CHAT_MEMORY_BEAN_NAME)
|
||||
private MessageWindowChatMemory mysqlChatMemory;
|
||||
|
||||
|
||||
/**
|
||||
* 创建OpenAI聊天模型Bean实例(主模型)
|
||||
* 配置了最大完成token数和响应格式为JSON Schema
|
||||
*
|
||||
* @return ChatModel实例
|
||||
*/
|
||||
@Bean(name = ChatConstant.OPEN_AI_CHAT_MODEL_BEAN_NAME)
|
||||
@Primary
|
||||
public ChatModel openAiChatModel() {
|
||||
return OpenAiChatModel.builder()
|
||||
.openAiApi(
|
||||
OpenAiApi.builder()
|
||||
.apiKey(openAiApiKey)
|
||||
.baseUrl(openAiBaseUrl)
|
||||
.webClientBuilder(getWebClientBuilder())
|
||||
.restClientBuilder(getRestClientBuilder())
|
||||
.build()
|
||||
)
|
||||
.defaultOptions(
|
||||
OpenAiChatOptions.builder()
|
||||
.model(openAiChatModelName)
|
||||
.maxCompletionTokens(ChatConstant.MAX_COMPLETION_TOKENS)
|
||||
|
||||
.responseFormat(
|
||||
ResponseFormat.builder()
|
||||
.type(ResponseFormat.Type.JSON_SCHEMA)
|
||||
.jsonSchema(
|
||||
ResponseFormat.JsonSchema
|
||||
.builder()
|
||||
.build()
|
||||
).build()
|
||||
)
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建基于MySQL存储聊天历史的OpenAI聊天客户端Bean实例
|
||||
* 配置了消息内存管理和日志记录功能
|
||||
*
|
||||
* @return ChatClient实例
|
||||
*/
|
||||
@Bean(name = ChatConstant.OPEN_AI_CHAT_CLIENT_BEAN_NAME)
|
||||
public ChatClient openAiChatClient() {
|
||||
return ChatClient
|
||||
.builder(openAiChatModel())
|
||||
.defaultAdvisors(
|
||||
MessageChatMemoryAdvisor.builder(mysqlChatMemory).build(),
|
||||
new SimpleLoggerAdvisor()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
32
src/main/java/com/qingqiu/interview/config/RedisConfig.java
Normal file
32
src/main/java/com/qingqiu/interview/config/RedisConfig.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package com.qingqiu.interview.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(redisConnectionFactory);
|
||||
|
||||
// 使用StringRedisSerializer来序列化和反序列化redis的key值
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
|
||||
// 使用Fastjson2RedisSerializer来序列化和反序列化redis的value值
|
||||
|
||||
Fastjson2RedisSerializer<Object> fastjson2RedisSerializer = new Fastjson2RedisSerializer<>(Object.class);
|
||||
|
||||
template.setValueSerializer(fastjson2RedisSerializer);
|
||||
template.setHashValueSerializer(fastjson2RedisSerializer);
|
||||
|
||||
template.afterPropertiesSet();
|
||||
return template;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,23 @@
|
||||
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.AiSessionLog;
|
||||
import com.qingqiu.interview.service.IAiSessionLogService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.ai.chat.messages.MessageType;
|
||||
import org.springframework.ai.chat.messages.SystemMessage;
|
||||
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 +26,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, MessageType.SYSTEM.getValue())
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
198
src/main/java/com/qingqiu/interview/controller/InterviewController.java
Executable file → Normal file
198
src/main/java/com/qingqiu/interview/controller/InterviewController.java
Executable file → Normal file
@@ -1,65 +1,133 @@
|
||||
package com.qingqiu.interview.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.qingqiu.interview.dto.*;
|
||||
import com.qingqiu.interview.entity.InterviewSession;
|
||||
import com.qingqiu.interview.service.InterviewService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.UUID;
|
||||
|
||||
/**
|
||||
* 面试流程相关接口
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/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);
|
||||
log.info("接收到的数据: {}", JSONObject.toJSONString(request));
|
||||
InterviewResponse interviewResponse = new InterviewResponse();
|
||||
interviewResponse.setSessionId(UUID.randomUUID().toString().replace("-", ""));
|
||||
return ApiResponse.success(interviewResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 继续面试会话(用户回答)
|
||||
*/
|
||||
@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.io.IOException;
|
||||
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));
|
||||
}
|
||||
|
||||
@PostMapping("/read-pdf")
|
||||
public R<?> readPdf(@RequestParam MultipartFile file) throws IOException {
|
||||
String readPdfFile = interviewService.readPdfFile(file);
|
||||
log.info("resume content: {}", readPdfFile);
|
||||
return R.success(readPdfFile);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,10 @@ package com.qingqiu.interview.controller;
|
||||
|
||||
import com.qingqiu.interview.common.res.R;
|
||||
import com.qingqiu.interview.dto.QuestionProgressPageParams;
|
||||
import com.qingqiu.interview.entity.InterviewQuestionProgress;
|
||||
import com.qingqiu.interview.service.IInterviewQuestionProgressService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
@@ -27,6 +25,7 @@ public class InterviewQuestionProgressController {
|
||||
|
||||
/**
|
||||
* 面试问题进度列表
|
||||
*
|
||||
* @param params 查询参数
|
||||
* @return data
|
||||
*/
|
||||
@@ -35,4 +34,16 @@ public class InterviewQuestionProgressController {
|
||||
return R.success(service.pageList(params));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取面试问题进度详情
|
||||
*
|
||||
* @param id id
|
||||
* @return data
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<InterviewQuestionProgress> getDetail(@PathVariable Long id) {
|
||||
return R.success(service.getById(id));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.qingqiu.interview.dto;
|
||||
|
||||
import com.qingqiu.interview.common.enums.LLMProvider;
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@@ -10,13 +11,14 @@ import lombok.experimental.Accessors;
|
||||
* @date 2025/9/18 12:54
|
||||
*/
|
||||
@Data
|
||||
|
||||
@Accessors(chain = true)
|
||||
public class ChatDTO {
|
||||
|
||||
/** 会话id */
|
||||
private String sessionId;
|
||||
/** 调用模型 */
|
||||
private String aiModel;
|
||||
private String aiModel = LLMProvider.DEEPSEEK.getCode();
|
||||
/** 输入内容 */
|
||||
private String content;
|
||||
/** 0 普通会话 1 面试会话 */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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;
|
||||
@@ -18,6 +19,16 @@ public class InterviewStartRequest {
|
||||
@NotBlank(message = "面试类型不能为空")
|
||||
private String model;
|
||||
|
||||
|
||||
/** 选择的AI模型 */
|
||||
private String aiModel = LLMProvider.QWEN.getCode();
|
||||
|
||||
/** 生成的面试题目数量 */
|
||||
private Integer totalQuestions = 10;
|
||||
|
||||
/**
|
||||
* 岗位要求
|
||||
*/
|
||||
private String jobRequirements;
|
||||
|
||||
// 简历文件通过MultipartFile单独传递
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -14,7 +15,7 @@ import lombok.experimental.Accessors;
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
public class QuestionCategoryPageParams extends PageBaseParams{
|
||||
public class QuestionCategoryPageParams extends PageBaseParams {
|
||||
/**
|
||||
* 分类名称(模糊查询)
|
||||
*/
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
33
src/main/java/com/qingqiu/interview/dto/SubmitAnswerDTO.java
Normal file
33
src/main/java/com/qingqiu/interview/dto/SubmitAnswerDTO.java
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -31,6 +31,9 @@ public class InterviewSession implements Serializable {
|
||||
@TableField("resume_content")
|
||||
private String resumeContent;
|
||||
|
||||
@TableField("job_requirements")
|
||||
private String jobRequirements;
|
||||
|
||||
@TableField("extracted_skills")
|
||||
private String extractedSkills;
|
||||
@TableField("interview_type")
|
||||
@@ -44,6 +47,8 @@ public class InterviewSession implements Serializable {
|
||||
|
||||
@TableField("ai_model")
|
||||
private String aiModel;
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record EvaluateAiRes(@JsonProperty("feedback") String feedback,
|
||||
@JsonProperty("suggestions") String suggestions,
|
||||
@JsonProperty("aiAnswer") String aiAnswer,
|
||||
@JsonProperty("score") double score,
|
||||
@JsonProperty("continueAsking") boolean continueAsking,
|
||||
@JsonProperty("followUpQuestion") String followUpQuestion) {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ExtractSkillAiRes(
|
||||
@JsonProperty("skills") List<String> skills
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public record InterviewReportAiRes(
|
||||
@JsonProperty("overallScore") String overallScore,
|
||||
@JsonProperty("overallFeedback") String overallFeedback,
|
||||
|
||||
@JsonProperty("technicalAssessment") Map<String, String> technicalAssessment,
|
||||
@JsonProperty("strengthsAndWeaknesses") StrengthsAndWeaknesses strengthsAndWeaknesses,
|
||||
|
||||
@JsonProperty("suggestions") List<String> suggestions,
|
||||
@JsonProperty("hiringRecommendation") String hiringRecommendation,
|
||||
@JsonProperty("hiringReason") String hiringReason
|
||||
) {
|
||||
|
||||
/**
|
||||
* 内部 Record:对应 "strengthsAndWeaknesses" 对象。
|
||||
*/
|
||||
public record StrengthsAndWeaknesses(
|
||||
@JsonProperty("strengths") List<String> strengths,
|
||||
@JsonProperty("weaknesses") List<String> weaknesses
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class QuestionAiRes {
|
||||
|
||||
/**
|
||||
* 内部实体类:对应 JSON 数组中的每个元素。
|
||||
* { "id": "ai-gen-1", "content": "问题内容..." }
|
||||
*/
|
||||
public record Question(
|
||||
@JsonProperty("id") String id,
|
||||
@JsonProperty("content") String content
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 外部实体类:对应整个 JSON 响应的顶层结构。
|
||||
* { "questions": [...] }
|
||||
*/
|
||||
public record Wrapper(
|
||||
@JsonProperty("questions") List<Question> questions
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description: 题型分类ai返回
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-06 20:08
|
||||
**/
|
||||
public class QuestionClassificationAiRes {
|
||||
|
||||
public record Item(@JsonProperty("content") String content,
|
||||
@JsonProperty("category") String category,
|
||||
@JsonProperty("difficulty") String difficulty,
|
||||
@JsonProperty("tags") String tags) {}
|
||||
|
||||
public record Wrapper(@JsonProperty("questions")List<Item> questions) {}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.qingqiu.interview.entity.ai;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import redis.clients.jedis.graph.Statistics;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description: 题目去重AI返回结果
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-07 10:37
|
||||
**/
|
||||
public record QuestionDeduplicationAiRes(
|
||||
@JsonProperty("questionIds") String questionIds
|
||||
) {
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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);
|
||||
}
|
||||
74
src/main/java/com/qingqiu/interview/service/DashboardService.java
Executable file → Normal file
74
src/main/java/com/qingqiu/interview/service/DashboardService.java
Executable file → Normal file
@@ -1,59 +1,15 @@
|
||||
package com.qingqiu.interview.service;
|
||||
|
||||
import com.qingqiu.interview.mapper.InterviewSessionMapper;
|
||||
import com.qingqiu.interview.mapper.QuestionMapper;
|
||||
import com.qingqiu.interview.dto.DashboardStatsResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DashboardService {
|
||||
|
||||
private final QuestionMapper questionMapper;
|
||||
private final InterviewSessionMapper sessionMapper;
|
||||
|
||||
public DashboardStatsResponse getDashboardStats() {
|
||||
DashboardStatsResponse stats = new DashboardStatsResponse();
|
||||
|
||||
// 1. 获取核心KPI
|
||||
stats.setTotalQuestions(questionMapper.selectCount(null));
|
||||
stats.setTotalInterviews(sessionMapper.selectCount(null));
|
||||
|
||||
// 2. 获取题库分类统计
|
||||
stats.setQuestionCategoryStats(questionMapper.countByCategory());
|
||||
|
||||
// 3. 获取最近7天的面试统计,并补全没有数据的日期
|
||||
List<DashboardStatsResponse.DailyStat> recentStats = sessionMapper.countRecentInterviews(7);
|
||||
stats.setRecentInterviewStats(fillMissingDates(recentStats, 7));
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充最近几天内没有面试数据的日期,补0
|
||||
*/
|
||||
private List<DashboardStatsResponse.DailyStat> fillMissingDates(List<DashboardStatsResponse.DailyStat> existingStats, int days) {
|
||||
Map<String, Long> statsMap = existingStats.stream()
|
||||
.collect(Collectors.toMap(DashboardStatsResponse.DailyStat::getDate, DashboardStatsResponse.DailyStat::getCount));
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
return IntStream.range(0, days)
|
||||
.mapToObj(i -> LocalDate.now().minusDays(i))
|
||||
.map(date -> {
|
||||
String dateString = date.format(formatter);
|
||||
long count = statsMap.getOrDefault(dateString, 0L);
|
||||
return new DashboardStatsResponse.DailyStat(dateString, count);
|
||||
})
|
||||
.sorted((d1, d2) -> d1.getDate().compareTo(d2.getDate())) // 按日期升序排序
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
package com.qingqiu.interview.service;
|
||||
|
||||
|
||||
import com.qingqiu.interview.dto.DashboardStatsResponse;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description: 工作台接口
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-07 14:54
|
||||
**/
|
||||
public interface DashboardService {
|
||||
|
||||
DashboardStatsResponse getDashboardStats();
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.qingqiu.interview.service;
|
||||
|
||||
import com.qingqiu.interview.entity.InterviewQuestionProgress;
|
||||
import com.qingqiu.interview.entity.InterviewSession;
|
||||
import com.qingqiu.interview.entity.Question;
|
||||
import com.qingqiu.interview.entity.ai.EvaluateAiRes;
|
||||
import com.qingqiu.interview.entity.ai.InterviewReportAiRes;
|
||||
import com.qingqiu.interview.entity.ai.QuestionAiRes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* <h1>
|
||||
* 面试接入AI的接口
|
||||
* </h1>
|
||||
*
|
||||
* @author qingqiu
|
||||
* @date 2025/9/19 16:48
|
||||
*/
|
||||
public interface InterviewAiService {
|
||||
|
||||
/**
|
||||
* 从简历内容中提取技能列表
|
||||
*
|
||||
* @param resumeContent 简历文本
|
||||
* @return 包含技能列表的JSON对象
|
||||
*/
|
||||
List<String> extractSkillsFromResume(String resumeContent);
|
||||
|
||||
/**
|
||||
* 根据技能动态生成面试题目
|
||||
*
|
||||
* @param skills 技能列表
|
||||
* @param resumeContent 简历内容
|
||||
* @param count 需要生成的题目数量
|
||||
* @return 包含问题列表的JSON对象
|
||||
*/
|
||||
List<QuestionAiRes.Question> generateQuestionsOfAi(String sessionId, List<String> skills, String jobRequirements, String resumeContent, int count);
|
||||
|
||||
List<QuestionAiRes.Question> generateQuestionOfLocal(String sessionId, List<Question> questions, List<String> skills, String jobRequirements, String resumeContent, int count);
|
||||
|
||||
/**
|
||||
* 评估用户的回答
|
||||
*
|
||||
* @param question 问题内容
|
||||
* @param userAnswer 用户的回答
|
||||
* @param context 可选的上下文(之前的问答历史)
|
||||
* @return 包含评估结果的JSON对象
|
||||
*/
|
||||
EvaluateAiRes evaluateAnswer(String sessionId, String question, String userAnswer, List<InterviewQuestionProgress> context);
|
||||
|
||||
/**
|
||||
* 生成最终的面试评估报告
|
||||
*
|
||||
* @param session 面试会话信息
|
||||
* @param progressList 整个面试的问答记录
|
||||
* @return 包含最终报告的JSON对象
|
||||
*/
|
||||
InterviewReportAiRes generateFinalReport(InterviewSession session, List<InterviewQuestionProgress> progressList);
|
||||
|
||||
String generateFirstQuestion(String sessionId, String candidateName, String questionContent);
|
||||
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
649
src/main/java/com/qingqiu/interview/service/InterviewService.java
Executable file → Normal file
649
src/main/java/com/qingqiu/interview/service/InterviewService.java
Executable file → Normal file
@@ -1,579 +1,70 @@
|
||||
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);
|
||||
// 判断是否AI出题
|
||||
if (request.getModel().equals("local")) {
|
||||
if (CollectionUtil.isEmpty(request.getSelectedNodes())) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取所有面试会话列表
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* 读取pdf文件数据
|
||||
*
|
||||
* @param file 文件
|
||||
* @return 文件内容
|
||||
*/
|
||||
String readPdfFile(MultipartFile file) throws IOException;
|
||||
}
|
||||
|
||||
156
src/main/java/com/qingqiu/interview/service/QuestionClassificationService.java
Executable file → Normal file
156
src/main/java/com/qingqiu/interview/service/QuestionClassificationService.java
Executable file → Normal file
@@ -1,138 +1,18 @@
|
||||
package com.qingqiu.interview.service;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.qingqiu.interview.entity.Question;
|
||||
import com.qingqiu.interview.service.llm.LlmService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class QuestionClassificationService {
|
||||
|
||||
private final LlmService llmService;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* 使用AI对题目进行分类
|
||||
*/
|
||||
public List<Question> classifyQuestions(String rawContent) {
|
||||
log.info("开始使用AI分类题目,内容长度: {}", rawContent.length());
|
||||
|
||||
String prompt = buildClassificationPrompt(rawContent);
|
||||
String aiResponse = llmService.chat(prompt);
|
||||
|
||||
log.info("AI分类响应: {}", aiResponse);
|
||||
|
||||
return parseAiResponse(aiResponse);
|
||||
}
|
||||
|
||||
private String buildClassificationPrompt(String content) {
|
||||
return """
|
||||
请分析以下面试题内容,将其分类并提取信息。请严格按照以下JSON格式返回结果:
|
||||
|
||||
{
|
||||
"questions": [
|
||||
{
|
||||
"content": "题目内容",
|
||||
"category": "分类(如:Java基础、Spring框架、数据库、算法、系统设计等)",
|
||||
"difficulty": "难度(Easy、Medium、Hard)",
|
||||
"tags": "相关标签,用逗号分隔"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
分类规则:
|
||||
1. category应该是具体的技术领域,如:Java基础、Spring框架、MySQL、Redis、算法与数据结构、系统设计、网络协议等
|
||||
2. difficulty根据题目复杂度判断:Easy(基础概念)、Medium(实际应用)、Hard(深入原理或复杂场景)
|
||||
3. tags包含更细粒度的标签,如:多线程、JVM、事务、索引等
|
||||
4. 如果内容包含多个独立的题目,请分别提取
|
||||
5. 只返回JSON,不要其他解释文字
|
||||
|
||||
待分析内容:
|
||||
""" + content;
|
||||
}
|
||||
|
||||
private List<Question> parseAiResponse(String aiResponse) {
|
||||
List<Question> questions = new ArrayList<>();
|
||||
|
||||
try {
|
||||
// 清理响应,移除可能的markdown标记
|
||||
String cleanResponse = aiResponse.trim();
|
||||
if (cleanResponse.startsWith("```json")) {
|
||||
cleanResponse = cleanResponse.substring(7);
|
||||
}
|
||||
if (cleanResponse.endsWith("```")) {
|
||||
cleanResponse = cleanResponse.substring(0, cleanResponse.length() - 3);
|
||||
}
|
||||
cleanResponse = cleanResponse.trim();
|
||||
|
||||
JsonNode rootNode = objectMapper.readTree(cleanResponse);
|
||||
JsonNode questionsNode = rootNode.get("questions");
|
||||
|
||||
if (questionsNode != null && questionsNode.isArray()) {
|
||||
for (JsonNode questionNode : questionsNode) {
|
||||
Question question = new Question()
|
||||
.setContent(getTextValue(questionNode, "content"))
|
||||
.setCategoryName(getTextValue(questionNode, "category"))
|
||||
.setDifficulty(getTextValue(questionNode, "difficulty"))
|
||||
.setTags(getTextValue(questionNode, "tags"));
|
||||
|
||||
if (isValidQuestion(question)) {
|
||||
questions.add(question);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("成功解析出 {} 个题目", questions.size());
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("解析AI响应失败: {}", e.getMessage());
|
||||
log.error("原始响应: {}", aiResponse);
|
||||
|
||||
// 降级处理:如果AI返回格式不正确,尝试简单分割
|
||||
questions.addAll(fallbackParsing(aiResponse));
|
||||
}
|
||||
|
||||
return questions;
|
||||
}
|
||||
|
||||
private String getTextValue(JsonNode node, String fieldName) {
|
||||
JsonNode fieldNode = node.get(fieldName);
|
||||
return fieldNode != null ? fieldNode.asText("") : "";
|
||||
}
|
||||
|
||||
private boolean isValidQuestion(Question question) {
|
||||
return question.getContent() != null && !question.getContent().trim().isEmpty()
|
||||
&& question.getCategoryName() != null && !question.getCategoryName().trim().isEmpty();
|
||||
}
|
||||
|
||||
private List<Question> fallbackParsing(String content) {
|
||||
log.warn("使用降级解析策略");
|
||||
List<Question> questions = new ArrayList<>();
|
||||
|
||||
// 简单的降级策略:按行分割,每行作为一个题目
|
||||
String[] lines = content.split("\n");
|
||||
for (String line : lines) {
|
||||
line = line.trim();
|
||||
if (!line.isEmpty() && line.length() > 10) { // 过滤太短的内容
|
||||
Question question = new Question()
|
||||
.setContent(line)
|
||||
.setCategoryName("未分类")
|
||||
.setDifficulty("Medium")
|
||||
.setTags("待分类");
|
||||
questions.add(question);
|
||||
}
|
||||
}
|
||||
|
||||
return questions;
|
||||
}
|
||||
}
|
||||
package com.qingqiu.interview.service;
|
||||
|
||||
|
||||
import com.qingqiu.interview.entity.Question;
|
||||
import com.qingqiu.interview.entity.ai.QuestionClassificationAiRes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @program: ai-interview
|
||||
* @description: 题型分类
|
||||
* @author: huangpeng
|
||||
* @create: 2025-11-06 19:59
|
||||
**/
|
||||
public interface QuestionClassificationService {
|
||||
|
||||
List<QuestionClassificationAiRes.Item> classifyQuestions(String rawContent);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ 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.entity.QuestionCategory;
|
||||
import com.qingqiu.interview.vo.QuestionAndCategoryTreeListVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -27,4 +26,14 @@ public interface QuestionService extends IService<Question> {
|
||||
void useAiCheckQuestionData();
|
||||
|
||||
List<QuestionAndCategoryTreeListVO> getTreeListCategory(QuestionOptionsDTO dto);
|
||||
|
||||
/**
|
||||
* 根据技能和难度从本地题库随机选择题目
|
||||
*
|
||||
* @param skills 技能列表
|
||||
* @param difficulty 难度
|
||||
* @param count 题目数量
|
||||
* @return 题目列表
|
||||
*/
|
||||
List<Question> selectLocalQuestions(List<String> skills, String difficulty, int count);
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
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.common.enums.LLMProvider;
|
||||
import com.qingqiu.interview.ai.factory.AIClientManager;
|
||||
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 IAiSessionLogService aiSessionLogService;
|
||||
|
||||
@Override
|
||||
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 = list.stream().map(data -> {
|
||||
tokens.getAndAdd(AIUtils.getPromptTokens(data.getContent()));
|
||||
return AIUtils.createMessage(data.getRole(), data.getContent());
|
||||
}).toList();
|
||||
}
|
||||
|
||||
}
|
||||
if (CollectionUtil.isEmpty( messages)) {
|
||||
messages = new ArrayList<>();
|
||||
}
|
||||
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 "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.qingqiu.interview.service.impl;
|
||||
|
||||
import com.qingqiu.interview.mapper.InterviewSessionMapper;
|
||||
import com.qingqiu.interview.mapper.QuestionMapper;
|
||||
import com.qingqiu.interview.dto.DashboardStatsResponse;
|
||||
import com.qingqiu.interview.service.DashboardService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DashboardServiceImpl implements DashboardService {
|
||||
|
||||
private final QuestionMapper questionMapper;
|
||||
private final InterviewSessionMapper sessionMapper;
|
||||
|
||||
@Override
|
||||
public DashboardStatsResponse getDashboardStats() {
|
||||
DashboardStatsResponse stats = new DashboardStatsResponse();
|
||||
|
||||
// 1. 获取核心KPI
|
||||
stats.setTotalQuestions(questionMapper.selectCount(null));
|
||||
stats.setTotalInterviews(sessionMapper.selectCount(null));
|
||||
|
||||
// 2. 获取题库分类统计
|
||||
stats.setQuestionCategoryStats(questionMapper.countByCategory());
|
||||
|
||||
// 3. 获取最近7天的面试统计,并补全没有数据的日期
|
||||
List<DashboardStatsResponse.DailyStat> recentStats = sessionMapper.countRecentInterviews(7);
|
||||
stats.setRecentInterviewStats(fillMissingDates(recentStats, 7));
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充最近几天内没有面试数据的日期,补0
|
||||
*/
|
||||
private List<DashboardStatsResponse.DailyStat> fillMissingDates(List<DashboardStatsResponse.DailyStat> existingStats, int days) {
|
||||
Map<String, Long> statsMap = existingStats.stream()
|
||||
.collect(Collectors.toMap(DashboardStatsResponse.DailyStat::getDate, DashboardStatsResponse.DailyStat::getCount));
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
return IntStream.range(0, days)
|
||||
.mapToObj(i -> LocalDate.now().minusDays(i))
|
||||
.map(date -> {
|
||||
String dateString = date.format(formatter);
|
||||
long count = statsMap.getOrDefault(dateString, 0L);
|
||||
return new DashboardStatsResponse.DailyStat(dateString, count);
|
||||
})
|
||||
.sorted((d1, d2) -> d1.getDate().compareTo(d2.getDate())) // 按日期升序排序
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package com.qingqiu.interview.service.impl;
|
||||
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.qingqiu.interview.common.constants.ChatConstant;
|
||||
import com.qingqiu.interview.common.utils.PromptTemplateUtils;
|
||||
import com.qingqiu.interview.entity.InterviewQuestionProgress;
|
||||
import com.qingqiu.interview.entity.InterviewSession;
|
||||
import com.qingqiu.interview.entity.Question;
|
||||
import com.qingqiu.interview.entity.ai.EvaluateAiRes;
|
||||
import com.qingqiu.interview.entity.ai.ExtractSkillAiRes;
|
||||
import com.qingqiu.interview.entity.ai.InterviewReportAiRes;
|
||||
import com.qingqiu.interview.entity.ai.QuestionAiRes;
|
||||
import com.qingqiu.interview.service.InterviewAiService;
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.memory.ChatMemory;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* <h1></h1>
|
||||
*
|
||||
* @author qingqiu
|
||||
* @date 2025/9/19 16:49
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class InterviewAiServiceImpl implements InterviewAiService {
|
||||
|
||||
@Resource
|
||||
private ChatClient chatClient;
|
||||
|
||||
@Resource(name = ChatConstant.DASH_SCOPE_CHAT_CLIENT_BEAN_NAME)
|
||||
private ChatClient dashScopeChatClient;
|
||||
|
||||
@Resource(name = ChatConstant.OPEN_AI_CHAT_CLIENT_BEAN_NAME)
|
||||
private ChatClient openAiChatClient;
|
||||
|
||||
@Override
|
||||
public List<String> extractSkillsFromResume(String resumeContent) {
|
||||
ExtractSkillAiRes entity = chatClient
|
||||
.prompt(PromptTemplateUtils.getExtractSkillsPrompt(resumeContent))
|
||||
.call()
|
||||
.entity(ExtractSkillAiRes.class);
|
||||
assert entity != null;
|
||||
return entity.skills();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<QuestionAiRes.Question> generateQuestionsOfAi(String sessionId,
|
||||
List<String> skills,
|
||||
String jobRequirements,
|
||||
String resumeContent,
|
||||
int count) {
|
||||
// TODO: 考虑删除这些注释掉的旧代码实现
|
||||
// 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
|
||||
// );
|
||||
Map<String, Object> params = MapUtil.<String, Object>builder()
|
||||
.put("count", count)
|
||||
.put("jobRequirements", jobRequirements)
|
||||
.put("skills", JSONObject.toJSONString(skills))
|
||||
.put("resume", resumeContent)
|
||||
.build();
|
||||
Prompt aiInterviewerPrompt = PromptTemplateUtils.getAiInterviewerPrompt(params);
|
||||
QuestionAiRes.Wrapper entity = openAiChatClient
|
||||
.prompt(aiInterviewerPrompt)
|
||||
.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, sessionId))
|
||||
.call()
|
||||
.entity(QuestionAiRes.Wrapper.class);
|
||||
// TODO: 考虑删除这些注释掉的旧代码实现
|
||||
// String content = openAiChatClient
|
||||
// .prompt(aiInterviewerPrompt)
|
||||
// .advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, sessionId))
|
||||
// .call()
|
||||
//
|
||||
// .content()
|
||||
// ;
|
||||
// ChatDTO chatDTO = new ChatDTO()
|
||||
// .setSessionId(sessionId)
|
||||
// .setContent(prompt)
|
||||
// .setRole(Role.SYSTEM.getValue())
|
||||
// .setDataType(CommonConstant.ONE);
|
||||
// ChatVO chatVO = chatService.createChat(chatDTO);
|
||||
return entity.questions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<QuestionAiRes.Question> generateQuestionOfLocal(String sessionId,
|
||||
List<Question> questions,
|
||||
List<String> skills,
|
||||
String jobRequirements,
|
||||
String resumeContent,
|
||||
int count) {
|
||||
Map<String, Object> params = MapUtil.<String, Object>builder()
|
||||
.put("count", count)
|
||||
.put("jobRequirements", jobRequirements)
|
||||
.put("skills", JSONObject.toJSONString(skills))
|
||||
.put("resume", resumeContent)
|
||||
.build();
|
||||
|
||||
Prompt aiInterviewerPrompt = PromptTemplateUtils.getLocalInterviewPrompt(params);
|
||||
QuestionAiRes.Wrapper entity = openAiChatClient.prompt(aiInterviewerPrompt)
|
||||
.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, sessionId))
|
||||
.call()
|
||||
.entity(QuestionAiRes.Wrapper.class);
|
||||
assert entity != null;
|
||||
return entity.questions();
|
||||
// TODO: 考虑删除这些注释掉的旧代码实现
|
||||
// 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 EvaluateAiRes evaluateAnswer(String sessionId, String question, String userAnswer, List<InterviewQuestionProgress> context) {
|
||||
// TODO: 考虑删除这些注释掉的旧代码实现
|
||||
// 构建上下文历史
|
||||
// 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);
|
||||
Map<String, Object> params = MapUtil.<String, Object>builder()
|
||||
.put("question", question)
|
||||
.put("candidateAnswer", userAnswer)
|
||||
.build();
|
||||
Prompt prompt = PromptTemplateUtils.getEvaluatePrompt(params);
|
||||
return openAiChatClient
|
||||
.prompt(prompt)
|
||||
.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, sessionId))
|
||||
.call()
|
||||
.entity(EvaluateAiRes.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InterviewReportAiRes generateFinalReport(InterviewSession session, List<InterviewQuestionProgress> progressList) {
|
||||
// TODO: 考虑删除这些注释掉的旧代码实现
|
||||
// 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;
|
||||
// ChatDTO chatDTO = new ChatDTO()
|
||||
// .setRole(Role.SYSTEM.getValue())
|
||||
// .setDataType(CommonConstant.ONE)
|
||||
// .setContent(prompt);
|
||||
// ChatVO chatVO = chatService.createChat(chatDTO);
|
||||
Map<String, Object> params = getFinalReportParams(session, progressList);
|
||||
Prompt prompt = PromptTemplateUtils.getFinalReportPrompt(params);
|
||||
return openAiChatClient.prompt(prompt)
|
||||
.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, UUID.randomUUID().toString().replace("-", "")))
|
||||
.call()
|
||||
.entity(InterviewReportAiRes.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static Map<String, Object> getFinalReportParams(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 MapUtil.<String, Object>builder()
|
||||
.put("resume", session.getResumeContent())
|
||||
.put("history", historyBuilder.toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
/*
|
||||
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) {
|
||||
|
||||
// ChatDTO chatDTO = new ChatDTO()
|
||||
// .setSessionId(sessionId)
|
||||
// .setRole(Role.SYSTEM.getValue())
|
||||
// .setDataType(CommonConstant.ONE)
|
||||
// .setContent(prompt);
|
||||
// ChatVO chatVO = chatService.createChat(chatDTO);
|
||||
// return chatVO.getContent();
|
||||
String prompt = String.format("""
|
||||
你是一位专业的技术面试官。现在要开始面试,候选人是 %s。
|
||||
\s
|
||||
第一个问题是:%s
|
||||
\s
|
||||
请以友好但专业的语气提出这个问题,可以适当添加一些引导性的话语。
|
||||
严格按照JSON格式输出,不得包含任何markdown标记或额外解释:
|
||||
请返回JSON格式的数据:\s
|
||||
{
|
||||
"content": "xxx"
|
||||
}
|
||||
\s""", candidateName, questionContent);
|
||||
String content = openAiChatClient.prompt()
|
||||
.user(prompt)
|
||||
.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, sessionId))
|
||||
.call()
|
||||
.content();
|
||||
return JSON.parseObject(content).getString("content");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,13 @@ import java.io.IOException;
|
||||
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);
|
||||
// TODO: 检查这个空if语句是否需要实现逻辑或删除
|
||||
// 判断是否使用本地题库
|
||||
if (request.getModel().equals("local")) {
|
||||
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -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>
|
||||
@@ -35,9 +37,43 @@ public class InterviewQuestionProgressServiceImpl extends ServiceImpl<InterviewQ
|
||||
InterviewQuestionProgress.Status.COMPLETED.name()
|
||||
)
|
||||
)
|
||||
.orderByDesc(InterviewQuestionProgress::getCreatedTime)
|
||||
.orderByAsc(InterviewQuestionProgress::getStatus)
|
||||
.orderByDesc(InterviewQuestionProgress::getUpdatedTime)
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
package com.qingqiu.interview.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.io.file.FileNameUtil;
|
||||
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.entity.ai.EvaluateAiRes;
|
||||
import com.qingqiu.interview.entity.ai.InterviewReportAiRes;
|
||||
import com.qingqiu.interview.entity.ai.QuestionAiRes;
|
||||
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.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
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;
|
||||
|
||||
private final Map<String, Integer> flowedQuestions = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public InterviewSession startInterview(MultipartFile file, InterviewStartRequest dto) throws IOException {
|
||||
// 1. 创建并保存会话主记录
|
||||
String sessionId = UUID.randomUUID().toString().replace("-", "");
|
||||
String resumeContent = readPdfFile(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());
|
||||
session.setJobRequirements(dto.getJobRequirements());
|
||||
this.baseMapper.insert(session); // 先插入以获取ID
|
||||
|
||||
// 2. 调用AI服务从简历提取技能
|
||||
List<String> skills = aiService.extractSkillsFromResume(resumeContent);
|
||||
|
||||
// ---> 解析AI返回的JSON数据,获取技能列表 <---
|
||||
session.setExtractedSkills(JSONObject.toJSONString(skills));
|
||||
|
||||
// 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);
|
||||
String aiRes = aiService.generateFirstQuestion(session.getSessionId(),
|
||||
session.getCandidateName(),
|
||||
nextQuestion.getQuestionContent()
|
||||
);
|
||||
saveMessage(sessionId,
|
||||
InterviewMessage.MessageType.QUESTION.name(),
|
||||
InterviewMessage.Sender.AI.name(),
|
||||
// nextQuestion.getQuestionContent(),
|
||||
aiRes,
|
||||
nextQuestion.getId()
|
||||
);
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
private void aiGenerateQuestions(InterviewSession session, List<String> skills) {
|
||||
List<InterviewQuestionProgress> progressList = new ArrayList<>();
|
||||
List<QuestionAiRes.Question> aiQuestionRes = aiService.generateQuestionsOfAi(
|
||||
session.getSessionId(),
|
||||
skills,
|
||||
session.getJobRequirements(),
|
||||
session.getResumeContent(),
|
||||
session.getTotalQuestions()
|
||||
);
|
||||
if (CollectionUtil.isNotEmpty(aiQuestionRes)) {
|
||||
for (QuestionAiRes.Question aiQuestionRe : aiQuestionRes) {
|
||||
InterviewQuestionProgress progress = new InterviewQuestionProgress();
|
||||
progress.setSessionId(session.getSessionId());
|
||||
progress.setQuestionId(0L); // AI生成的问题没有本地ID
|
||||
// ---> 解析单个问题内容 <---
|
||||
progress.setQuestionContent(aiQuestionRe.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调用返回的内容进行提取
|
||||
List<QuestionAiRes.Question> questions = aiService.generateQuestionOfLocal(
|
||||
session.getSessionId(),
|
||||
localQuestionDataList,
|
||||
skills,
|
||||
session.getJobRequirements(),
|
||||
session.getResumeContent(),
|
||||
session.getTotalQuestions()
|
||||
);
|
||||
Set<String> resQuestionIds = questions.stream().map(QuestionAiRes.Question::id).collect(Collectors.toSet());
|
||||
// 查询返回的内容 并将其保存为问题进度的相关数据
|
||||
List<Question> questionList = questionService.list(
|
||||
new LambdaQueryWrapper<Question>()
|
||||
.in(Question::getId, resQuestionIds)
|
||||
);
|
||||
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)
|
||||
);
|
||||
Integer flowedQuestionCount = this.flowedQuestions.getOrDefault(currentProgress.getSessionId(), 0);
|
||||
EvaluateAiRes evaluateAiRes = aiService.evaluateAnswer(
|
||||
currentProgress.getSessionId(),
|
||||
currentProgress.getQuestionContent(),
|
||||
dto.getAnswer(),
|
||||
context
|
||||
);
|
||||
|
||||
// 3. ---> 解析AI返回的JSON评估结果并存入数据库 <---
|
||||
currentProgress.setFeedback(evaluateAiRes.feedback());
|
||||
currentProgress.setSuggestions(evaluateAiRes.suggestions());
|
||||
currentProgress.setAiAnswer(evaluateAiRes.aiAnswer());
|
||||
currentProgress.setScore(BigDecimal.valueOf(evaluateAiRes.score()));
|
||||
currentProgress.setStatus(InterviewQuestionProgress.Status.COMPLETED.name());
|
||||
progressService.updateById(currentProgress);
|
||||
|
||||
// 4. 将单题评估结果存入 evaluation 表用于分析
|
||||
saveEvaluationRecord(currentProgress, evaluateAiRes);
|
||||
|
||||
|
||||
// 5. ---> 解析AI的是否追问判断,并处理追问逻辑 <---
|
||||
if (evaluateAiRes.continueAsking()) {
|
||||
// 创建一个新的、状态为ACTIVE的追问问题
|
||||
InterviewQuestionProgress followUp = new InterviewQuestionProgress();
|
||||
followUp.setSessionId(currentProgress.getSessionId());
|
||||
followUp.setQuestionId(0L); // 追问问题没有本地ID
|
||||
followUp.setQuestionContent(evaluateAiRes.followUpQuestion());
|
||||
followUp.setStatus(InterviewQuestionProgress.Status.ACTIVE.name()); // 直接设为激活状态,作为下一个问题
|
||||
progressService.save(followUp);
|
||||
// 记录追问题目数量
|
||||
flowedQuestionCount++;
|
||||
this.flowedQuestions.put(currentProgress.getSessionId(), flowedQuestionCount);
|
||||
return followUp; // 将这个新的追问问题返回给前端
|
||||
}
|
||||
// 清空追问题目数量
|
||||
this.flowedQuestions.put(currentProgress.getSessionId(), 0);
|
||||
|
||||
return currentProgress;
|
||||
}
|
||||
|
||||
private void saveEvaluationRecord(InterviewQuestionProgress progress, EvaluateAiRes evaluateAiRes) {
|
||||
InterviewEvaluation evaluation = new InterviewEvaluation();
|
||||
evaluation.setSessionId(progress.getSessionId());
|
||||
evaluation.setQuestionId(progress.getQuestionId());
|
||||
evaluation.setUserAnswer(progress.getUserAnswer());
|
||||
// ---> 解析AI评估结果并存入分析表 <---
|
||||
evaluation.setAiFeedback(evaluateAiRes.feedback());
|
||||
evaluation.setScore(BigDecimal.valueOf(evaluateAiRes.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服务生成最终报告
|
||||
InterviewReportAiRes interviewReportAiRes = aiService.generateFinalReport(session, completedProgresses);
|
||||
|
||||
// 3. ---> 解析AI返回的最终报告JSON,更新会话状态 <---
|
||||
session.setStatus(InterviewSession.Status.COMPLETED.name());
|
||||
session.setScore(new BigDecimal(interviewReportAiRes.overallScore()));
|
||||
session.setFinalReport(JSONObject.toJSONString(interviewReportAiRes));
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String readPdfFile(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.qingqiu.interview.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.qingqiu.interview.entity.Question;
|
||||
import com.qingqiu.interview.entity.ai.QuestionClassificationAiRes;
|
||||
import com.qingqiu.interview.service.QuestionClassificationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.chat.prompt.PromptTemplate;
|
||||
import org.springframework.ai.template.st.StTemplateRenderer;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class QuestionClassificationServiceImpl implements QuestionClassificationService {
|
||||
|
||||
private final ChatClient chatClient;
|
||||
|
||||
/**
|
||||
* 使用AI对题目进行分类
|
||||
*/
|
||||
@Override
|
||||
public List<QuestionClassificationAiRes.Item> classifyQuestions(String rawContent) {
|
||||
log.info("开始使用AI分类题目,内容长度: {}", rawContent.length());
|
||||
|
||||
|
||||
QuestionClassificationAiRes.Wrapper entity = chatClient.prompt()
|
||||
.user(buildClassificationPrompt(rawContent))
|
||||
.call()
|
||||
.entity(QuestionClassificationAiRes.Wrapper.class);
|
||||
assert entity != null;
|
||||
return entity.questions();
|
||||
}
|
||||
|
||||
private String buildClassificationPrompt(String content) {
|
||||
|
||||
PromptTemplate prompt = PromptTemplate.builder()
|
||||
.renderer(StTemplateRenderer.builder().startDelimiterToken('<').endDelimiterToken('>').build())
|
||||
.template(
|
||||
"""
|
||||
请分析以下面试题内容,将其分类并提取信息。请严格按照以下JSON格式返回结果:
|
||||
|
||||
{
|
||||
"questions": [
|
||||
{
|
||||
"content": "题目内容",
|
||||
"category": "分类(如:Java基础、Spring框架、数据库、算法、系统设计等)",
|
||||
"difficulty": "难度(Easy、Medium、Hard)",
|
||||
"tags": "相关标签,用逗号分隔"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
分类规则:
|
||||
1. category应该是具体的技术领域,如:Java基础、Spring框架、MySQL、Redis、算法与数据结构、系统设计、网络协议等
|
||||
2. difficulty根据题目复杂度判断:Easy(基础概念)、Medium(实际应用)、Hard(深入原理或复杂场景)
|
||||
3. tags包含更细粒度的标签,如:多线程、JVM、事务、索引等
|
||||
4. 如果内容包含多个独立的题目,请分别提取
|
||||
5. 只返回JSON,不要其他解释文字
|
||||
|
||||
待分析内容:
|
||||
<content>
|
||||
"""
|
||||
)
|
||||
.build();
|
||||
return prompt.render(Map.of("content", content));
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,36 @@
|
||||
package com.qingqiu.interview.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
|
||||
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.common.enums.LLMProvider;
|
||||
import com.qingqiu.interview.common.utils.TreeUtils;
|
||||
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.entity.ai.QuestionClassificationAiRes;
|
||||
import com.qingqiu.interview.entity.ai.QuestionDeduplicationAiRes;
|
||||
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 jakarta.annotation.Resource;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.prompt.PromptTemplate;
|
||||
import org.springframework.ai.template.TemplateRenderer;
|
||||
import org.springframework.ai.template.st.StTemplateRenderer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -31,10 +38,7 @@ 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.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@@ -42,11 +46,12 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor(onConstructor_ = {@Autowired, @Lazy})
|
||||
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
|
||||
private final QuestionMapper questionMapper;
|
||||
private final QuestionClassificationService classificationService;
|
||||
private final QuestionClassificationServiceImpl classificationService;
|
||||
private final List<DocumentParser> documentParserList; // This will be injected by Spring
|
||||
private final LlmService llmService;
|
||||
private final IQuestionCategoryService questionCategoryService;
|
||||
|
||||
private final ChatClient chatClient;
|
||||
|
||||
/**
|
||||
* 分页查询题库
|
||||
*/
|
||||
@@ -101,19 +106,19 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
.orElseThrow(() -> new IllegalArgumentException("不支持的文件类型: " + fileExtension));
|
||||
|
||||
String content = parser.parse(file.getInputStream());
|
||||
List<Question> questionsFromAi = classificationService.classifyQuestions(content);
|
||||
List<QuestionClassificationAiRes.Item> items = classificationService.classifyQuestions(content);
|
||||
|
||||
int newQuestionsCount = 0;
|
||||
for (Question question : questionsFromAi) {
|
||||
for (QuestionClassificationAiRes.Item item : items) {
|
||||
try {
|
||||
validateQuestion(question.getContent(), null);
|
||||
questionMapper.insert(question);
|
||||
validateQuestion(item.content(), null);
|
||||
questionMapper.insert(BeanUtil.toBean(item, Question.class));
|
||||
newQuestionsCount++;
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("跳过重复题目: {}", question.getContent());
|
||||
log.warn("跳过重复题目: {}", item.content());
|
||||
}
|
||||
}
|
||||
log.info("成功导入 {} 个新题目,跳过 {} 个重复题目。", newQuestionsCount, questionsFromAi.size() - newQuestionsCount);
|
||||
log.info("成功导入 {} 个新题目,跳过 {} 个重复题目。", newQuestionsCount, items.size() - newQuestionsCount);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,16 +137,18 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
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);
|
||||
|
||||
|
||||
QuestionDeduplicationAiRes entity = chatClient.prompt().user(prompt).call().entity(QuestionDeduplicationAiRes.class);
|
||||
assert entity != null;
|
||||
// 调用AI
|
||||
log.info("AI返回内容: {}", chat);
|
||||
JSONObject parse = JSONObject.parse(chat);
|
||||
JSONArray questionsIds = parse.getJSONArray("questions");
|
||||
List<Long> list = questionsIds.toList(Long.class);
|
||||
log.info("AI返回内容: {}", JSONObject.toJSONString(entity));
|
||||
String s = entity.questionIds();
|
||||
List<String> list = Arrays.asList(s.split(","));
|
||||
// TODO: 检查这些注释代码是否可以删除
|
||||
// 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)
|
||||
@@ -160,25 +167,71 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
}
|
||||
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());
|
||||
|
||||
return PromptTemplate.builder()
|
||||
.renderer(
|
||||
StTemplateRenderer.builder()
|
||||
.startDelimiterToken('<')
|
||||
.endDelimiterToken('>')
|
||||
.build()
|
||||
)
|
||||
.template("""
|
||||
请对以下题库JSON数据进行智能去重处理。
|
||||
|
||||
## 任务说明
|
||||
识别并移除语义相似或表达意思基本相同的重复题目,只保留每个独特题目的一个版本。
|
||||
|
||||
## 语义相似度判断标准
|
||||
1. 核心意思相同:即使表述不同,但考察的知识点和答案逻辑一致
|
||||
2. 同义替换:使用同义词、近义词但意思不变的题目
|
||||
3. 句式变换:主动被动语态转换、疑问词替换等句式变化
|
||||
4. 冗余表述:增加了无关修饰词但核心内容相同的题目
|
||||
|
||||
## 处理规则
|
||||
- 对语义相似的题目组,只保留其中一条数据
|
||||
- 保留原则:选择表述最清晰、最完整的那条
|
||||
- 如果难以判断,保留ID较小或创建时间较早的那条
|
||||
|
||||
## 输出要求
|
||||
1. 只返回JSON,不要其他解释文字
|
||||
2. 请严格按照API接口形式返回,不要返回任何额外的文字内容,包括'```json```'!!!!
|
||||
3. 请严格按照网络接口的形式返回JSON数据!!!
|
||||
{
|
||||
"questionIds": "1, 2, 3" # 请返回保留数据的id
|
||||
}
|
||||
|
||||
## 特殊说明
|
||||
- 注意区分真正重复和只是题型相似的题目
|
||||
- 对于选择题,要同时考虑题干和选项的语义相似度
|
||||
- 保留题目版本的完整性
|
||||
|
||||
请处理以下JSON数据:
|
||||
<data>
|
||||
""")
|
||||
.build()
|
||||
.render(Map.of("data", jsonObject.toJSONString()))
|
||||
;
|
||||
|
||||
// TODO: 检查这些注释代码是否可以删除 - 这是旧的prompt模板实现
|
||||
// return String.format("""
|
||||
// 你是一个数据清洗与去重专家。你的任务是从以下文本列表中,识别出语义相同或高度相似的条目,并为每一组相似条目筛选出一个最规范、最简洁的代表性版本。
|
||||
//
|
||||
// 【去重规则】
|
||||
// 1. **语义核心优先**:忽略无关的修饰词、标点符号、后缀(如“:2”)、大小写和空格。
|
||||
// 2. **合并同类项**:将表达同一主题或问题的文本归为一组。
|
||||
// 3. **选择标准**:从每一组中,选出那个最完整、最简洁、且没有多余符号(如序号、特殊后缀)的版本作为代表。如果两个版本质量相当,优先选择更短的那个。
|
||||
// 4. **保留原意**:确保选出的代表版本没有改变原文本的核心含义。
|
||||
// 请返回数据的id,已被剔除掉的数据无需返回,格式如下:
|
||||
// {
|
||||
// "questions": [1, 2, 3, .....]
|
||||
// }
|
||||
// 分类规则:
|
||||
// 1. 只返回JSON,不要其他解释文字
|
||||
// 2. 请严格按照API接口形式返回,不要返回任何额外的文字内容,包括'```json```'!!!!
|
||||
// 3. 请严格按照网络接口的形式返回JSON数据!!!
|
||||
// 【请处理以下数据列表】:
|
||||
// %s
|
||||
// """, jsonObject.toJSONString());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,7 +267,7 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
if (CollectionUtil.isNotEmpty(dto.getCategoryIds())) {
|
||||
questionCategories = questionCategoryService.batchFindByAncestorIdsUnion(dto.getCategoryIds());
|
||||
if (CollectionUtil.isNotEmpty(questionCategories)) {
|
||||
treeList = TreeUtil.buildTree(
|
||||
treeList = TreeUtils.buildTree(
|
||||
questionCategories,
|
||||
QuestionCategory::getId,
|
||||
QuestionCategory::getParentId,
|
||||
@@ -242,6 +295,7 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
log.info("根节点题目总数: {}", i);
|
||||
QuestionAndCategoryTreeListVO rootVO = new QuestionAndCategoryTreeListVO();
|
||||
rootVO.setId(0L);
|
||||
rootVO.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
|
||||
rootVO.setName("全部题目");
|
||||
rootVO.setType("root");
|
||||
rootVO.setChildren(voList);
|
||||
@@ -252,6 +306,20 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
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列表,并整合题目数据
|
||||
*
|
||||
@@ -302,6 +370,7 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
vo.setName(category.getName());
|
||||
vo.setType("category");
|
||||
vo.setCount(0);
|
||||
vo.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
|
||||
|
||||
// 处理子节点(包括子分类和题目)
|
||||
List<QuestionAndCategoryTreeListVO> childrenVOs = new ArrayList<>();
|
||||
@@ -355,6 +424,7 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
|
||||
vo.setChildren(List.of());
|
||||
vo.setType("question");
|
||||
vo.setCount(0); // 题目节点没有子节点,count设为0
|
||||
vo.setNodeKey(UUID.randomUUID().toString().replace("-", ""));
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.qingqiu.interview.service.llm;
|
||||
|
||||
import com.qingqiu.interview.common.enums.LLMProvider;
|
||||
|
||||
public interface LlmService {
|
||||
|
||||
|
||||
/**
|
||||
* 与模型进行单轮对话
|
||||
* @param prompt 提示词
|
||||
* @return ai回复
|
||||
*/
|
||||
String chat(String prompt);
|
||||
String chat(String prompt, LLMProvider provider);
|
||||
|
||||
/**
|
||||
* 与模型进行多轮对话
|
||||
* @param prompt 提示词
|
||||
* @param token 会话token
|
||||
* @return ai回复
|
||||
*/
|
||||
String chat(String prompt, String token);
|
||||
|
||||
/**
|
||||
* 与模型进行多轮对话 指定模型
|
||||
* @param prompt 提示词
|
||||
* @param model 模型名称
|
||||
* @param token 会话token
|
||||
* @return ai回复
|
||||
*/
|
||||
String chat(String prompt, String token, LLMProvider provider);
|
||||
|
||||
Integer getPromptTokens(String prompt);
|
||||
}
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
package com.qingqiu.interview.service.llm.qwen;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.dashscope.aigc.generation.Generation;
|
||||
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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.qingqiu.interview.common.enums.LLMProvider;
|
||||
import com.qingqiu.interview.ai.factory.AIClientManager;
|
||||
import com.qingqiu.interview.entity.AiSessionLog;
|
||||
import com.qingqiu.interview.mapper.AiSessionLogMapper;
|
||||
import com.qingqiu.interview.service.llm.LlmService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.qingqiu.interview.common.utils.AIUtils.createMessage;
|
||||
|
||||
@Slf4j
|
||||
@Service("qwenService")
|
||||
@RequiredArgsConstructor
|
||||
public class QwenService implements LlmService {
|
||||
|
||||
private final Generation generation;
|
||||
|
||||
private final AiSessionLogMapper aiSessionLogMapper;
|
||||
|
||||
@Value("${dashscope.api-key}")
|
||||
private String apiKey;
|
||||
|
||||
private final AIClientManager aiClientManager;
|
||||
|
||||
|
||||
@Override
|
||||
public String chat(String prompt) {
|
||||
// log.info("开始调用API....");
|
||||
// long l = System.currentTimeMillis();
|
||||
return chat(prompt, LLMProvider.DEEPSEEK);
|
||||
// GenerationParam param = GenerationParam.builder()
|
||||
// .model(DEEPSEEK_3) // 可根据需要更换模型
|
||||
// .messages(Collections.singletonList(createMessage(Role.USER.getValue(), prompt)))
|
||||
// .resultFormat(GenerationParam.ResultFormat.MESSAGE)
|
||||
// .apiKey(apiKey)
|
||||
// .build();
|
||||
//
|
||||
// GenerationResult result = null;
|
||||
// try {
|
||||
// result = generation.call(param);
|
||||
// log.info("调用成功,耗时: {} ms", System.currentTimeMillis() - l);
|
||||
// log.debug("响应结果: {}", result.getOutput().getChoices().get(0).getMessage().getContent());
|
||||
// return result.getOutput().getChoices().get(0).getMessage().getContent();
|
||||
// } catch (ApiException | InputRequiredException e) {
|
||||
// throw new RuntimeException("调用AI服务失败", e);
|
||||
// } catch (NoApiKeyException e) {
|
||||
// throw new RuntimeException("请检查API密钥是否正确", e);
|
||||
// }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chat(String prompt, LLMProvider provider) {
|
||||
return aiClientManager.getClient(provider).chatCompletion(prompt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chat(String prompt, String token) {
|
||||
return chat(prompt, token, LLMProvider.DEEPSEEK);
|
||||
|
||||
// // 调用AI模型
|
||||
// try {
|
||||
// log.info("开始调用API....");
|
||||
// long l = System.currentTimeMillis();
|
||||
// GenerationParam param = GenerationParam.builder()
|
||||
// .model(DEEPSEEK_3_1) // 可根据需要更换模型
|
||||
// .messages(messages)
|
||||
// .resultFormat(GenerationParam.ResultFormat.MESSAGE)
|
||||
// .apiKey(apiKey)
|
||||
// .build();
|
||||
//
|
||||
// GenerationResult result = generation.call(param);
|
||||
// log.info("调用成功,耗时: {} ms", System.currentTimeMillis() - l);
|
||||
// String aiResponse = result.getOutput().getChoices().get(0).getMessage().getContent();
|
||||
// log.debug("响应结果: {}", aiResponse);
|
||||
// // 存储用户提问
|
||||
// AiSessionLog userLog = new AiSessionLog();
|
||||
// userLog.setToken(token);
|
||||
// userLog.setRole(Role.USER.getValue());
|
||||
// userLog.setContent(prompt);
|
||||
// aiSessionLogMapper.insert(userLog);
|
||||
//
|
||||
// // 存储AI回复
|
||||
// AiSessionLog aiLog = new AiSessionLog();
|
||||
// aiLog.setToken(token);
|
||||
// aiLog.setRole(Role.ASSISTANT.getValue());
|
||||
// aiLog.setContent(aiResponse);
|
||||
// aiSessionLogMapper.insert(aiLog);
|
||||
//
|
||||
// return aiResponse;
|
||||
// } catch (ApiException | NoApiKeyException | InputRequiredException e) {
|
||||
// throw new RuntimeException("调用AI服务失败", e);
|
||||
// }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chat(String prompt, String token, LLMProvider provider) {
|
||||
// 根据token查询会话记录
|
||||
List<AiSessionLog> aiSessionLogs = aiSessionLogMapper.selectList(
|
||||
new LambdaQueryWrapper<AiSessionLog>()
|
||||
.eq(AiSessionLog::getToken, token)
|
||||
.orderByDesc(AiSessionLog::getCreatedTime)
|
||||
);
|
||||
// 构造发给ai的消息
|
||||
List<Message> messages = new ArrayList<>();
|
||||
if (CollectionUtil.isNotEmpty(aiSessionLogs)) {
|
||||
// 预估tokens
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (AiSessionLog aiSessionLog : aiSessionLogs) {
|
||||
sb.append(aiSessionLog.getContent());
|
||||
}
|
||||
// 加上本次对话内容
|
||||
sb.append(prompt);
|
||||
Integer promptTokens = getPromptTokens(sb.toString());
|
||||
// 如果token大于了模型上限,则执行丢弃操作
|
||||
int size = aiSessionLogs.size();
|
||||
log.info("当前会话id: {}, tokens: {}", token, promptTokens);
|
||||
|
||||
// 假设模型上限为30000个token(根据实际模型调整)
|
||||
int maxTokens = 100000;
|
||||
if (promptTokens > maxTokens) {
|
||||
// 需要丢弃30%的会话记录(按时间倒序,丢弃最旧的)
|
||||
int discardCount = (int) (size * 0.3);
|
||||
// 从当前会话记录列表中移除旧的会话记录,而不是删除数据库中的记录
|
||||
for (int i = 0; i < discardCount; i++) {
|
||||
aiSessionLogs.remove(aiSessionLogs.size() - 1);
|
||||
}
|
||||
}
|
||||
// 移除旧记录后再按时间正序排序(最旧的在前面,最新的在后面)
|
||||
aiSessionLogs = aiSessionLogs.stream()
|
||||
.sorted((log1, log2) -> log1.getCreatedTime().compareTo(log2.getCreatedTime()))
|
||||
.collect(Collectors.toList());
|
||||
for (AiSessionLog aiSessionLog : aiSessionLogs) {
|
||||
messages.add(
|
||||
createMessage(aiSessionLog.getRole(), aiSessionLog.getContent())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
messages.add(
|
||||
createMessage(Role.USER.getValue(), prompt)
|
||||
);
|
||||
|
||||
String aiResponse = aiClientManager.getClient(provider).chatCompletion(messages);
|
||||
// 存储用户提问
|
||||
AiSessionLog userLog = new AiSessionLog();
|
||||
userLog.setToken(token);
|
||||
userLog.setRole(Role.USER.getValue());
|
||||
userLog.setContent(prompt);
|
||||
aiSessionLogMapper.insert(userLog);
|
||||
|
||||
// 存储AI回复
|
||||
AiSessionLog aiLog = new AiSessionLog();
|
||||
aiLog.setToken(token);
|
||||
aiLog.setRole(Role.ASSISTANT.getValue());
|
||||
aiLog.setContent(aiResponse);
|
||||
aiSessionLogMapper.insert(aiLog);
|
||||
return aiResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取prompt的token数
|
||||
*
|
||||
* @param prompt 输入
|
||||
* @return tokens
|
||||
*/
|
||||
@Override
|
||||
public Integer getPromptTokens(String prompt) {
|
||||
Tokenizer tokenizer = TokenizerFactory.qwen();
|
||||
List<Integer> integers = tokenizer.encodeOrdinary(prompt);
|
||||
return integers.size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import lombok.experimental.Accessors;
|
||||
* @date 2025/9/18 12:56
|
||||
*/
|
||||
@Data
|
||||
@Accessors
|
||||
@Accessors(chain = true)
|
||||
@Builder
|
||||
public class ChatVO {
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ public class QuestionAndCategoryTreeListVO implements Serializable {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String nodeKey;
|
||||
|
||||
private String name;
|
||||
/**
|
||||
* category:分类
|
||||
|
||||
@@ -1,14 +1,43 @@
|
||||
dashscope:
|
||||
api-key: sk-58d6fed688c54e8db02e6a7ffbfc7a5f
|
||||
deepseek:
|
||||
api-url: https://api.deepseek.com/chat/completions
|
||||
api-key: sk-faaa2a1b485442ccbf115ff1271a3480
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://gz-cynosdbmysql-grp-5ai5zw7r.sql.tencentcdb.com:24944/ai_interview?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
|
||||
username: qingqiu
|
||||
password: 020979hP
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
ai:
|
||||
openai:
|
||||
base-url: https://api.ruyun.fun
|
||||
api-key: ${RUYUN_API_KEY}
|
||||
chat:
|
||||
options:
|
||||
model: gemini-2.5-flash-nothinking
|
||||
dashscope:
|
||||
api-key: ${DASHSCOPE_API_KEY}
|
||||
read-timeout: 600
|
||||
chat:
|
||||
options:
|
||||
model: qwen3-max
|
||||
memory:
|
||||
redis:
|
||||
host: 127.0.0.1
|
||||
port: 6379
|
||||
password: 123456
|
||||
timeout: 6000
|
||||
data:
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
password: 123456
|
||||
database: 0
|
||||
timeout: 6000
|
||||
jedis:
|
||||
pool:
|
||||
max-active: 16
|
||||
max-idle: 8
|
||||
min-idle: 0
|
||||
max-wait: -1ms
|
||||
|
||||
# TODO: 考虑删除已注释的配置
|
||||
# ai:
|
||||
# openai:
|
||||
# api-key: sk-faaa2a1b485442ccbf115ff1271a3480
|
||||
@@ -16,6 +45,14 @@ spring:
|
||||
# chat:
|
||||
# options:
|
||||
# model: deepseek-chat
|
||||
logging:
|
||||
level:
|
||||
org:
|
||||
springframework:
|
||||
ai:
|
||||
chat:
|
||||
client:
|
||||
advisor: debug
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
@@ -24,4 +61,4 @@ mybatis-plus:
|
||||
db-config:
|
||||
logic-delete-field: deleted # 全局逻辑删除字段名
|
||||
logic-delete-value: 1 # 逻辑已删除值。可选,默认值为 1
|
||||
logic-not-delete-value: 0 # 逻辑未删除值。可选,默认值为 0
|
||||
logic-not-delete-value: 0 # 逻辑未删除值。可选,默认值为 0
|
||||
|
||||
61
src/main/resources/logback-spring.xml
Normal file
61
src/main/resources/logback-spring.xml
Normal file
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<property name="LOG_PATH" value="./logs"/>
|
||||
<property name="LOG_FILE_NAME" value="interview"/>
|
||||
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${LOG_FILE_NAME}.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/${LOG_FILE_NAME}.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>100MB</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/error.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/error.%d{yyyy-MM-dd}.log.gz</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>ERROR</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>256</queueSize>
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<appender-ref ref="FILE"/>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="ASYNC_FILE"/>
|
||||
<appender-ref ref="ERROR_FILE"/>
|
||||
</root>
|
||||
|
||||
<logger name="com.qingqiu.interview" level="DEBUG" additivity="false">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="ASYNC_FILE"/>
|
||||
<appender-ref ref="ERROR_FILE"/>
|
||||
</logger>
|
||||
|
||||
</configuration>
|
||||
@@ -1,23 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.qingqiu.interview.mapper.InterviewMessageMapper">
|
||||
|
||||
<select id="selectBySessionIdOrderByOrder" resultType="com.qingqiu.interview.entity.InterviewMessage">
|
||||
SELECT * FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
ORDER BY message_order ASC
|
||||
</select>
|
||||
|
||||
<select id="selectLatestBySessionId" resultType="com.qingqiu.interview.entity.InterviewMessage">
|
||||
SELECT * FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
ORDER BY message_order DESC
|
||||
LIMIT 1
|
||||
</select>
|
||||
|
||||
<select id="selectMaxOrderBySessionId" resultType="int">
|
||||
SELECT COALESCE(MAX(message_order), 0) FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.qingqiu.interview.mapper.InterviewMessageMapper">
|
||||
|
||||
<select id="selectBySessionIdOrderByOrder" resultType="com.qingqiu.interview.entity.InterviewMessage">
|
||||
SELECT * FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
ORDER BY message_order ASC
|
||||
</select>
|
||||
|
||||
<select id="selectLatestBySessionId" resultType="com.qingqiu.interview.entity.InterviewMessage">
|
||||
SELECT * FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
ORDER BY message_order DESC
|
||||
LIMIT 1
|
||||
</select>
|
||||
|
||||
<select id="selectMaxOrderBySessionId" resultType="int">
|
||||
SELECT COALESCE(MAX(message_order), 0) FROM interview_message
|
||||
WHERE session_id = #{sessionId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
Reference in New Issue
Block a user