♻️Refactor: LLM输出JSON可用性校验 增强系统安全性
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package com.wonder.bi.manager;
|
||||
|
||||
import com.wonder.bi.constant.CommonConstant;
|
||||
import com.wonder.bi.utils.JsonUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -23,6 +24,7 @@ public class ChartAgentManager {
|
||||
.call()
|
||||
.content();
|
||||
log.info(content);
|
||||
JsonUtils.isValidJson(content);
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.wonder.bi.utils;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.wonder.bi.common.ErrorCode;
|
||||
import com.wonder.bi.exception.BusinessException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Slf4j
|
||||
public class JsonUtils {
|
||||
|
||||
public static boolean isValidJson(String input) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
mapper.readTree(input);
|
||||
return true;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new BusinessException(ErrorCode.OPERATION_ERROR, "LLM JSON 输出错误,请重试");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.wonder.bi.utils;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class JsonUtilsTest {
|
||||
|
||||
@Test
|
||||
void isValidJson() {
|
||||
boolean validJson = JsonUtils.isValidJson("{\"name\": \"John\", \"age\": 30, \"isStudent\": false}");
|
||||
assertTrue(validJson);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user