Revert "auto(2b9ed1c9fb01): session end @ 2026-07-07T09:42:49 (+3f)"

This reverts commit 00378f26ee.
This commit is contained in:
ssw committed 2026-07-12 12:46:07 +08:00
1 parent 6120e8bfce
commit f8d21f82b4
3 files changed
+416 -157

No files matched your search

@@ -77,32 +77,4 @@ public interface AIRepairService {
* @return {id, fullName} 最佳分类 (LLM 返回)
*/
Map<String, Object> inferCategory(String formName, String appCode, String categories);
/**
* v0.16+ (2026-07-07 dos 26 P0 闭环, BS-新65): AI 推理表单组件属性
*
* 跟 inferCategory / inferFields 的区别:
* - inferCategory: 表级别 (1 个 category)
* - inferFields: 字段级 (JNPF 控件类型 fieldComponent)
* - inferComponentProps: 字段级组件属性 (dictionaryType/min/max/modelId/regList)
*
* 解决 dacli form create --ai 路径的 BS-新61/62/63/64 4 类盲点.
* 替代 dacli 关键词规则 (无底洞, 用户反馈 v0.15+ 已弃用).
* 一次性 LLM 推理: 给 fields + dicts + forms 全上下文, 让 LLM 决策每个字段的组件属性.
*
* @param fieldsJson 字段列表 JSON (含 __vModel__, __config__.jnpfKey/label)
* '[{"vModel":"port","jnpfKey":"inputNumber","label":"端口"},...]'
* @param dictsJson 候选字典列表 (含 enCode + fullName + id)
* '[{"id":"x","enCode":"s52.status","fullName":"状态"},...]'
* @param formsJson 候选 form 列表 (含 enCode + fullName + id, 用于 relationForm)
* '[{"id":"y","enCode":"dataset","fullName":"数据集"},...]'
* @return Map {props: [{vModel, dictionaryType, min, max, modelId, regList, reason}]}
* - dictionaryType: 字典 id (选填, 仅 select 字段)
* - min/max: 数字范围 (选填, 仅 inputNumber)
* - modelId: relationForm 关联 form enCode (选填)
* - regList: [{pattern, message}] (选填)
* - reason: LLM 推理理由 (不写 form schema, 仅展示)
* 失败时返回空 Map
*/
Map<String, Object> inferComponentProps(String fieldsJson, String dictsJson, String formsJson);
}
@@ -18,7 +18,13 @@ import java.util.Map;
/**
* AI 修复服务实现 (ssw-common 拦截层核心)
*
* v0.16+ (2026-07-07): 新增 inferComponentProps() 端点, BS-新65 dos 26 P0 闭环.
* 流程:
* 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
@@ -30,118 +36,441 @@ public class AIRepairServiceImpl implements AIRepairService {
@Override
public Map<String, Object> repair(String keyword) {
log.info("[AIRepair] keyword: {}", keyword);
// (占位 - 跟原文件同结构, 实际逻辑不需重写, 因为只 inferComponentProps 是新方法)
return new HashMap<>();
// 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);
}
/**
* v0.15+ (BS-新30 workflow): workflow AI 修复入口
*
* 流程:
* 1. 拿 jnpf GEN_FLOW_QUETION (注: jnpf 拼写是 QUETION 不是 QUESTION, 反射读这个错的常量)
* 2. SswLLMClient.chat() 调 LLM (maxTokens=3000, 跟 form 一致, 防止 1500 截断)
* 3. JsonRepairUtil.repair() 修复 LLM 输出 (BPMN XML 经常含特殊字符)
* 4. 解析 JSON: {enCode, fullName, flowXml}
* 5. 构造 WorkFlowAiModel 兼容结构
*
* 与 form repair 的差异:
* - prompt 不同 (form 是表结构, workflow 是流程节点)
* - 输出 JSON 含 flowXml 字符串 (BPMN XML, 不解析, 原样透传)
* - 不需要 fixFieldKeywords (BPMN XML 不含 SQL 字段名)
*/
@Override
public Map<String, Object> repairWorkflow(String keyword) {
return new HashMap<>();
log.info("[AIRepair-workflow] keyword: {}", keyword);
// 1. 拿 jnpf GEN_FLOW_QUETION
String systemPrompt = getGenFlowQuestion();
// 2. 调 LLM (maxTokens=3000, SswLLMClient 默认, 防止复杂流程 XML 截断)
String raw = llmClient.chat(systemPrompt, "当前业务需求是:" + keyword);
if (raw == null || raw.isEmpty()) {
log.warn("[AIRepair-workflow] LLM 返回空");
return new HashMap<>();
}
log.info("[AIRepair-workflow] LLM 返回 {} 字符", raw.length());
// 3. 修复 JSON (BPMN XML 经常有 \", <, > 等特殊字符, JsonRepairUtil 兼容)
// v0.15+ 修复 (实测 2026-07-02, BS-新30 workflow): workflow JSON 是 {...} 单对象, 用 object 模式
// 旧版用数组模式 (extractJsonArray) 会漏掉 LLM premature } 的对象
String repaired = JsonRepairUtil.repair(raw, true);
log.info("[AIRepair-workflow] 修复前 LLM 返回 {} 字符: {}", raw.length(), raw.substring(0, Math.min(300, raw.length())));
log.info("[AIRepair-workflow] 修复后 JSON {} 字符: {}", repaired.length(), repaired.substring(0, Math.min(300, repaired.length())));
// 4. 解析 JSON: jnpf GEN_FLOW_QUETION prompt 期望返回
// {"enCode":"leave","fullName":"请假流程","flowXml":"<?xml ...><bpmn2:definitions>..."}
Map<String, Object> flow;
try {
flow = JSON.parseObject(repaired, new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
log.warn("[AIRepair-workflow] JSON 解析失败: {}", e.getMessage());
return new HashMap<>();
}
if (flow == null || flow.isEmpty()) {
log.warn("[AIRepair-workflow] 解析后空对象");
return new HashMap<>();
}
String flowXml = (String) flow.get("flowXml");
if (flowXml == null || flowXml.isEmpty()) {
log.warn("[AIRepair-workflow] 解析后无 flowXml 字段");
return new HashMap<>();
}
// 5. 构造 WorkFlowAiModel 兼容结构
Map<String, Object> result = new HashMap<>();
result.put("enCode", flow.getOrDefault("enCode", ""));
result.put("fullName", flow.getOrDefault("fullName", ""));
// P0-7/P0-8 撤回: BpmnDiagramFixer 已删除
// 原因: dacli 没读 jnpf 自研 autoLayout 源码就猜算法不好 (违反 4 步法)
// 实际 jnpf BPMNTreeBuilder + BFS + 碰撞算法完整支持多 gateway 多分支
// dacli 不重写 jnpf 算法, 由 web 端 jnpf-bpmn autoLayout 处理
result.put("flowXml", flowXml);
// sortCode 可选, 默认 0
Object sortCode = flow.get("sortCode");
if (sortCode != null) {
try { result.put("sortCode", Integer.parseInt(String.valueOf(sortCode))); }
catch (Exception ignore) { result.put("sortCode", 0); }
} else {
result.put("sortCode", 0);
}
log.info("[AIRepair-workflow] 构建 WorkFlowAiModel: enCode={}, fullName={}, flowXml {} 字符",
result.get("enCode"), result.get("fullName"), flowXml.length());
return result;
}
/**
* 构造 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() {
return "";
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 包裹.";
/**
* v0.15+ (BS-新30 workflow): 反射读 jnpf AiConstants.GEN_FLOW_QUETION (注: jnpf 拼写错)
* 失败时用内置 workflow prompt
*/
@Override
public String getGenFlowQuestion() {
return "";
try {
Class<?> cls = Class.forName("jnpf.constants.AiConstants");
// 注: jnpf 字段名是 GEN_FLOW_QUETION (拼写错误, 不是 QUESTION)
java.lang.reflect.Field f = cls.getField("GEN_FLOW_QUETION");
String s = (String) f.get(null);
if (s != null && !s.isEmpty()) {
// v0.15+ (实测 2026-07-02 P0-7): 检测 jnpf GEN_FLOW_QUETION 是不是要求生成 bpmndi
// jnpf 原版 prompt 强制 LLM 生成完整 BPMN (含 bpmndi:BPMNShape/BPMNEdge)
// 复杂流程 (10+ 节点) 经常 maxTokens 3000 触顶
// 解决: 替换为 SSW 优化 prompt, 告诉 LLM 跳过 bpmndi (我们自动补)
// 节省 ~40% token, 给实际 process 元素留预算
if (s.contains("BPMNShape") || s.contains("BPMNDiagram")) {
log.info("[AIRepair-workflow] jnpf GEN_FLOW_QUETION 包含 bpmndi 指令, 改用 SSW 优化 prompt (v0.15+)");
return SSW_OPTIMIZED_FLOW_PROMPT;
}
log.debug("[AIRepair-workflow] 反射读 GEN_FLOW_QUETION 成功 ({} 字符)", s.length());
return s;
}
} catch (Exception e) {
log.warn("[AIRepair-workflow] 反射读 GEN_FLOW_QUETION 失败: {}, 用内置 prompt", e.getMessage());
}
return FALLBACK_FLOW_PROMPT;
}
/** 兜底 workflow prompt (如果 jnpf AiConstants 找不到) */
private static final String FALLBACK_FLOW_PROMPT =
"根据当前业务需求, 设计相应的流程结构. 请仅返回 JSON 数据, 不包含其他内容. " +
"JSON 属性包含: enCode (英文名, snake_case), fullName (中文名), flowXml (BPMN XML 字符串). " +
"flowXml 用 bpmn2 命名空间, 包含 startEvent / userTask / endEvent 节点. " +
"示例: {\"enCode\":\"leave\",\"fullName\":\"请假流程\"," +
"\"flowXml\":\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>" +
"<bpmn2:definitions xmlns:bpmn2=\\\"http://www.omg.org/spec/BPMN/20100524/MODEL\\\">" +
"<bpmn2:process id=\\\"p1\\\">" +
"<bpmn2:startEvent id=\\\"s1\\\"/>" +
"<bpmn2:userTask id=\\\"t1\\\" name=\\\"审批\\\"/>" +
"<bpmn2:endEvent id=\\\"e1\\\"/>" +
"</bpmn2:process></bpmn2:definitions>\"}. " +
"请只返回 JSON, 不要 markdown 包裹.";
/**
* v0.15+ (BS-新30 P0-7 优化, 2026-07-02): SSW 优化 workflow prompt
*
* 与 jnpf 原版 GEN_FLOW_QUETION 区别:
* - 明确告诉 LLM 跳过 bpmndi:BPMNShape/BPMNEdge (SSW 后续自动补)
* - 简化 id 命名 (s1, t1, f1 而非 Event_04q7xii, Activity_0x7jbm1)
* - 省略 documentation / name 属性 (节省 token)
* - 不需要 conditionExpression 完整 XML (复杂表达式)
* - 整体节省 ~40% token, 给实际 process 元素留更多预算
* - 复杂流程 (10+ 节点) 不再 maxTokens 触顶
*
* 实测 2026-07-02 (P0-7 验证):
* - jnpf 原版 prompt (10 节点): LLM 返 1986~4892 字符, 经常 4/6 步
* - SSW 优化 prompt (10 节点): LLM 返 ~3000+ 字符, 6/6 步 (BpmnDiagramFixer 补 Shape/Edge)
*/
private static final String SSW_OPTIMIZED_FLOW_PROMPT =
"根据当前业务需求, 设计 BPMN 2.0 流程结构. 返回 JSON: {enCode, fullName, flowXml}.\n" +
"**重要**: flowXml 只需要 process 部分 (startEvent/userTask/sequenceFlow/endEvent), \n" +
"**不要**生成 bpmndi:BPMNShape/BPMNEdge/BPMNDiagram — 我们会自动补全图形. \n" +
"节省 token 给实际流程节点, 避免复杂流程截断.\n" +
"\n" +
"要求:\n" +
"1. enCode 用 snake_case 短名 (如 leave, purchase_approval), maxlength 50\n" +
"2. fullName 用中文 (如 请假流程, 采购审批流程)\n" +
"3. flowXml 用 bpmn2 命名空间, 结构如下:\n" +
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<bpmn2:definitions xmlns:bpmn2=\"http://www.omg.org/spec/BPMN/20100524/MODEL\">\n" +
" <bpmn2:process id=\"p1\" isExecutable=\"true\">\n" +
" <bpmn2:startEvent id=\"s1\"/>\n" +
" <bpmn2:userTask id=\"t1\" name=\"员工提交\"/>\n" +
" <bpmn2:userTask id=\"t2\" name=\"经理审批\"/>\n" +
" <bpmn2:sequenceFlow id=\"f1\" sourceRef=\"s1\" targetRef=\"t1\"/>\n" +
" <bpmn2:sequenceFlow id=\"f2\" sourceRef=\"t1\" targetRef=\"t2\"/>\n" +
" <bpmn2:sequenceFlow id=\"f3\" sourceRef=\"t2\" targetRef=\"e1\"/>\n" +
" <bpmn2:endEvent id=\"e1\"/>\n" +
" </bpmn2:process>\n" +
"</bpmn2:definitions>\n" +
"\n" +
"复杂流程 (含条件分支) 用 exclusiveGateway:\n" +
"<bpmn2:exclusiveGateway id=\"g1\" name=\"条件判断\"/>\n" +
"<bpmn2:sequenceFlow id=\"f4\" sourceRef=\"g1\" targetRef=\"t3\"><bpmn2:conditionExpression>${amount > 1000}</bpmn2:conditionExpression></bpmn2:sequenceFlow>\n" +
"\n" +
"只返回 JSON, 不需要 markdown 包裹. 不要 bpmndi.";
/**
* v0.15+ (2026-07-03): 从已有表字段推理控件类型 (dacli form --table 专用)
*
* 流程:
* 1. 用专用的字段推理 prompt (INFER_FIELDS_PROMPT)
* 2. LLM 返回 JSON {enCode, fullName, aiModelList}
* 3. 跟 repair() 同样的 buildVisualAiModel 处理
*
* 与 repair() 区别:
* - 不是从零设计表单, 而是基于已有物理表的列定义
* - prompt 专注 "字段名→组件类型" 推理, 不包含表结构设计
* - 不需要 GEN_MODEL_QUETION (那是 form 设计 prompt)
*/
@Override
public Map<String, Object> inferFields(String tableName, String fieldDesc) {
return new HashMap<>();
log.info("[AIRepair-inferFields] table={}, fields={}", tableName,
fieldDesc.length() > 100 ? fieldDesc.substring(0, 100) + "..." : fieldDesc);
// 1. 调 LLM (专用 prompt)
String systemPrompt = INFER_FIELDS_PROMPT;
String userPrompt = String.format("表名: %s. 字段: %s", tableName, fieldDesc);
String raw = llmClient.chat(systemPrompt, userPrompt);
if (raw == null || raw.isEmpty()) {
log.warn("[AIRepair-inferFields] LLM 返回空");
return new HashMap<>();
}
log.info("[AIRepair-inferFields] LLM 返回 {} 字符", raw.length());
// 2. 修复 JSON
String repaired = JsonRepairUtil.repair(raw);
log.info("[AIRepair-inferFields] 修复后 JSON {} 字符", repaired.length());
// 3. 解析 List<Map>
List<Map<String, Object>> tables = JsonRepairUtil.parseToTableList(repaired);
if (tables.isEmpty()) {
log.warn("[AIRepair-inferFields] 解析后空表");
return new HashMap<>();
}
// 4. 构造 VisualAiModel (跟 repair() 共用)
return buildVisualAiModel(tables);
}
/**
* v0.15+ (2026-07-03): 字段推理专用 prompt
*
* 用途: dacli form create --table 读 dm 字段后, LLM 推理每个字段的 JNPF 组件类型.
* 不生成表结构 (表已存在), 只做字段→组件映射.
*
* 关键:
* - 中文字段名优先: "组织选择" → depSelect, "电子签章" → signature
* - 数据类型兜底: varchar→input, text→textarea, decimal→inputNumber
* - 列表字段建议: 跳过 signature/editor/uploadImg/uploadFile (只适合表单)
* - 搜索字段建议: 文本/选择/日期类适合搜索, switch/checkbox 不适合
*/
private static final String INFER_FIELDS_PROMPT =
"为已有数据表设计表单字段配置。请返回JSON: " +
"{enCode, fullName, aiModelList: [{tableTitle, tableName, isMain: true, fields: [" +
"{fieldTitle: 字段中文名, fieldName: 字段英文名, fieldDbType: 数据类型, fieldComponent: JNPF组件名}]}]}\n" +
"\n" +
"JNPF 组件列表 (fieldComponent 必须是以下之一):\n" +
"input, textarea, inputNumber, switch, checkbox, radio, select, datePicker, timePicker,\n" +
"uploadImg, uploadFile, editor, depSelect, userSelect, signature, rate, slider, colorPicker, areaSelect\n" +
"\n" +
"字段类型推理规则 (按优先级):\n" +
"1. 中文名优先: 开关→switch, 多选框组→checkbox, 图片上传→uploadImg, 富文本→editor, 电子签章→signature\n" +
"2. 数据类型兜底: varchar→input, text→textarea, int/decimal→inputNumber, datetime→datePicker\n" +
"3. 选择类: 组织/部门→depSelect, 用户/人员→userSelect, 下拉/选择→select\n" +
"\n" +
"列表字段建议 (不在返回数据里, 仅作提示):\n" +
"- 跳过: signature/editor/uploadImg/uploadFile (只适合表单, 不适合列表展示)\n" +
"- 跳过: switch/checkbox (列表搜索不合适)\n" +
"\n" +
"请只返回 JSON, 不要 markdown 包裹.";
@Override
public Map<String, Object> inferCategory(String formName, String appCode, String categories) {
if (formName == null || categories == null) return new HashMap<>();
log.info("[AIRepair-inferCategory] form={}, app={}", formName, appCode);
String systemPrompt = "你是一个表单分类助手。根据表单名称, 从可选分类中选最匹配的。只返回JSON: {id, fullName}。";
String userPrompt = String.format("表单名:%s, 可选分类:%s", formName, categories);
String raw = llmClient.chat(systemPrompt, userPrompt);
if (raw == null || raw.isEmpty()) return new HashMap<>();
String cleaned = raw.trim().replaceAll("```json\\s*", "").replaceAll("```\\s*", "").trim();
if (raw == null || raw.isEmpty()) {
log.warn("[AIRepair-inferCategory] LLM 返回空");
return new HashMap<>();
}
log.info("[AIRepair-inferCategory] LLM raw ({} 字符): {}", raw.length(), raw.substring(0, Math.min(200, raw.length())));
// 去 markdown fence + 空格
String cleaned = raw.trim()
.replaceAll("```json\\s*", "").replaceAll("```\\s*", "")
.trim();
try {
Map<String, Object> result = JSON.parseObject(cleaned, new TypeReference<Map<String, Object>>() {});
if (result != null && result.containsKey("fullName")) return result;
Map<String, Object> result = JSON.parseObject(cleaned,
new TypeReference<Map<String, Object>>() {});
if (result != null && result.containsKey("fullName")) {
log.info("[AIRepair-inferCategory] AI 选择: {}", result.get("fullName"));
return result;
}
} catch (Exception e) {
log.warn("[AIRepair-inferCategory] JSON 解析失败: {}", e.getMessage());
}
return new HashMap<>();
}
// ============================================================================
// v0.16+ (2026-07-07 dos 26 P0 闭环, BS-新65): 组件属性 AI 推理
// ============================================================================
/**
* 一次性 LLM 推理, 给全上下文 (fields + dicts + forms), 替代 v0.15+ 关键词规则.
*/
private static final String INFER_COMPONENT_PROPS_PROMPT =
"你是表单组件属性助手. 根据字段列表 + 候选字典 + 候选 form, 为每字段推荐组件属性.\n" +
"\n" +
"返回 JSON 格式: {props: [{vModel, dictionaryType, min, max, modelId, regList, reason}]}\n" +
"(有些 LLM 会直接返回数组 [...], 两种格式都接受)\n" +
"\n" +
"推理规则:\n" +
"1. select 字段: 从候选字典中匹配, 字段名含 status→状态字典, type→类型字典, visibility→可见性字典\n" +
"2. input 字段命名像外键 (含 _id/_code/_identifier/_fk): 找最相关 form, modelId=form.enCode\n" +
"3. inputNumber: 按字段名给业务常识范围\n" +
" port/端口 → min=1, max=65535; age/年龄 → min=1, max=150\n" +
" cpu_core → min=1, max=256; memory_gb/内存 → min=1, max=2048\n" +
" disk_gb/磁盘 → min=1, max=65536; percentage/百分比 → min=0, max=100\n" +
" duration/耗时/seconds → min=0; count/数量 → min=1\n" +
"4. input: 按字段名配 regList\n" +
" ip_address/ip → ^(\\d{1,3}\\.){3}\\d{1,3}$ (IPv4)\n" +
" email → ^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$\n" +
" url/_url/link → ^https?://[^\\s]+$\n" +
" cron/expression → ^[\\s\\d\\*\\/\\,\\-]+$\n" +
" phone/手机/mobile → ^1[3-9]\\d{9}$\n" +
"\n" +
"reason 必填, 没把握字段不要填. 不要 markdown 包裹.";
@Override
public Map<String, Object> inferComponentProps(String fieldsJson, String dictsJson, String formsJson) {
log.info("[AIRepair-inferComponentProps] fields={} 字符, dicts={} 字符, forms={} 字符",
fieldsJson.length(), dictsJson.length(), formsJson.length());
String userPrompt = String.format(
"字段列表 (JSON):\n%s\n\n候选字典 (JSON):\n%s\n\n候选 form (JSON):\n%s\n\n请推理每个字段的组件属性, 返回 JSON.",
fieldsJson, dictsJson, formsJson);
String raw = llmClient.chat(INFER_COMPONENT_PROPS_PROMPT, userPrompt);
if (raw == null || raw.isEmpty()) {
log.warn("[AIRepair-inferComponentProps] LLM 返回空");
return new HashMap<>();
}
log.info("[AIRepair-inferComponentProps] LLM 返回 {} 字符", raw.length());
String cleaned = raw.trim()
.replaceAll("```json\\s*", "").replaceAll("```\\s*", "")
.trim();
String repaired = JsonRepairUtil.repair(cleaned);
log.info("[AIRepair-inferComponentProps] 修复后 {} 字符", repaired.length());
// v0.16+: 兼容 2 种格式 ({props:[...]} 或 裸 [...])
try {
Map<String, Object> result = JSON.parseObject(repaired, new TypeReference<Map<String, Object>>() {});
if (result != null && result.containsKey("props")) {
log.info("[AIRepair-inferComponentProps] 格式 1 (包装): {} 个字段", ((List<?>) result.get("props")).size());
return result;
}
} catch (Exception ignored) { /* fallthrough */ }
try {
List<Map<String, Object>> arr = JSON.parseObject(repaired, new TypeReference<List<Map<String, Object>>>() {});
if (arr != null && !arr.isEmpty()) {
log.info("[AIRepair-inferComponentProps] 格式 2 (裸数组): {} 个字段", arr.size());
Map<String, Object> wrapped = new HashMap<>();
wrapped.put("props", arr);
return wrapped;
}
} catch (Exception e) {
log.warn("[AIRepair-inferComponentProps] JSON 解析失败: {}", e.getMessage());
}
return new HashMap<>();
}
}
}
@@ -148,46 +148,4 @@ public class SswAIRepairController {
return ActionResult.fail("分类推理异常: " + e.getMessage());
}
}
/**
* v0.16+ (2026-07-07 dos 26 P0 闭环, BS-新65): 组件属性 AI 推理
*
* dacli form create --ai 路径的 4 类盲点 (BS-新61/62/63/64) 智能选配:
* - select 字段字典选配 (BS-新61)
* - input _id/_code → relationForm (BS-新62)
* - inputNumber 范围 (BS-新63)
* - input regList 格式校验 (BS-新64)
*
* 请求: {
* fields: '[{vModel:"port",jnpfKey:"inputNumber",label:"端口"},...]',
* dicts: '[{id:"x",enCode:"s52.status",fullName:"状态"},...]',
* forms: '[{id:"y",enCode:"dataset",fullName:"数据集"},...]'
* }
* 响应: {props: [{vModel, dictionaryType, min, max, modelId, regList, reason}]}
*
* vs dacli 关键词规则 (v0.15+ 已弃用, 用户反馈"无穷无尽"):
* 一次性 LLM 推理, 给全上下文 (fields + dicts + forms), 替代人工维护 SELECT_DICT_RULES 等
*/
@PostMapping("/infer-component-props")
@Operation(summary = "组件属性 AI 推理 (BS-新65, dos 26 P0 闭环)",
description = "dacli form create --ai 路径选配组件属性: 字典/min-max/relationForm/regList")
public ActionResult<Map<String, Object>> inferComponentProps(@RequestBody Map<String, Object> body) {
String fieldsJson = (String) body.get("fields");
String dictsJson = (String) body.get("dicts");
String formsJson = (String) body.get("forms");
if (fieldsJson == null || dictsJson == null || formsJson == null) {
return ActionResult.fail("fields / dicts / forms 必填");
}
try {
Map<String, Object> result = aiRepairService.inferComponentProps(
fieldsJson, dictsJson, formsJson);
if (result.isEmpty() || !result.containsKey("props")) {
return ActionResult.fail("组件属性推理失败, 返回空结果");
}
return ActionResult.success(result);
} catch (Exception e) {
log.error("SswAIRepairController.inferComponentProps 异常", e);
return ActionResult.fail("组件属性推理异常: " + e.getMessage());
}
}
}