73 lines
2.6 KiB
Java
73 lines
2.6 KiB
Java
package com.superbiz.agent.service;
|
|
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.util.LinkedHashMap;
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* 统一维护 diagnosis_session.self_evaluation JSON 容器。
|
|
*/
|
|
@Slf4j
|
|
@Service
|
|
public class SelfEvaluationMergeService {
|
|
|
|
private static final TypeReference<LinkedHashMap<String, Object>> MAP_TYPE = new TypeReference<>() {};
|
|
|
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
public String mergeRuleEvaluation(String existingJson, Map<String, Object> ruleEvaluation) {
|
|
return merge(existingJson, "rule_evaluation", ruleEvaluation);
|
|
}
|
|
|
|
public String mergeVerifierEvaluation(String existingJson, Map<String, Object> verifierEvaluation) {
|
|
return merge(existingJson, "verifier_evaluation", verifierEvaluation);
|
|
}
|
|
|
|
private String merge(String existingJson, String key, Map<String, Object> value) {
|
|
try {
|
|
Map<String, Object> root = parseRoot(existingJson);
|
|
root.put(key, value);
|
|
return objectMapper.writeValueAsString(root);
|
|
} catch (Exception e) {
|
|
log.error("合并 self_evaluation 失败: key={}", key, e);
|
|
return fallbackJson(key, value);
|
|
}
|
|
}
|
|
|
|
private Map<String, Object> parseRoot(String existingJson) throws Exception {
|
|
if (existingJson == null || existingJson.isBlank()) {
|
|
return new LinkedHashMap<>();
|
|
}
|
|
|
|
Map<String, Object> parsed = objectMapper.readValue(existingJson, MAP_TYPE);
|
|
if (parsed.containsKey("rule_evaluation")
|
|
|| parsed.containsKey("verifier_evaluation")) {
|
|
return new LinkedHashMap<>(parsed);
|
|
}
|
|
|
|
LinkedHashMap<String, Object> wrapped = new LinkedHashMap<>();
|
|
if (parsed.containsKey("evidence_score") || parsed.containsKey("source") || parsed.containsKey("factors")) {
|
|
wrapped.put("rule_evaluation", parsed);
|
|
return wrapped;
|
|
}
|
|
if (parsed.containsKey("verdict") || parsed.containsKey("groundedness_score") || parsed.containsKey("facts_checked")) {
|
|
wrapped.put("verifier_evaluation", parsed);
|
|
return wrapped;
|
|
}
|
|
return new LinkedHashMap<>(parsed);
|
|
}
|
|
|
|
private String fallbackJson(String key, Map<String, Object> value) {
|
|
try {
|
|
return objectMapper.writeValueAsString(Map.of(key, value));
|
|
} catch (Exception ex) {
|
|
log.error("兜底序列化 self_evaluation 失败", ex);
|
|
return "{}";
|
|
}
|
|
}
|
|
}
|