ssw-common: BS-新30 v0.14+ AI 修复层 (dacli form create --ai fallback)
背景: jnpf-common-ai/SendAiMessage.java:148 硬编码 maxTokens=1500,
不对 LLM 输出做 format 修复. LLM 输出经常不规范:
- fieldOptions: ["男","女"] 字符串数组 (期望 List<{id, fullName}>)
- 含 // 注释行 (fastjson 1.2.83 不支持, 抛 "not match : -")
- 输出截断缺闭合 } 或 ]
- 偶尔输出纯文字说明 (无 JSON)
- 输出字段名用 SQL 关键字 (name/status) 触发 BS-新3 SYS128
CLAUDE.md §14 规定 jnpf 源码不能改, 所以加 ssw-common 拦截层:
ssw-common-biz 新增:
- util/JsonRepairUtil: stripMarkdownFence + extractJsonArray + stripJsonComments
+ tryCloseTruncatedJson + fixFieldOptionsStrings
- util/SswLLMClient: 从 base_ai 表读 default AI 配置 + 直调 MiniMax OpenAI 兼容 API
(maxTokens=3000, 可注入)
- service/AIRepairService: 入口接口
- service/impl/AIRepairServiceImpl: 调 LLMClient 拿原始 → JsonRepairUtil 修复
→ 构造 VisualAiModel 兼容结构 + fixFieldKeywords 修复 SQL 关键字
(name → nameX, status → statusX 等, 镜像 jnpf GenerateConstant.containKeyword)
ssw-common-controller 新增:
- SswAIRepairController: POST /api/ssw/ai/repair 暴露给 dacli fallback
集成: dacli form create --ai 失败时 (后端错/空 data) 自动调 SSW 修复,
完全不动 jnpf 源码. CLAUDE.md §3.6 兼容 (ssw-common 是合规扩展点).
测试: 26 字段用户管理表 --ai prompt, jnpf 后端返回空 → SSW fallback 修复
→ 26 字段全部生成 + fieldOptions 自动转换 → form 创建+发布成功
(id=842169175051863237).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
This commit is contained in:
1 parent
fb0069179d
commit
038bd981fc
5 files changed
+609
No files matched your search
@@ -0,0 +1,28 @@
|
||||
package ssw.common.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 修复服务接口
|
||||
*
|
||||
* 当 jnpf 后端 /api/visualdev/ai/form 返回空 data (enCode/fullName/aiModelList 都空) 时,
|
||||
* dacli 端 fallback 调此服务, 自己调 LLM + 修复 JSON + 返回 VisualAiModel 兼容结构.
|
||||
*
|
||||
* @author claude (2026-07-02)
|
||||
*/
|
||||
public interface AIRepairService {
|
||||
|
||||
/**
|
||||
* AI 修复入口
|
||||
*
|
||||
* @param keyword 用户 --ai 描述
|
||||
* @return VisualAiModel 兼容结构: {enCode, fullName, aiModelList: [{tableTitle, tableName, fields: [...]}]}
|
||||
* 如果修复失败返回空 Map (调用方走原错误处理)
|
||||
*/
|
||||
Map<String, Object> repair(String keyword);
|
||||
|
||||
/**
|
||||
* 调 jnpf 后端拿 GEN_MODEL_QUETION (与 jnpf 保持一致 prompt)
|
||||
*/
|
||||
String getGenModelQuestion();
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package ssw.common.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.google.common.base.CaseFormat;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ssw.common.service.AIRepairService;
|
||||
import ssw.common.util.JsonRepairUtil;
|
||||
import ssw.common.util.SswLLMClient;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AI 修复服务实现 (ssw-common 拦截层核心)
|
||||
*
|
||||
* 流程:
|
||||
* 1. 从 jnpf AiConstants 拿 GEN_MODEL_QUETION (与 jnpf 后端保持一致 prompt)
|
||||
* 2. SswLLMClient.chat() 调 LLM API (绕开 jnpf SendAiMessage)
|
||||
* 3. JsonRepairUtil.repair() 修复 LLM 输出 (fieldOptions/注释/截断)
|
||||
* 4. 解析 List<Map> → 构造 VisualAiModel 兼容结构
|
||||
*
|
||||
* @author claude (2026-07-02)
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AIRepairServiceImpl implements AIRepairService {
|
||||
|
||||
@Autowired
|
||||
private SswLLMClient llmClient;
|
||||
|
||||
@Override
|
||||
public Map<String, Object> repair(String keyword) {
|
||||
log.info("[AIRepair] keyword: {}", keyword);
|
||||
|
||||
// 1. 拿 jnpf 的 GEN_MODEL_QUETION (通过反射读 AiConstants.GEN_MODEL_QUETION)
|
||||
String systemPrompt = getGenModelQuestion();
|
||||
|
||||
// 2. 调 LLM
|
||||
String raw = llmClient.chat(systemPrompt, "当前业务需求是:" + keyword);
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
log.warn("[AIRepair] LLM 返回空");
|
||||
return new HashMap<>();
|
||||
}
|
||||
log.info("[AIRepair] LLM 返回 {} 字符", raw.length());
|
||||
|
||||
// 3. 修复 JSON
|
||||
String repaired = JsonRepairUtil.repair(raw);
|
||||
log.info("[AIRepair] 修复前 LLM 返回 {} 字符: {}", raw.length(), raw.substring(0, Math.min(300, raw.length())));
|
||||
log.info("[AIRepair] 修复后 JSON {} 字符: {}", repaired.length(), repaired.substring(0, Math.min(300, repaired.length())));
|
||||
|
||||
// 4. 解析 List<Map>
|
||||
List<Map<String, Object>> tables = JsonRepairUtil.parseToTableList(repaired);
|
||||
if (tables.isEmpty()) {
|
||||
log.warn("[AIRepair] 解析后空表");
|
||||
return new HashMap<>();
|
||||
}
|
||||
|
||||
// 5. 构造 VisualAiModel 兼容结构 (jnpf 期望的格式)
|
||||
return buildVisualAiModel(tables);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 jnpf VisualAiModel 兼容响应:
|
||||
* {enCode: "userManagement", fullName: "用户管理表",
|
||||
* aiModelList: [{tableTitle, tableName, isMain: true, fields: [...]}]}
|
||||
*
|
||||
* 同时修复 LLM 输出的字段名关键字问题 (name/status/type 等 SQL/Java 关键字)
|
||||
* 参考 jnpf GenerateConstant.containKeyword() 规则
|
||||
*/
|
||||
private Map<String, Object> buildVisualAiModel(List<Map<String, Object>> tables) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
List<Map<String, Object>> aiModelList = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < tables.size(); i++) {
|
||||
Map<String, Object> table = tables.get(i);
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
String tableTitle = (String) table.getOrDefault("tableTitle", "未命名表");
|
||||
String tableName = (String) table.getOrDefault("tableName", "unnamed");
|
||||
|
||||
// 字段名关键字修复 (避免 LLM 输出 name/status/type 等 SQL 关键字触发 SYS128)
|
||||
List<Map<String, Object>> fixedFields = fixFieldKeywords((List<Map<String, Object>>) table.getOrDefault("fields", new ArrayList<>()));
|
||||
|
||||
model.put("tableTitle", tableTitle);
|
||||
model.put("tableName", tableName);
|
||||
model.put("isMain", i == 0);
|
||||
model.put("fields", fixedFields);
|
||||
|
||||
aiModelList.add(model);
|
||||
|
||||
// 第一个表的 enCode/fullName 用于顶层
|
||||
if (i == 0) {
|
||||
// LLM 返回 tableName 是 snake_case (online_order_form), 转 camelCase
|
||||
String enCode = toCamelCase(tableName);
|
||||
// enCode 也修复关键字
|
||||
if (isKeyword(enCode)) enCode = enCode + "X";
|
||||
result.put("enCode", enCode);
|
||||
result.put("fullName", tableTitle);
|
||||
}
|
||||
}
|
||||
result.put("aiModelList", aiModelList);
|
||||
log.info("[AIRepair] 构建 VisualAiModel: enCode={}, tables={}",
|
||||
result.get("enCode"), aiModelList.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段名关键字修复:
|
||||
* LLM 经常输出 name/status/type/count 等通用词, 触犯 SQL/Java 关键字规则.
|
||||
* 这里检测到关键字就在末尾加 'X' 后缀.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<Map<String, Object>> fixFieldKeywords(List<Map<String, Object>> fields) {
|
||||
if (fields == null) return new ArrayList<>();
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
for (Map<String, Object> f : fields) {
|
||||
Map<String, Object> nf = new HashMap<>(f);
|
||||
String fieldName = (String) nf.get("fieldName");
|
||||
if (fieldName != null && isKeyword(fieldName)) {
|
||||
log.warn("[AIRepair] 字段名 '{}' 是关键字, 自动重命名为 '{}'", fieldName, fieldName + "X");
|
||||
nf.put("fieldName", fieldName + "X");
|
||||
}
|
||||
result.add(nf);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 简化版关键字检查 (与 jnpf GenerateConstant.containKeyword() 行为一致)
|
||||
* 包括 SQL 关键字 (name/status/type/count 等) + Java 关键字 + sys 系列
|
||||
*/
|
||||
private static final java.util.Set<String> KEYWORDS = new java.util.HashSet<>(java.util.Arrays.asList(
|
||||
// SQL 常用
|
||||
"name", "status", "type", "count", "sum", "select", "insert", "update", "delete",
|
||||
"from", "where", "order", "group", "by", "having", "join", "left", "right", "inner",
|
||||
"table", "index", "view", "user", "password", "id", "key", "value", "data",
|
||||
"primary", "foreign", "default", "null", "not", "and", "or",
|
||||
// Java 关键字
|
||||
"class", "interface", "enum", "abstract", "static", "final", "public", "private",
|
||||
"protected", "void", "int", "long", "double", "float", "boolean", "char",
|
||||
"byte", "short", "if", "else", "for", "while", "do", "switch", "case",
|
||||
"break", "continue", "return", "new", "this", "super", "try", "catch",
|
||||
"finally", "throw", "throws", "import", "package", "extends", "implements",
|
||||
// jnpf 关键字 (BS-新3 SYS128)
|
||||
"admin", "system", "role", "menu", "module", "function", "procedure",
|
||||
"session", "token", "permission"
|
||||
));
|
||||
|
||||
private boolean isKeyword(String name) {
|
||||
return name != null && KEYWORDS.contains(name.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* snake_case → camelCase (与 jnpf CaseFormat.LOWER_UNDERSCORE.to(LOWER_CAMEL) 一致)
|
||||
*/
|
||||
private String toCamelCase(String snake) {
|
||||
if (snake == null || !snake.contains("_")) return snake;
|
||||
try {
|
||||
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, snake);
|
||||
} catch (Exception e) {
|
||||
// fallback: 简单替换
|
||||
String[] parts = snake.split("_");
|
||||
StringBuilder sb = new StringBuilder(parts[0]);
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
if (parts[i].isEmpty()) continue;
|
||||
sb.append(Character.toUpperCase(parts[i].charAt(0)));
|
||||
if (parts[i].length() > 1) sb.append(parts[i].substring(1));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反射读 jnpf AiConstants.GEN_MODEL_QUETION
|
||||
* 失败时用内置默认 prompt
|
||||
*/
|
||||
@Override
|
||||
public String getGenModelQuestion() {
|
||||
try {
|
||||
Class<?> cls = Class.forName("jnpf.constants.AiConstants");
|
||||
java.lang.reflect.Field f = cls.getField("GEN_MODEL_QUETION");
|
||||
String s = (String) f.get(null);
|
||||
if (s != null && !s.isEmpty()) {
|
||||
log.debug("[AIRepair] 反射读 GEN_MODEL_QUETION 成功 ({} 字符)", s.length());
|
||||
return s;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("[AIRepair] 反射读 GEN_MODEL_QUETION 失败: {}, 用内置 prompt", e.getMessage());
|
||||
}
|
||||
return FALLBACK_PROMPT;
|
||||
}
|
||||
|
||||
/** 兜底 prompt (如果 jnpf AiConstants 找不到) */
|
||||
private static final String FALLBACK_PROMPT =
|
||||
"根据当前业务需求, 设计相应的表单结构. 请仅返回 JSON 数组, 不包含其他内容. " +
|
||||
"每个表单对象包含 tableTitle, tableName, fields 数组. " +
|
||||
"fields 元素包含 fieldTitle, fieldName, fieldDbType, fieldComponent. " +
|
||||
"如果字段用 radio/select, 需要 fieldOptions 数组, 元素是 {\"id\":\"1\",\"fullName\":\"选项名\"}. " +
|
||||
"示例: [{\"tableTitle\":\"用户管理\",\"tableName\":\"user_management\",\"fields\":[" +
|
||||
"{\"fieldTitle\":\"姓名\",\"fieldName\":\"name\",\"fieldDbType\":\"varchar\",\"fieldComponent\":\"input\"}]}]. " +
|
||||
"请只返回 JSON, 不要 markdown 包裹.";
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package ssw.common.util;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* JSON 修复工具 (ssw-common AI 修复层核心)
|
||||
*
|
||||
* 背景: JNPF 平台 jnpf-common-ai/SendAiMessage.java:148 硬编码 maxTokens=1500,
|
||||
* 且不对 LLM 输出做 format 修正. LLM (尤其 abab6.5s-chat / 通义千问 / GPT) 输出
|
||||
* 经常不规范:
|
||||
* 1. fieldOptions: ["男","女"] 字符串数组 (期望 List<{id, fullName}>)
|
||||
* 2. 含 // 注释行 (fastjson 1.2.83 不支持 JSON 注释, 抛 "not match : -")
|
||||
* 3. 输出被截断, 缺闭合 } 或 ]
|
||||
* 4. 偶尔输出纯文字说明 (无 JSON)
|
||||
*
|
||||
* 本类提供 3 个修复方法, 严格不动 jnpf 源码 (CLAUDE.md §14 规定 jnpf 是只读备份).
|
||||
*
|
||||
* @author claude (2026-07-02)
|
||||
*/
|
||||
@Slf4j
|
||||
public class JsonRepairUtil {
|
||||
|
||||
/**
|
||||
* 主入口: 修复 LLM 输出的 JSON 字符串
|
||||
*
|
||||
* @param raw LLM 原始输出 (可能含 markdown ``` 包裹, // 注释, 截断, 字符串数组)
|
||||
* @return 修复后的 JSON 字符串 (符合 AiFormModel 反序列化要求)
|
||||
*/
|
||||
public static String repair(String raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return raw;
|
||||
}
|
||||
String s = stripMarkdownFence(raw);
|
||||
// LLM 经常输出 "以下是 JSON: ...[actual JSON]..."
|
||||
// 用 [ 和 ] 提取真正的 JSON 段 (与 jnpf SendAiMessage 同样的逻辑)
|
||||
s = extractJsonArray(s);
|
||||
s = stripJsonComments(s);
|
||||
s = tryCloseTruncatedJson(s);
|
||||
s = fixFieldOptionsStrings(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 LLM 输出里提取 [...] JSON 数组 (跳过前面文字说明和 markdown fence)
|
||||
*/
|
||||
static String extractJsonArray(String s) {
|
||||
int start = s.indexOf('[');
|
||||
int end = s.lastIndexOf(']');
|
||||
if (start == -1 || end == -1 || start >= end) {
|
||||
return s;
|
||||
}
|
||||
return s.substring(start, end + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析为 List<Map> 用于直接构造 AiFormModel
|
||||
*/
|
||||
public static List<Map<String, Object>> parseToTableList(String json) {
|
||||
try {
|
||||
return JSON.parseObject(json, new TypeReference<List<Map<String, Object>>>() {});
|
||||
} catch (Exception e) {
|
||||
log.warn("JsonRepairUtil.parseToTableList failed: {}", e.getMessage());
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 步骤1: 去掉 LLM 经常输出的 ```json ... ``` markdown 包裹 + 提取 JSON 段
|
||||
*
|
||||
* LLM 输出经常是 "以下是 JSON:\n```json\n[...]\n```" 或 "根据需求, ...\n```\n[...]\n```"
|
||||
* 需要找到第一个 [ 和最后一个 ] 之间的内容
|
||||
*/
|
||||
static String stripMarkdownFence(String s) {
|
||||
// 去掉开头 ```json 或 ``` (不区分大小写)
|
||||
s = s.replaceFirst("(?i)^\\s*```\\s*json\\s*", "");
|
||||
s = s.replaceFirst("(?i)^\\s*```\\s*", "");
|
||||
// 去掉结尾 ```
|
||||
s = s.replaceFirst("(?i)\\s*```\\s*$", "");
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 步骤2: 移除 LLM 加的 // 行内注释 (fastjson 1.2.83 不支持)
|
||||
* 正则: ([空白/[/{/,]) 后跟可选空白 + // + 非 , ] } \n \r 的字符
|
||||
*/
|
||||
static String stripJsonComments(String s) {
|
||||
return s.replaceAll("([\\s\\[{\\,])\\s*//[^,\\]\\}\\n\\r]*", "$1");
|
||||
}
|
||||
|
||||
/**
|
||||
* 步骤3: 尝试补全截断的 JSON (缺的闭合括号)
|
||||
* 思路: 数 { [ 的开闭数量, 在末尾补全缺的闭合符号
|
||||
*/
|
||||
static String tryCloseTruncatedJson(String s) {
|
||||
int braces = 0, brackets = 0;
|
||||
boolean inString = false;
|
||||
boolean escape = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (escape) { escape = false; continue; }
|
||||
if (c == '\\') { escape = true; continue; }
|
||||
if (c == '"') { inString = !inString; continue; }
|
||||
if (inString) continue;
|
||||
if (c == '{') braces++;
|
||||
else if (c == '}') braces--;
|
||||
else if (c == '[') brackets++;
|
||||
else if (c == ']') brackets--;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
// 如果不是字符串中, 补全闭合
|
||||
while (braces > 0) { sb.append('}'); braces--; }
|
||||
while (brackets > 0) { sb.append(']'); brackets--; }
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 步骤4: fieldOptions 字符串数组 → 对象数组
|
||||
* LLM 经常输出 "fieldOptions": ["男","女"]
|
||||
* 但 AiFormFieldOptionModel 期望 [{"id":"1","fullName":"男"}]
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static String fixFieldOptionsStrings(String json) {
|
||||
try {
|
||||
List<Map<String, Object>> tables = JSON.parseObject(json,
|
||||
new TypeReference<List<Map<String, Object>>>() {});
|
||||
if (tables == null) return json;
|
||||
|
||||
boolean changed = false;
|
||||
for (Map<String, Object> table : tables) {
|
||||
Object fieldsObj = table.get("fields");
|
||||
if (!(fieldsObj instanceof List)) continue;
|
||||
List<?> fields = (List<?>) fieldsObj;
|
||||
for (Object fObj : fields) {
|
||||
if (!(fObj instanceof Map)) continue;
|
||||
Map<String, Object> field = (Map<String, Object>) fObj;
|
||||
Object optsObj = field.get("fieldOptions");
|
||||
if (!(optsObj instanceof List)) continue;
|
||||
List<?> opts = (List<?>) optsObj;
|
||||
if (opts.isEmpty()) continue;
|
||||
Object first = opts.get(0);
|
||||
if (!(first instanceof String)) continue; // 已经是对象数组
|
||||
// 转换: ["男","女"] → [{"id":"1","fullName":"男"},{"id":"2","fullName":"女"}]
|
||||
List<Map<String, String>> converted = new ArrayList<>();
|
||||
int i = 1;
|
||||
for (Object s : opts) {
|
||||
Map<String, String> opt = new HashMap<>();
|
||||
opt.put("id", String.valueOf(i));
|
||||
opt.put("fullName", String.valueOf(s));
|
||||
converted.add(opt);
|
||||
i++;
|
||||
}
|
||||
field.put("fieldOptions", converted);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? JSON.toJSONString(tables) : json;
|
||||
} catch (Exception e) {
|
||||
return json; // 解析失败返回原 json
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package ssw.common.util;
|
||||
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* SSW LLM 客户端 (绕过 jnpf-common-ai SendAiMessage)
|
||||
*
|
||||
* 背景: jnpf SendAiMessage 是 static 方法, 硬编码 maxTokens=1500, 不读 yml,
|
||||
* 也不对 LLM 输出做 format 修复. SSW 拦截层需要直接调 LLM API.
|
||||
*
|
||||
* 数据源: 从 base_ai 表 (主库 dbLinkId=0) 读 default AI 配置 (f_baseUrl, f_credential, f_model)
|
||||
* API 协议: OpenAI 兼容 (MiniMax / 通义千问 dashscope / OpenAI 都支持)
|
||||
*
|
||||
* @author claude (2026-07-02)
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SswLLMClient {
|
||||
|
||||
private static final int CONNECT_TIMEOUT = 5;
|
||||
private static final int READ_TIMEOUT = 60;
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private int maxTokens = 3000;
|
||||
|
||||
public void setMaxTokens(int maxTokens) {
|
||||
this.maxTokens = maxTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调 LLM API (chat/completions)
|
||||
*
|
||||
* @param systemPrompt 系统提示词 (如 jnpf 的 GEN_MODEL_QUETION)
|
||||
* @param userPrompt 用户提示词 (如 "--ai" 描述)
|
||||
* @return LLM 原始输出 (content 字段)
|
||||
*/
|
||||
public String chat(String systemPrompt, String userPrompt) {
|
||||
Map<String, Object> aiConfig = loadDefaultAIConfig();
|
||||
String baseUrl = (String) aiConfig.get("baseUrl");
|
||||
String credential = (String) aiConfig.get("credential");
|
||||
String model = (String) aiConfig.get("model");
|
||||
|
||||
if (baseUrl == null || credential == null || model == null) {
|
||||
log.error("SswLLMClient: AI 配置缺失 baseUrl={}, credential={}, model={}",
|
||||
baseUrl, credential, model);
|
||||
return null;
|
||||
}
|
||||
|
||||
JSONObject body = new JSONObject();
|
||||
body.put("model", model);
|
||||
body.put("max_tokens", maxTokens);
|
||||
body.put("temperature", 0.85);
|
||||
|
||||
JSONObject sysMsg = new JSONObject();
|
||||
sysMsg.put("role", "system");
|
||||
sysMsg.put("content", systemPrompt);
|
||||
JSONObject userMsg = new JSONObject();
|
||||
userMsg.put("role", "user");
|
||||
userMsg.put("content", userPrompt);
|
||||
|
||||
JSONArray messages = new JSONArray();
|
||||
messages.add(sysMsg);
|
||||
messages.add(userMsg);
|
||||
body.put("messages", messages);
|
||||
|
||||
try {
|
||||
log.info("[SswLLMClient] POST {} model={} maxTokens={}", baseUrl, model, maxTokens);
|
||||
HttpResponse resp = HttpRequest.post(baseUrl)
|
||||
.header("Authorization", "Bearer " + credential)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body.toJSONString())
|
||||
.timeout(READ_TIMEOUT * 1000)
|
||||
.execute();
|
||||
|
||||
if (!resp.isOk()) {
|
||||
log.error("[SswLLMClient] HTTP {} body={}", resp.getStatus(), resp.body());
|
||||
return null;
|
||||
}
|
||||
|
||||
JSONObject respJson = JSON.parseObject(resp.body());
|
||||
if (respJson.containsKey("error")) {
|
||||
log.error("[SswLLMClient] LLM error: {}", respJson.getString("error"));
|
||||
return null;
|
||||
}
|
||||
|
||||
String content = respJson.getJSONArray("choices")
|
||||
.getJSONObject(0)
|
||||
.getJSONObject("message")
|
||||
.getString("content");
|
||||
|
||||
JSONObject usage = respJson.getJSONObject("usage");
|
||||
if (usage != null) {
|
||||
log.info("[SswLLMClient] usage: prompt={} completion={}/{}",
|
||||
usage.getInteger("prompt_tokens"),
|
||||
usage.getInteger("completion_tokens"), maxTokens);
|
||||
}
|
||||
|
||||
return content;
|
||||
} catch (Exception e) {
|
||||
log.error("[SswLLMClient] 调用异常: {}", e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 base_ai 表读 default AI 配置 (主库 dbLinkId=0)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> loadDefaultAIConfig() {
|
||||
try {
|
||||
String sql = "SELECT f_baseurl AS baseUrl, f_credential AS credential, f_model AS model " +
|
||||
"FROM base_ai WHERE f_enabled_mark = 1 " +
|
||||
"ORDER BY f_creator_time DESC LIMIT 1";
|
||||
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
log.error("SswLLMClient: base_ai 表没有启用记录");
|
||||
return new HashMap<>();
|
||||
}
|
||||
return rows.get(0);
|
||||
} catch (Exception e) {
|
||||
log.error("SswLLMClient: 读 base_ai 失败: {}", e.getMessage());
|
||||
return new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
/** 兼容: 不传 systemPrompt 用默认 */
|
||||
public String chat(String userPrompt) {
|
||||
return chat(DEFAULT_SYSTEM_PROMPT, userPrompt);
|
||||
}
|
||||
|
||||
private static final String DEFAULT_SYSTEM_PROMPT =
|
||||
"你是一个表单设计助手. 用户会描述业务需求, 请根据描述生成 JSON 数组格式的表单定义. " +
|
||||
"每个表单对象包含 tableTitle, tableName, fields 字段. fields 是数组, 每个元素包含 " +
|
||||
"fieldTitle (中文), fieldName (英文snake_case), fieldDbType (varchar/int/datetime 等), " +
|
||||
"fieldComponent (input/textarea/inputNumber/radio/select/switch/datePicker 等). " +
|
||||
"如果字段是 radio/select, 需要 fieldOptions 数组, 元素格式 {\"id\":\"1\",\"fullName\":\"选项名\"}. " +
|
||||
"请只返回 JSON, 不要包含其他文字或 markdown 包裹.";
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package ssw.common.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jnpf.base.ActionResult;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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 ssw.common.service.AIRepairService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* SSW AI 修复 Controller
|
||||
*
|
||||
* 用途: 当 jnpf 后端 /api/visualdev/ai/form 返回空 data 时,
|
||||
* dacli fallback 调本端点, 自己调 LLM + 修复 JSON.
|
||||
*
|
||||
* 端点: POST /api/ssw/ai/repair
|
||||
* 请求: {"keyword": "用户管理表:姓名、电话..."}
|
||||
* 响应: jnpf VisualAiModel 兼容结构 (同 /api/visualdev/ai/form 的 data 字段)
|
||||
*
|
||||
* @author claude (2026-07-02)
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/ssw/ai")
|
||||
@Tag(name = "SSW AI 修复", description = "绕过 jnpf SendAiMessage, 直接调 LLM 修复 JSON")
|
||||
public class SswAIRepairController {
|
||||
|
||||
@Autowired
|
||||
private AIRepairService aiRepairService;
|
||||
|
||||
@PostMapping("/repair")
|
||||
@Operation(summary = "AI 修复", description = "绕开 jnpf SendAiMessage, SSW 直接调 LLM 修复")
|
||||
public ActionResult<Map<String, Object>> repair(@RequestBody Map<String, Object> body) {
|
||||
String keyword = (String) body.get("keyword");
|
||||
if (keyword == null || keyword.isEmpty()) {
|
||||
return ActionResult.fail("keyword 必填");
|
||||
}
|
||||
try {
|
||||
Map<String, Object> result = aiRepairService.repair(keyword);
|
||||
if (result.isEmpty() || !result.containsKey("enCode")) {
|
||||
return ActionResult.fail("AI 修复失败, 返回空结果");
|
||||
}
|
||||
return ActionResult.success(result);
|
||||
} catch (Exception e) {
|
||||
log.error("SswAIRepairController.repair 异常", e);
|
||||
return ActionResult.fail("AI 修复异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user