feat: align training AI assessment with task steps

bugfix/ai-assessment-evidence-rescore
chenyuan 3 months ago
parent 9b389607a0
commit 067469bd4c

@ -1,14 +1,29 @@
package com.sztzjy.linkCommerce.entity.dto;
import java.util.ArrayList;
import java.util.List;
public class ReleaseChannelEvaluationStepThreeValidationResult {
private boolean valid;
private boolean calculationCorrect;
private String message;
private int rowCount;
private int totalItemCount;
private int incorrectItemCount;
private List<String> incorrectItems = new ArrayList<>();
public boolean isValid() { return valid; }
public void setValid(boolean valid) { this.valid = valid; }
public boolean isCalculationCorrect() { return calculationCorrect; }
public void setCalculationCorrect(boolean calculationCorrect) { this.calculationCorrect = calculationCorrect; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public int getRowCount() { return rowCount; }
public void setRowCount(int rowCount) { this.rowCount = rowCount; }
public int getTotalItemCount() { return totalItemCount; }
public void setTotalItemCount(int totalItemCount) { this.totalItemCount = totalItemCount; }
public int getIncorrectItemCount() { return incorrectItemCount; }
public void setIncorrectItemCount(int incorrectItemCount) { this.incorrectItemCount = incorrectItemCount; }
public List<String> getIncorrectItems() { return incorrectItems; }
public void setIncorrectItems(List<String> incorrectItems) { this.incorrectItems = incorrectItems == null ? new ArrayList<>() : incorrectItems; }
}

@ -26,5 +26,5 @@ public interface AiTrainingEvaluationMapper {
@Param("updateTime") Date updateTime);
int failAssessment(@Param("id") String id, @Param("errorMessage") String errorMessage,
@Param("updateTime") Date updateTime);
@Param("rawResponse") String rawResponse, @Param("updateTime") Date updateTime);
}

@ -28,7 +28,10 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@ -39,6 +42,7 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
private static final int MAX_ERROR_LENGTH = 1000;
private static final int MAX_HELP_QUESTION_LENGTH = 500;
private static final int MAX_STEP_CONTEXT_LENGTH = 2000;
private static final int MAX_ASSESSMENT_RATIONALE_CHARACTERS = 200;
private final ObjectMapper objectMapper = new ObjectMapper();
@ -125,16 +129,20 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
String taskSnapshot = taskSnapshot(context.effectiveContent);
String answerSnapshot = answerSnapshot(context.answer);
String knowledgeContext = knowledgeContext(context, user, "");
List<AssessmentCriterionPlan> criterionPlan = assessmentCriterionPlan(context.effectiveContent.getSteps());
String rawResponse = null;
try {
String rawResponse = qwenChatClient.completeJson(assessmentSystemPrompt(), assessmentUserPrompt(taskSnapshot, answerSnapshot, knowledgeContext));
int score = validateAssessment(rawResponse);
rawResponse = qwenChatClient.completeJson(assessmentSystemPrompt(criterionPlan), assessmentUserPrompt(taskSnapshot, answerSnapshot, knowledgeContext));
JsonNode assessmentReport = object(rawResponse);
int score = validateAssessment(assessmentReport, criterionPlan);
compactAssessmentRationales(assessmentReport);
Date completedAt = new Date();
AiTrainingEvaluation completed = new AiTrainingEvaluation();
completed.setId(evaluation.getId());
completed.setAssessmentTaskSnapshot(taskSnapshot);
completed.setAssessmentAnswerSnapshot(answerSnapshot);
completed.setAssessmentScore(score);
completed.setAssessmentReportJson(rawResponse);
completed.setAssessmentReportJson(json(assessmentReport));
completed.setAssessmentRawResponse(rawResponse);
completed.setAssessmentModel("qwen");
completed.setAssessmentCompletedAt(completedAt);
@ -144,7 +152,7 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
completed.setAssessmentStatus(SUCCEEDED);
return toView(completed);
} catch (RuntimeException e) {
aiTrainingEvaluationMapper.failAssessment(evaluation.getId(), cappedMessage(e), new Date());
aiTrainingEvaluationMapper.failAssessment(evaluation.getId(), cappedMessage(e), rawResponse, new Date());
throw asServiceException(e);
}
}
@ -323,42 +331,118 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
requireArray(root, "recommendedActions");
}
private int validateAssessment(String report) {
JsonNode root = object(report);
JsonNode score = root.get("score");
if (score == null || !score.isInt() || score.intValue() < 0 || score.intValue() > 100) {
private int validateAssessment(JsonNode root, List<AssessmentCriterionPlan> criterionPlan) {
Integer score = wholeNumber(root.get("score"));
if (score == null || score < 0 || score > 100) {
throw invalidReport();
}
JsonNode criteria = root.get("criteria");
if (criteria == null || !criteria.isArray() || criteria.size() < 3 || criteria.size() > 5) {
if (criteria == null || !criteria.isArray() || criteria.size() != criterionPlan.size()) {
throw invalidReport();
}
int maxTotal = 0;
int earnedTotal = 0;
for (JsonNode criterion : criteria) {
for (int index = 0; index < criteria.size(); index++) {
JsonNode criterion = criteria.get(index);
AssessmentCriterionPlan expected = criterionPlan.get(index);
if (!criterion.isObject()) {
throw invalidReport();
}
requireText(criterion, "name");
requireText(criterion, "rationale");
JsonNode max = criterion.get("maxScore");
JsonNode earned = criterion.get("score");
if (max == null || earned == null || !max.isInt() || !earned.isInt()
|| max.intValue() < 0 || earned.intValue() < 0 || earned.intValue() > max.intValue()) {
Integer max = wholeNumber(criterion.get("maxScore"));
Integer earned = wholeNumber(criterion.get("score"));
if (!expected.name.equals(StringUtils.trimToEmpty(criterion.path("name").asText()))
|| max == null || earned == null || max != expected.maxScore || earned < 0 || earned > max) {
throw invalidReport();
}
maxTotal += max.intValue();
earnedTotal += earned.intValue();
maxTotal += max;
earnedTotal += earned;
}
if (maxTotal != 100 || earnedTotal != score.intValue()) {
if (maxTotal != 100 || earnedTotal != score) {
throw invalidReport();
}
return score.intValue();
return score;
}
private List<AssessmentCriterionPlan> assessmentCriterionPlan(String steps) {
List<String> names = stepNames(steps);
if (names.isEmpty() || names.size() > 100) {
throw new ServiceException(HttpStatus.BAD_REQUEST, "Training task steps are invalid for AI assessment");
}
int baseScore = 100 / names.size();
int remainder = 100 % names.size();
List<AssessmentCriterionPlan> result = new ArrayList<>();
for (int index = 0; index < names.size(); index++) {
result.add(new AssessmentCriterionPlan(names.get(index), baseScore + (index < remainder ? 1 : 0)));
}
return result;
}
private List<String> stepNames(String steps) {
List<String> result = new ArrayList<>();
String source = StringUtils.trimToEmpty(steps);
if (StringUtils.isBlank(source)) return result;
try {
JsonNode values = objectMapper.readTree(source);
if (values != null && values.isArray()) {
for (JsonNode value : values) {
String name = value.isTextual() ? value.asText() : value.path("name").asText();
if (StringUtils.isNotBlank(name)) result.add(name.trim());
}
return result;
}
} catch (JsonProcessingException ignored) {
// Fall through to support legacy delimiter-separated task steps.
}
for (String value : source.split("[;;,,\\r\\n]+")) {
if (StringUtils.isNotBlank(value)) result.add(value.trim());
}
return result;
}
private void compactAssessmentRationales(JsonNode report) {
JsonNode criteria = report.path("criteria");
int remainingCharacters = MAX_ASSESSMENT_RATIONALE_CHARACTERS;
for (int index = 0; index < criteria.size(); index++) {
JsonNode criterion = criteria.get(index);
int remainingCriteria = criteria.size() - index;
int limit = remainingCriteria == 0 ? 0 : remainingCharacters / remainingCriteria;
String rationale = criterion.path("rationale").asText("");
String compacted = truncateRationaleAtSentenceBoundary(rationale, limit);
((ObjectNode) criterion).put("rationale", compacted);
remainingCharacters -= compacted.codePointCount(0, compacted.length());
}
}
private String truncateRationaleAtSentenceBoundary(String value, int maxCharacters) {
String normalized = StringUtils.trimToEmpty(value);
if (maxCharacters <= 0 || normalized.isEmpty()) return "";
int characterCount = normalized.codePointCount(0, normalized.length());
if (characterCount <= maxCharacters) return normalized;
int cutoff = normalized.offsetByCodePoints(0, maxCharacters);
String prefix = normalized.substring(0, cutoff);
int sentenceEnd = Math.max(Math.max(prefix.lastIndexOf('。'), prefix.lastIndexOf('!')),
Math.max(prefix.lastIndexOf('?'), prefix.lastIndexOf(';')));
if (sentenceEnd >= 0) return prefix.substring(0, sentenceEnd + 1).trim();
if (maxCharacters == 1) return "…";
int shortenedEnd = normalized.offsetByCodePoints(0, maxCharacters - 1);
return normalized.substring(0, shortenedEnd).trim() + "…";
}
private JsonNode object(String report) {
try {
JsonNode root = objectMapper.readTree(report);
String normalized = StringUtils.trimToEmpty(report);
if (normalized.startsWith("```")) {
int firstLineEnd = normalized.indexOf('\n');
normalized = firstLineEnd < 0 ? "" : normalized.substring(firstLineEnd + 1);
int closingFence = normalized.lastIndexOf("```");
if (closingFence >= 0) normalized = normalized.substring(0, closingFence);
}
int firstBrace = normalized.indexOf('{');
int lastBrace = normalized.lastIndexOf('}');
if (firstBrace < 0 || lastBrace < firstBrace) throw invalidReport();
JsonNode root = objectMapper.readTree(normalized.substring(firstBrace, lastBrace + 1));
if (root == null || !root.isObject()) {
throw invalidReport();
}
@ -368,6 +452,19 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
}
}
private Integer wholeNumber(JsonNode value) {
if (value == null || value.isNull()) return null;
try {
BigDecimal decimal = value.isNumber()
? value.decimalValue()
: value.isTextual() ? new BigDecimal(value.textValue().trim()) : null;
if (decimal == null || decimal.stripTrailingZeros().scale() > 0) return null;
return decimal.intValueExact();
} catch (NumberFormatException | ArithmeticException e) {
return null;
}
}
private void requireText(JsonNode node, String field) {
JsonNode value = node.get(field);
if (value == null || !value.isTextual() || StringUtils.isBlank(value.textValue())) {
@ -395,13 +492,34 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
+ "\nResolved case material and this student's uploaded-file excerpts: " + knowledgeContext;
}
private String assessmentSystemPrompt() {
return "You are a training assessor. Return only JSON with score, overallComment, criteria, strengths, and improvements. Create 3 to 5 criteria; all maxScore values total 100, all criterion score values total 100, and the integer score equals that total.";
private String assessmentSystemPrompt(List<AssessmentCriterionPlan> criterionPlan) {
return "You are a training assessor. Return exactly one JSON object, with no Markdown fence or other text. "
+ "Use this schema: {\"score\":86,\"overallComment\":\"summary\",\"criteria\":[{\"name\":\"步骤名称\",\"maxScore\":25,\"score\":22,\"rationale\":\"reason\"}],\"strengths\":[\"item\"],\"improvements\":[\"item\"]}. "
+ "There are exactly " + criterionPlan.size() + " training steps and the total score is exactly 100. "
+ "Return exactly " + criterionPlan.size() + " criteria in this exact order. Each name and maxScore must exactly match this required step plan: "
+ criterionPlanPrompt(criterionPlan) + ". "
+ "score, maxScore, and each criterion score must be JSON integer numbers (not strings). "
+ "Write one complete concise Chinese sentence for each rationale and end it with Chinese punctuation. "
+ "The combined text length of all criteria.rationale values must not exceed 200 Chinese characters; target no more than "
+ (MAX_ASSESSMENT_RATIONALE_CHARACTERS / criterionPlan.size()) + " Chinese characters per rationale; do not repeat the student's table data. "
+ "All criterion score values must total exactly score, and score must be from 0 to 100.";
}
private String criterionPlanPrompt(List<AssessmentCriterionPlan> criterionPlan) {
StringBuilder result = new StringBuilder("[");
for (int index = 0; index < criterionPlan.size(); index++) {
AssessmentCriterionPlan item = criterionPlan.get(index);
if (index > 0) result.append(", ");
result.append(index + 1).append(". ").append(item.name).append(" (max ").append(item.maxScore).append(")");
}
return result.append("]").toString();
}
private String assessmentUserPrompt(String taskSnapshot, String answerSnapshot, String knowledgeContext) {
return "Task snapshot: " + taskSnapshot + "\nStudent answer snapshot: " + answerSnapshot
+ "\nResolved case material and this student's uploaded-file excerpts: " + knowledgeContext;
+ "\nResolved case material and this student's uploaded-file excerpts: " + knowledgeContext
+ "\nIf the answer snapshot contains a server-generated calculationCheck object, treat it as verified calculation evidence. "
+ "When calculationCorrect is false, deduct points for the reported incorrectItemCount rather than treating the calculation as correct.";
}
private AiTrainingEvaluationView toView(AiTrainingEvaluation evaluation) {
@ -430,6 +548,16 @@ public class AiTrainingEvaluationServiceImpl implements AiTrainingEvaluationServ
return new ServiceException(HttpStatus.BAD_GATEWAY, "AI evaluation failed");
}
private static class AssessmentCriterionPlan {
private final String name;
private final int maxScore;
private AssessmentCriterionPlan(String name, int maxScore) {
this.name = name;
this.maxScore = maxScore;
}
}
private static class EvaluationContext {
private final TrainingTask task;
private final String teachingClassId;

@ -47,11 +47,17 @@ public class ReleaseChannelEvaluationStepThreeServiceImpl implements ReleaseChan
public ReleaseChannelEvaluationStepThreeValidationResult validate(ReleaseChannelEvaluationStepThreeValidationRequest request, JwtUser user) {
requireStudent(user);
Context context = loadContext(user);
validateRows(request == null ? null : request.getRows(), context);
CalculationCheck calculationCheck = validateRows(request == null ? null : request.getRows(), context);
ReleaseChannelEvaluationStepThreeValidationResult result = new ReleaseChannelEvaluationStepThreeValidationResult();
result.setValid(true);
result.setMessage("归一化得分与加权得分校验通过");
result.setCalculationCorrect(calculationCheck.isCorrect());
result.setTotalItemCount(calculationCheck.getTotalItemCount());
result.setIncorrectItemCount(calculationCheck.getIncorrectItems().size());
result.setIncorrectItems(calculationCheck.getIncorrectItems());
result.setMessage(calculationCheck.isCorrect()
? "计算结果已校验正确,可进入下一步"
: "已保存并进入下一步。系统发现" + calculationCheck.getIncorrectItems().size() + "项计算结果与参考值不一致,AI助评时将据此扣分。");
result.setRowCount(context.channelRows.size());
return result;
}
@ -96,7 +102,7 @@ public class ReleaseChannelEvaluationStepThreeServiceImpl implements ReleaseChan
}
}
private void validateRows(List<ReleaseChannelEvaluationStepThreeValidationRequest.Row> rows, Context context) {
private CalculationCheck validateRows(List<ReleaseChannelEvaluationStepThreeValidationRequest.Row> rows, Context context) {
if (rows == null || rows.size() != context.channelRows.size()) throw badRequest("第三步必须填写第二步中的全部渠道");
Map<String, ReleaseChannelEvaluationStepThreeValidationRequest.Row> submitted = new LinkedHashMap<>();
for (ReleaseChannelEvaluationStepThreeValidationRequest.Row row : rows) {
@ -104,16 +110,19 @@ public class ReleaseChannelEvaluationStepThreeServiceImpl implements ReleaseChan
if (StringUtils.isBlank(channel) || submitted.put(channel, row) != null) throw badRequest("渠道名称不能为空且不能重复");
}
CalculationCheck calculationCheck = new CalculationCheck();
for (int index = 0; index < context.channelRows.size(); index++) {
JSONObject source = context.channelRows.getJSONObject(index);
String channel = StringUtils.trimToEmpty(source.getString("channel"));
ReleaseChannelEvaluationStepThreeValidationRequest.Row submittedRow = submitted.get(channel);
if (submittedRow == null) throw badRequest("第" + (index + 1) + "行渠道必须为“" + channel + "”");
validateChannelScores(submittedRow, source, context);
validateChannelScores(submittedRow, source, context, calculationCheck);
}
return calculationCheck;
}
private void validateChannelScores(ReleaseChannelEvaluationStepThreeValidationRequest.Row submittedRow, JSONObject source, Context context) {
private void validateChannelScores(ReleaseChannelEvaluationStepThreeValidationRequest.Row submittedRow, JSONObject source, Context context,
CalculationCheck calculationCheck) {
List<ReleaseChannelEvaluationStepThreeValidationRequest.Dimension> dimensions = submittedRow.getDimensions();
if (dimensions == null || dimensions.size() != METRICS.size()) throw badRequest("“" + submittedRow.getChannel() + "”的七项维度得分必须填写完整");
Map<String, ReleaseChannelEvaluationStepThreeValidationRequest.Dimension> submittedDimensions = new LinkedHashMap<>();
@ -131,14 +140,16 @@ public class ReleaseChannelEvaluationStepThreeServiceImpl implements ReleaseChan
throw badRequest("“" + metric.dimension + "”权重必须与第一步一致");
}
BigDecimal expectedScore = normalizedScore(source, metric, context.channelRows);
calculationCheck.incrementTotalItemCount();
if (!matchesOneDecimal(submitted.getScore(), expectedScore)) {
throw badRequest("“" + submittedRow.getChannel() + "”的“" + metric.dimension + "”得分不正确");
calculationCheck.addIncorrectItem("“" + submittedRow.getChannel() + "”的“" + metric.dimension + "”得分");
}
expectedWeightedScore = expectedWeightedScore.add(expectedScore.multiply(weight).divide(ONE_HUNDRED, 4, RoundingMode.HALF_UP));
}
expectedWeightedScore = expectedWeightedScore.setScale(2, RoundingMode.HALF_UP);
calculationCheck.incrementTotalItemCount();
if (!matchesTwoDecimals(submittedRow.getWeightedScore(), expectedWeightedScore)) {
throw badRequest("“" + submittedRow.getChannel() + "”的加权得分不正确");
calculationCheck.addIncorrectItem("“" + submittedRow.getChannel() + "”的加权得分");
}
}
@ -178,4 +189,13 @@ public class ReleaseChannelEvaluationStepThreeServiceImpl implements ReleaseChan
private final JSONArray channelRows;
private Context(Map<String, BigDecimal> weights, JSONArray channelRows) { this.weights = weights; this.channelRows = channelRows; }
}
private static class CalculationCheck {
private int totalItemCount;
private final List<String> incorrectItems = new java.util.ArrayList<>();
private void incrementTotalItemCount() { totalItemCount++; }
private void addIncorrectItem(String item) { incorrectItems.add(item); }
private int getTotalItemCount() { return totalItemCount; }
private List<String> getIncorrectItems() { return incorrectItems; }
private boolean isCorrect() { return incorrectItems.isEmpty(); }
}
}

@ -31,8 +31,8 @@ public class ReleaseChannelEvaluationStepTwoServiceImpl implements ReleaseChanne
if (!isNonNegative(row.getAverageCpc())) throw rowError(index, "平均CPC必须为非负数");
if (!isPercentage(row.getAverageConversionRate())) throw rowError(index, "平均转化率必须在0到100之间");
if (!isNonNegative(row.getExistingVisitorCount())) throw rowError(index, "现有相关访客数必须为非负数");
if (row.getMatchingScore() == null || row.getMatchingScore() < 1 || row.getMatchingScore() > 5) {
throw rowError(index, "匹配度必须为1到5的整数");
if (row.getMatchingScore() == null || row.getMatchingScore() < 1 || row.getMatchingScore() > 100) {
throw rowError(index, "匹配度必须为1到100的整数");
}
}

@ -110,6 +110,7 @@
<update id="failAssessment">
UPDATE ai_training_evaluation
SET assessment_status = 'FAILED', assessment_error_message = #{errorMessage,jdbcType=VARCHAR},
assessment_raw_response = #{rawResponse,jdbcType=LONGVARCHAR},
update_time = #{updateTime,jdbcType=TIMESTAMP}
WHERE id = #{id,jdbcType=VARCHAR} AND assessment_status = 'PROCESSING'
</update>

@ -12,6 +12,7 @@ import com.sztzjy.linkCommerce.mapper.TeachingClassStudentMapper;
import com.sztzjy.linkCommerce.mapper.TrainingTaskMapper;
import com.sztzjy.linkCommerce.config.exception.handler.ServiceException;
import com.sztzjy.linkCommerce.config.security.JwtUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.PlatformTransactionManager;
@ -127,6 +128,32 @@ class AiTrainingEvaluationServiceImplTest {
verify(service.studentTrainingAnswerMapper).updateAiAssessmentScore(eq("answer-1"), eq(86), any(Date.class));
}
@Test
void assessmentAcceptsJsonFenceAndWholeNumberStrings() {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
String fencedResponse = "```json\n" + assessmentJson()
.replace("\"score\":86", "\"score\":\"86\"")
.replace("\"maxScore\":25", "\"maxScore\":\"25\"")
.replace("\"score\":22", "\"score\":\"22\"")
.replace("\"score\":21", "\"score\":\"21\"") + "\n```";
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(fencedResponse);
when(service.aiTrainingEvaluationMapper.completeAssessment(any(AiTrainingEvaluation.class))).thenReturn(1);
when(service.studentTrainingAnswerMapper.updateAiAssessmentScore(eq("answer-1"), eq(86), any(Date.class))).thenReturn(1);
AiTrainingEvaluationView view = service.generateAssessment("new-product-survey", student());
ArgumentCaptor<AiTrainingEvaluation> saved = ArgumentCaptor.forClass(AiTrainingEvaluation.class);
verify(service.aiTrainingEvaluationMapper).completeAssessment(saved.capture());
assertEquals(Integer.valueOf(86), view.getAssessmentScore());
assertEquals(fencedResponse, saved.getValue().getAssessmentRawResponse());
assertTrue(saved.getValue().getAssessmentReportJson().startsWith("{"));
assertTrue(!saved.getValue().getAssessmentReportJson().contains("```"));
}
@Test
void assessmentScoreWriteFailureRollsBackCompletionAndLeavesEvaluationRetryable() throws Exception {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
@ -149,7 +176,7 @@ class AiTrainingEvaluationServiceImplTest {
});
when(service.studentTrainingAnswerMapper.updateAiAssessmentScore(eq("answer-1"), eq(86), any(Date.class)))
.thenThrow(new IllegalStateException("score write failed"));
when(service.aiTrainingEvaluationMapper.failAssessment(eq("evaluation-1"), any(), any(Date.class))).thenAnswer(invocation -> {
when(service.aiTrainingEvaluationMapper.failAssessment(eq("evaluation-1"), any(), any(), any(Date.class))).thenAnswer(invocation -> {
if ("PROCESSING".equals(evaluation.getAssessmentStatus())) {
evaluation.setAssessmentStatus("FAILED");
return 1;
@ -175,10 +202,116 @@ class AiTrainingEvaluationServiceImplTest {
assertThrows(ServiceException.class, () -> service.generateAssessment("new-product-survey", student()));
verify(service.aiTrainingEvaluationMapper).failAssessment(eq("evaluation-1"), any(), any(Date.class));
verify(service.aiTrainingEvaluationMapper).failAssessment(eq("evaluation-1"), any(), any(), any(Date.class));
verify(service.studentTrainingAnswerMapper, never()).updateAiAssessmentScore(any(), any(), any());
}
@Test
void invalidAssessmentKeepsRawModelResponseForDiagnosis() {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
String invalidResponse = assessmentJson().replace("\"maxScore\":25", "\"maxScore\":24");
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(invalidResponse);
assertThrows(ServiceException.class, () -> service.generateAssessment("new-product-survey", student()));
verify(service.aiTrainingEvaluationMapper).failAssessment(eq("evaluation-1"), any(), eq(invalidResponse), any(Date.class));
}
@Test
void assessmentUsesEachOfFiveConfiguredStepsWithAMaximumOfTwentyPoints() {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
TrainingTask task = task();
task.setSteps("[{\"name\":\"步骤一\"},{\"name\":\"步骤二\"},{\"name\":\"步骤三\"},{\"name\":\"步骤四\"},{\"name\":\"步骤五\"}]");
when(service.trainingTaskMapper.selectByTaskKey("new-product-survey")).thenReturn(task);
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(fiveStepAssessmentJson());
when(service.aiTrainingEvaluationMapper.completeAssessment(any(AiTrainingEvaluation.class))).thenReturn(1);
when(service.studentTrainingAnswerMapper.updateAiAssessmentScore(eq("answer-1"), eq(90), any(Date.class))).thenReturn(1);
AiTrainingEvaluationView view = service.generateAssessment("new-product-survey", student());
ArgumentCaptor<String> systemPrompt = ArgumentCaptor.forClass(String.class);
verify(service.qwenChatClient).completeJson(systemPrompt.capture(), any());
assertEquals(Integer.valueOf(90), view.getAssessmentScore());
assertTrue(systemPrompt.getValue().contains("There are exactly 5 training steps and the total score is exactly 100"));
assertTrue(systemPrompt.getValue().contains("步骤五 (max 20)"));
}
@Test
void assessmentRejectsFiveStepCriteriaThatExceedTwentyPoints() {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
TrainingTask task = task();
task.setSteps("[\"步骤一\",\"步骤二\",\"步骤三\",\"步骤四\",\"步骤五\"]");
when(service.trainingTaskMapper.selectByTaskKey("new-product-survey")).thenReturn(task);
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(fiveStepAssessmentJson().replaceFirst("\"maxScore\":20", "\"maxScore\":21"));
assertThrows(ServiceException.class, () -> service.generateAssessment("new-product-survey", student()));
verify(service.aiTrainingEvaluationMapper).failAssessment(eq("evaluation-1"), any(), any(), any(Date.class));
}
@Test
void assessmentLimitsAllStepRationalesToTwoHundredCharacters() throws Exception {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
String longRationale = "评分依据".repeat(80);
String response = assessmentJson()
.replace("evidence", longRationale)
.replace("logic", longRationale)
.replace("clarity", longRationale)
.replace("coverage", longRationale);
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(response);
when(service.aiTrainingEvaluationMapper.completeAssessment(any(AiTrainingEvaluation.class))).thenReturn(1);
when(service.studentTrainingAnswerMapper.updateAiAssessmentScore(eq("answer-1"), eq(86), any(Date.class))).thenReturn(1);
service.generateAssessment("new-product-survey", student());
ArgumentCaptor<AiTrainingEvaluation> saved = ArgumentCaptor.forClass(AiTrainingEvaluation.class);
verify(service.aiTrainingEvaluationMapper).completeAssessment(saved.capture());
int totalCharacters = 0;
for (com.fasterxml.jackson.databind.JsonNode criterion : new ObjectMapper()
.readTree(saved.getValue().getAssessmentReportJson()).path("criteria")) {
String rationale = criterion.path("rationale").asText();
totalCharacters += rationale.codePointCount(0, rationale.length());
}
assertTrue(totalCharacters <= 200);
}
@Test
void assessmentTruncationUsesASentenceBoundaryWhenAvailable() throws Exception {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
AiTrainingEvaluation evaluation = evaluation("NOT_STARTED", "NOT_STARTED");
String response = assessmentJson().replace("evidence", "第一句说明问题。第二句非常长" + "内容".repeat(80));
when(service.aiTrainingEvaluationMapper.findByStudentClassAndTask("stu-1", "class-1", "task-1"))
.thenReturn(null, evaluation);
when(service.aiTrainingEvaluationMapper.claimAssessment(eq("evaluation-1"), any(Date.class))).thenReturn(1);
when(service.qwenChatClient.completeJson(any(), any())).thenReturn(response);
when(service.aiTrainingEvaluationMapper.completeAssessment(any(AiTrainingEvaluation.class))).thenReturn(1);
when(service.studentTrainingAnswerMapper.updateAiAssessmentScore(eq("answer-1"), eq(86), any(Date.class))).thenReturn(1);
service.generateAssessment("new-product-survey", student());
ArgumentCaptor<AiTrainingEvaluation> saved = ArgumentCaptor.forClass(AiTrainingEvaluation.class);
verify(service.aiTrainingEvaluationMapper).completeAssessment(saved.capture());
String rationale = new ObjectMapper().readTree(saved.getValue().getAssessmentReportJson())
.path("criteria").get(0).path("rationale").asText();
assertEquals("第一句说明问题。", rationale);
}
@Test
void succeededHelpCanBeRegeneratedForANewQuestion() {
AiTrainingEvaluationServiceImpl service = serviceWithContext(answer("answer-1", "step one", null, null, null));
@ -289,7 +422,7 @@ class AiTrainingEvaluationServiceImplTest {
assertNotNull(AiTrainingEvaluationMapper.class.getDeclaredMethod("completeHelp", AiTrainingEvaluation.class));
assertNotNull(AiTrainingEvaluationMapper.class.getDeclaredMethod("completeAssessment", AiTrainingEvaluation.class));
assertNotNull(AiTrainingEvaluationMapper.class.getDeclaredMethod("failHelp", String.class, String.class, Date.class));
assertNotNull(AiTrainingEvaluationMapper.class.getDeclaredMethod("failAssessment", String.class, String.class, Date.class));
assertNotNull(AiTrainingEvaluationMapper.class.getDeclaredMethod("failAssessment", String.class, String.class, String.class, Date.class));
String xml = readResource("src/main/resources/mappers/AiTrainingEvaluationMapper.xml");
assertTrue(xml.contains("INSERT IGNORE INTO ai_training_evaluation"));
@ -364,6 +497,7 @@ class AiTrainingEvaluationServiceImplTest {
task.setBackground("task background");
task.setObjectives("[\"objective one\"]");
task.setRequirements("task requirement");
task.setSteps("[{\"name\":\"步骤一\"},{\"name\":\"步骤二\"},{\"name\":\"步骤三\"},{\"name\":\"步骤四\"}]");
return task;
}
@ -398,9 +532,20 @@ class AiTrainingEvaluationServiceImplTest {
private String assessmentJson() {
return "{\"score\":86,\"overallComment\":\"good\",\"criteria\":["
+ "{\"name\":\"research\",\"maxScore\":40,\"score\":34,\"rationale\":\"evidence\"},"
+ "{\"name\":\"analysis\",\"maxScore\":35,\"score\":30,\"rationale\":\"logic\"},"
+ "{\"name\":\"presentation\",\"maxScore\":25,\"score\":22,\"rationale\":\"clarity\"}],"
+ "{\"name\":\"步骤一\",\"maxScore\":25,\"score\":22,\"rationale\":\"evidence\"},"
+ "{\"name\":\"步骤二\",\"maxScore\":25,\"score\":22,\"rationale\":\"logic\"},"
+ "{\"name\":\"步骤三\",\"maxScore\":25,\"score\":21,\"rationale\":\"clarity\"},"
+ "{\"name\":\"步骤四\",\"maxScore\":25,\"score\":21,\"rationale\":\"coverage\"}],"
+ "\"strengths\":[\"clear\"],\"improvements\":[\"more data\"]}";
}
private String fiveStepAssessmentJson() {
return "{\"score\":90,\"overallComment\":\"good\",\"criteria\":["
+ "{\"name\":\"步骤一\",\"maxScore\":20,\"score\":18,\"rationale\":\"one\"},"
+ "{\"name\":\"步骤二\",\"maxScore\":20,\"score\":18,\"rationale\":\"two\"},"
+ "{\"name\":\"步骤三\",\"maxScore\":20,\"score\":18,\"rationale\":\"three\"},"
+ "{\"name\":\"步骤四\",\"maxScore\":20,\"score\":18,\"rationale\":\"four\"},"
+ "{\"name\":\"步骤五\",\"maxScore\":20,\"score\":18,\"rationale\":\"five\"}],"
+ "\"strengths\":[\"clear\"],\"improvements\":[\"more data\"]}";
}
}

@ -13,6 +13,8 @@ import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@ -27,16 +29,25 @@ class ReleaseChannelEvaluationStepThreeServiceImplTest {
ReleaseChannelEvaluationStepThreeValidationResult result = service.validate(request("天猫", "10.00"), student());
assertTrue(result.isValid());
assertTrue(result.isCalculationCorrect());
assertEquals(0, result.getIncorrectItemCount());
}
@Test
void rejectsIncorrectNormalizedScoreAndWeightedTotal() {
void reportsIncorrectNormalizedScoreAndWeightedTotalWithoutBlockingProgress() {
ReleaseChannelEvaluationStepThreeServiceImpl service = new ReleaseChannelEvaluationStepThreeServiceImpl(savedAnswers());
ReleaseChannelEvaluationStepThreeValidationRequest wrongScore = request("天猫", "10.00");
wrongScore.getRows().get(0).getDimensions().get(0).setScore(new BigDecimal("9.9"));
assertThrows(ServiceException.class, () -> service.validate(wrongScore, student()));
assertThrows(ServiceException.class, () -> service.validate(request("天猫", "9.99"), student()));
ReleaseChannelEvaluationStepThreeValidationResult scoreResult = service.validate(wrongScore, student());
ReleaseChannelEvaluationStepThreeValidationResult totalResult = service.validate(request("天猫", "9.99"), student());
assertTrue(scoreResult.isValid());
assertFalse(scoreResult.isCalculationCorrect());
assertEquals(1, scoreResult.getIncorrectItemCount());
assertTrue(totalResult.isValid());
assertFalse(totalResult.isCalculationCorrect());
assertEquals(1, totalResult.getIncorrectItemCount());
}
@Test

@ -19,7 +19,7 @@ class ReleaseChannelEvaluationStepTwoServiceImplTest {
ReleaseChannelEvaluationStepTwoServiceImpl service = new ReleaseChannelEvaluationStepTwoServiceImpl();
ReleaseChannelEvaluationStepTwoValidationResult result = service.validate(request(
row("天猫", "10000", "0.2", "3.5", "2.1", "4.2", "600", 5),
row("天猫", "10000", "0.2", "3.5", "2.1", "4.2", "600", 100),
row("京东", "8000", "0.3", "2.8", "1.8", "3.7", "480", 4)), student());
assertTrue(result.isValid());
@ -34,7 +34,7 @@ class ReleaseChannelEvaluationStepTwoServiceImplTest {
assertThrows(ServiceException.class, () -> service.validate(request(
row("天猫", "10000", "0.2", "101", "2.1", "4.2", "600", 5)), student()));
assertThrows(ServiceException.class, () -> service.validate(request(
row("天猫", "10000", "0.2", "3.5", "2.1", "4.2", "600", 6)), student()));
row("天猫", "10000", "0.2", "3.5", "2.1", "4.2", "600", 101)), student()));
}
@Test

Loading…
Cancel
Save