feat(ai): 自由模式转创意助手,失败日志补失败节点与上游 error(issue 17 / 18)
自由模式(issue 18): - docType 为空时不调「内容创作与宣传助手」——它开始节点的 doc_type 是必填 select, 空值直接被上游判 failed(error="doc_type is required in input form")。改为转 「AI 创意助手」,只发它唯一的必填入参 user_content。 - ManuscriptGenInputs 增加 userContent;doc_type / Number 仍无条件带键(空串能过 Dify 的必填校验,缺键不行)。 - 用例:AiManuscriptFreeModeRouteTest、AiManuscriptInputsContractTest。 失败日志(issue 17): - 稿件流程、大纲流程、executeWorkflowForResult 三处失败日志补 status + failedNode + upstreamError + elapsed。失败信息拆在 node_finished 与 workflow_finished 两类事件, 入参校验类失败只有后者,只取节点事件等于没取。 - 补 event=error 与「静默断流」(没有 workflow_finished / message_end)的日志, 两者都带 taskId,可与请求对上。 - 日志级用 error 而非 warn:生产 com.gxwebsoft 只开 ERROR。 - 用例:AiWorkflowFailureDetailTest。
This commit is contained in:
@@ -207,7 +207,6 @@ public class AiController extends BaseController {
|
||||
payload.put("user", getLoginUserId() == null ? "0" : getLoginUserId().toString());
|
||||
payload.put("conversation_id", StrUtil.blankToDefault(message.getConversationId(), ""));
|
||||
payload.put("inputs", parseInputs(message.getInputs()));
|
||||
System.out.println("payload:" + payload);
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
os.write(JSONUtil.toJSONString(payload).getBytes(StandardCharsets.UTF_8));
|
||||
os.flush();
|
||||
@@ -216,6 +215,8 @@ public class AiController extends BaseController {
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode < 200 || responseCode >= 300) {
|
||||
String responseBody = readStream(connection.getErrorStream());
|
||||
logger.error("chat message rejected, httpStatus={}, body={}",
|
||||
responseCode, briefUpstreamError(responseBody));
|
||||
JSONObject result = JSONObject.parseObject(responseBody);
|
||||
throw new RuntimeException(result != null ? result.toJSONString() : responseBody);
|
||||
}
|
||||
@@ -289,7 +290,6 @@ public class AiController extends BaseController {
|
||||
? (data.get("answer") == null ? null : data.get("answer").toString())
|
||||
: data.get("thought").toString();
|
||||
if (answer != null) {
|
||||
System.out.println(answer);
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", answer);
|
||||
answerData.put("loading", "true");
|
||||
@@ -334,10 +334,7 @@ public class AiController extends BaseController {
|
||||
clearActiveAiTask(getLoginUserId(), taskId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
|
||||
System.out.println(stackTraceElement);
|
||||
}
|
||||
logger.error("chat message request failed", e);
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", "出错了,请晚点再来提问吧~");
|
||||
answerData.put("taskId", "0");
|
||||
@@ -353,6 +350,13 @@ public class AiController extends BaseController {
|
||||
|
||||
@PostMapping("/manuscriptGen")
|
||||
public ApiResult<?> manuscriptGen(@RequestBody ManuscriptGenInputs message) throws IOException {
|
||||
// 未选文稿模板 = 自由模式。此时不调「内容创作与宣传助手」:它开始节点的
|
||||
// doc_type 是必填 select,空值会被上游直接判 failed
|
||||
// (实测 error="doc_type is required in input form"),转「AI 创意助手」,
|
||||
// 只带 user_content。选了模板才走下面的稿件生成流程(见 issue 18)。
|
||||
if (message == null || StrUtil.isBlank(message.getDocType())) {
|
||||
return runCreativeAssistantForFreeMode(message);
|
||||
}
|
||||
try {
|
||||
URL url = new URL(aiUrl() + "/workflows/run");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
@@ -374,8 +378,6 @@ public class AiController extends BaseController {
|
||||
payload.put("user", getLoginUserId() == null ? "0" : getLoginUserId().toString());
|
||||
payload.put("inputs", inputs);
|
||||
|
||||
System.out.println("manuscript payload:" + payload);
|
||||
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
os.write(JSONUtil.toJSONString(payload).getBytes(StandardCharsets.UTF_8));
|
||||
os.flush();
|
||||
@@ -384,6 +386,8 @@ public class AiController extends BaseController {
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode < 200 || responseCode >= 300) {
|
||||
String responseBody = readStream(connection.getErrorStream());
|
||||
logger.error("manuscript workflow rejected, httpStatus={}, body={}",
|
||||
responseCode, briefUpstreamError(responseBody));
|
||||
JSONObject result = JSONObject.parseObject(responseBody);
|
||||
throw new RuntimeException(result != null ? result.toJSONString() : responseBody);
|
||||
}
|
||||
@@ -396,6 +400,13 @@ public class AiController extends BaseController {
|
||||
// 不用局部布尔直接在收尾赋值是因为失败分支里 `continue` 了,
|
||||
// 必须在外层作用域里记录。
|
||||
boolean workflowFailed = false;
|
||||
// 失败现场:失败节点名 + 上游 error。日志里只有 taskId 一行时
|
||||
// 无从判断是哪个节点、什么原因挂的(2026-10-21 的排查就卡在这里)。
|
||||
WorkflowFailure failure = new WorkflowFailure();
|
||||
// 收尾事件是否出现过。没出现说明流被上游或网络提前截断,
|
||||
// 这种「静默断流」以前在日志里一个字都没有。
|
||||
boolean finalEventSeen = false;
|
||||
String lastEvent = null;
|
||||
|
||||
try (BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
@@ -415,6 +426,10 @@ public class AiController extends BaseController {
|
||||
}
|
||||
|
||||
String event = data.get("event") == null ? "" : data.get("event").toString();
|
||||
lastEvent = event;
|
||||
// 失败信息散在 node_finished / workflow_finished 事件里,逐个喂进去。
|
||||
failure.observe(data);
|
||||
|
||||
if (StrUtil.isNotBlank(stringValue(data.get("workflow_run_id")))) {
|
||||
workflowRunId = stringValue(data.get("workflow_run_id"));
|
||||
}
|
||||
@@ -426,7 +441,6 @@ public class AiController extends BaseController {
|
||||
if (StrUtil.isNotBlank(taskId)) {
|
||||
recordActiveAiTask(getLoginUserId(), "workflow", taskId, appKeys().getManuscript());
|
||||
}
|
||||
System.out.println(data);
|
||||
// 正文只认正文事件(text_chunk / message);其余事件的
|
||||
// extractAnswer 结果可能是 data.id 这类内部标识符,不得进 reply(见 issue 06)。
|
||||
String answer = extractAnswer(data);
|
||||
@@ -454,11 +468,15 @@ public class AiController extends BaseController {
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
}
|
||||
} else if ("workflow_finished".equals(event) || "message_end".equals(event)) {
|
||||
finalEventSeen = true;
|
||||
// 失败态先判定:outputs 为空时 answer 可能是 workflow_run_id
|
||||
// 这类内部标识符,不能当正文推给端上(见 issue 03)。
|
||||
if (isWorkflowFailed(workflowStatus(data))) {
|
||||
logger.warn("manuscript workflow failed, taskId={}, workflowRunId={}",
|
||||
taskId, workflowRunId);
|
||||
// 用 error 而非 warn:生产日志级别是 com.gxwebsoft: ERROR,
|
||||
// warn 会被整个吞掉,就成了「端上说生成失败、后端日志里什么都没有」
|
||||
// (同 executeCreativeAssistantWithRetry 上方的注释)。
|
||||
logger.error("manuscript workflow failed, taskId={}, workflowRunId={}, {}",
|
||||
taskId, workflowRunId, failure.describe());
|
||||
workflowFailed = true;
|
||||
reply.setLength(0);
|
||||
reply.append(CREATIVE_FAILED_MESSAGE);
|
||||
@@ -511,11 +529,22 @@ public class AiController extends BaseController {
|
||||
}
|
||||
clearActiveAiTask(getLoginUserId(), taskId);
|
||||
} else if ("error".equals(event)) {
|
||||
// error 事件带的是整段上游异常,以前直接 throw 只留一个 500 的栈,
|
||||
// taskId 都没进日志,排查时无法与请求对上。
|
||||
logger.error("manuscript stream error event, taskId={}, workflowRunId={}, event={}",
|
||||
taskId, workflowRunId, briefUpstreamError(json));
|
||||
throw new RuntimeException(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalEventSeen) {
|
||||
// 流结束却没有 workflow_finished / message_end:正文可能只有半截,
|
||||
// 也可能一个字都没有,端上看到的就是「什么都没生成」。
|
||||
logger.error("manuscript stream ended without finish event, taskId={}, workflowRunId={}, "
|
||||
+ "chars={}, lastEvent={}",
|
||||
taskId, workflowRunId, reply.length(), lastEvent);
|
||||
}
|
||||
if (!endSent) {
|
||||
HashMap<String, String> endData = new HashMap<>();
|
||||
endData.put("answer", "__END__");
|
||||
@@ -531,10 +560,7 @@ public class AiController extends BaseController {
|
||||
return success("Stream processing completed",
|
||||
buildManuscriptResult(reply, taskId, workflowRunId, workflowFailed));
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
|
||||
System.out.println(stackTraceElement);
|
||||
}
|
||||
logger.error("manuscript request failed", e);
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", "出错了,请晚点再试~");
|
||||
answerData.put("taskId", "0");
|
||||
@@ -835,6 +861,8 @@ public class AiController extends BaseController {
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
String messageText = responseData == null ? responseBody : JSONUtil.toJSONString(responseData);
|
||||
logger.error("activity outline workflow rejected, httpStatus={}, body={}",
|
||||
responseCode, briefUpstreamError(messageText));
|
||||
return fail("活动策划大纲生成失败", messageText);
|
||||
}
|
||||
|
||||
@@ -844,6 +872,11 @@ public class AiController extends BaseController {
|
||||
boolean endSent = false;
|
||||
// 见 manuscriptGen:失败分支里有 continue,故在外层作用域记录(issue 10)。
|
||||
boolean workflowFailed = false;
|
||||
// 失败现场(失败节点名 + 上游 error),见 WorkflowFailure。
|
||||
WorkflowFailure failure = new WorkflowFailure();
|
||||
// 收尾事件是否出现过,用于识别上游提前断流。
|
||||
boolean finalEventSeen = false;
|
||||
String lastEvent = null;
|
||||
|
||||
try (BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
@@ -863,6 +896,9 @@ public class AiController extends BaseController {
|
||||
}
|
||||
|
||||
String event = stringValue(data.get("event"));
|
||||
lastEvent = event;
|
||||
// 失败信息散在 node_finished / workflow_finished 事件里,逐个喂进去。
|
||||
failure.observe(data);
|
||||
if (StrUtil.isNotBlank(stringValue(data.get("conversation_id")))) {
|
||||
conversationId = stringValue(data.get("conversation_id"));
|
||||
}
|
||||
@@ -885,12 +921,13 @@ public class AiController extends BaseController {
|
||||
sendActivityOutlineSocketMessage(loadingText, conversationId, messageId, true);
|
||||
}
|
||||
} else if ("message_end".equals(event) || "workflow_finished".equals(event)) {
|
||||
finalEventSeen = true;
|
||||
// 失败态必须先判定:此时 outputs 为空、answer 可能是
|
||||
// workflow_run_id 这类内部标识符,直接下发等于把标识符
|
||||
// 当正文推给端上(见 issue 03)。
|
||||
if (isWorkflowFailed(workflowStatus(data))) {
|
||||
logger.warn("activity outline workflow failed, conversationId={}, messageId={}",
|
||||
conversationId, messageId);
|
||||
logger.error("activity outline workflow failed, conversationId={}, messageId={}, {}",
|
||||
conversationId, messageId, failure.describe());
|
||||
workflowFailed = true;
|
||||
reply.setLength(0);
|
||||
reply.append(CREATIVE_FAILED_MESSAGE);
|
||||
@@ -914,11 +951,18 @@ public class AiController extends BaseController {
|
||||
sendActivityOutlineSocketEnd(conversationId, messageId);
|
||||
}
|
||||
} else if ("error".equals(event)) {
|
||||
logger.error("activity outline stream error event, conversationId={}, messageId={}, event={}",
|
||||
conversationId, messageId, briefUpstreamError(json));
|
||||
throw new RuntimeException(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalEventSeen) {
|
||||
logger.error("activity outline stream ended without finish event, conversationId={}, "
|
||||
+ "messageId={}, chars={}, lastEvent={}",
|
||||
conversationId, messageId, reply.length(), lastEvent);
|
||||
}
|
||||
if (!endSent) {
|
||||
sendActivityOutlineSocketEnd(conversationId, messageId);
|
||||
}
|
||||
@@ -1388,9 +1432,14 @@ public class AiController extends BaseController {
|
||||
if (message == null) {
|
||||
return inputs;
|
||||
}
|
||||
if (StrUtil.isNotBlank(message.getDocType())) {
|
||||
inputs.put("doc_type", message.getDocType());
|
||||
}
|
||||
// doc_type / Number 是上游提示词里的**主控指令**变量,但前端「自动识别」时故意不带值。
|
||||
// 这两个键**无条件带上下发**(没值给空串),理由:
|
||||
// - Dify 的必填校验只看「键是否存在」:缺键直接 failed,而空串能过
|
||||
// (见 .scratch/dify-probe/README.md 的对照表);对没声明必填的变量,
|
||||
// 空串与不传等价(开始节点自己会补空)。
|
||||
// - 值留空 = 交给上游工作流自己的识别分支,不在我们这边猜
|
||||
// (猜错就是把垃圾值当主控指令,见 writing-params 的契约说明)。
|
||||
inputs.put("doc_type", StrUtil.blankToDefault(message.getDocType(), ""));
|
||||
if (StrUtil.isNotBlank(message.getEventType())) {
|
||||
inputs.put("event_type", message.getEventType());
|
||||
}
|
||||
@@ -1409,14 +1458,53 @@ public class AiController extends BaseController {
|
||||
if (StrUtil.isNotBlank(message.getHighlights())) {
|
||||
inputs.put("highlights", message.getHighlights());
|
||||
}
|
||||
if (message.getNumber() != null) {
|
||||
// Dify 工作流里该变量名首字母大写(Number),与其它小写变量不一致。
|
||||
// 变量名大小写敏感,发 "number" 会因缺参报错,故按实际变量名发送。
|
||||
inputs.put("Number", message.getNumber());
|
||||
}
|
||||
// Dify 工作流里该变量名首字母大写(Number),与其它小写变量不一致。
|
||||
// 变量名大小写敏感,发 "number" 会因缺参报错,故按实际变量名发送。
|
||||
// 与 doc_type 同理:没值也要带键,空串交给上游自己判。
|
||||
inputs.put("Number", message.getNumber() == null ? "" : message.getNumber());
|
||||
return inputs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自由模式:把「未选文稿模板」的写作请求转给「AI 创意助手」。
|
||||
*
|
||||
* <p>创意助手的开始节点只有 {@code user_content} 一个必填入参,所以这里把
|
||||
* 用户原话拼成一整段下发,不再经过稿件生成那套 doc_type/event_type 入参。
|
||||
* 返回值沿用创意助手的结果结构。
|
||||
*/
|
||||
private ApiResult<?> runCreativeAssistantForFreeMode(ManuscriptGenInputs message) {
|
||||
String userContent = freeModeText(message);
|
||||
if (StrUtil.isBlank(userContent)) {
|
||||
return fail("请先填写要创作的内容");
|
||||
}
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("user_content", userContent);
|
||||
logger.info("manuscript free mode (docType blank), delegate to creative assistant, chars={}",
|
||||
userContent.length());
|
||||
return executeCreativeAssistant(body, getLoginUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 自由模式的创作素材。新前端把用户原话放在 {@code userContent};
|
||||
* 老小程序(写作模式仍是"自动识别")只发解析后的 theme / highlights,
|
||||
* 这里按顺序兜底,免得前端版本差异让自由模式空着入参。
|
||||
*/
|
||||
private String freeModeText(ManuscriptGenInputs message) {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
if (StrUtil.isNotBlank(message.getUserContent())) {
|
||||
return message.getUserContent().trim();
|
||||
}
|
||||
List<String> parts = new ArrayList<>();
|
||||
for (String part : new String[]{message.getTheme(), message.getHighlights()}) {
|
||||
if (StrUtil.isNotBlank(part)) {
|
||||
parts.add(part.trim());
|
||||
}
|
||||
}
|
||||
return parts.isEmpty() ? null : String.join("。", parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 「活动策划大纲生成」的前置校验。
|
||||
*
|
||||
@@ -1713,6 +1801,8 @@ public class AiController extends BaseController {
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode < 200 || responseCode >= 300) {
|
||||
String responseBody = readStream(connection.getErrorStream());
|
||||
logger.error("{} workflow rejected, httpStatus={}, body={}",
|
||||
stopType, responseCode, briefUpstreamError(responseBody));
|
||||
return fail("AI工作流调用失败", responseBody);
|
||||
}
|
||||
|
||||
@@ -1722,6 +1812,11 @@ public class AiController extends BaseController {
|
||||
Map<String, Object> lastData = null;
|
||||
boolean endSent = false;
|
||||
boolean workflowFailed = false;
|
||||
// 失败现场(失败节点名 + 上游 error),见 WorkflowFailure。
|
||||
WorkflowFailure failure = new WorkflowFailure();
|
||||
// 收尾事件是否出现过,用于识别上游提前断流。
|
||||
boolean finalEventSeen = false;
|
||||
String lastEvent = null;
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
@@ -1753,6 +1848,9 @@ public class AiController extends BaseController {
|
||||
}
|
||||
|
||||
String event = stringValue(data.get("event"));
|
||||
lastEvent = event;
|
||||
// 失败信息散在 node_finished / workflow_finished 事件里,逐个喂进去。
|
||||
failure.observe(data);
|
||||
String answer = extractAnswer(data);
|
||||
if (answer != null && ("text_chunk".equals(event) || "message".equals(event))) {
|
||||
reply.append(answer);
|
||||
@@ -1767,12 +1865,13 @@ public class AiController extends BaseController {
|
||||
taskId, workflowRunId, stopType, true, loginUserId);
|
||||
}
|
||||
} else if ("workflow_finished".equals(event) || "message_end".equals(event)) {
|
||||
finalEventSeen = true;
|
||||
// 失败态必须先判定:outputs 为空时 answer 可能是
|
||||
// workflow_run_id 这类内部标识符,不能当正文推给端上(见 issue 03)。
|
||||
String eventStatus = workflowStatus(data);
|
||||
if (isWorkflowFailed(eventStatus)) {
|
||||
logger.warn("workflow failed, stopType={}, taskId={}, workflowRunId={}",
|
||||
stopType, taskId, workflowRunId);
|
||||
logger.error("workflow failed, stopType={}, taskId={}, workflowRunId={}, {}",
|
||||
stopType, taskId, workflowRunId, failure.describe());
|
||||
workflowFailed = true;
|
||||
reply.setLength(0);
|
||||
reply.append(CREATIVE_FAILED_MESSAGE);
|
||||
@@ -1801,11 +1900,20 @@ public class AiController extends BaseController {
|
||||
}
|
||||
clearActiveAiTask(loginUserId, taskId);
|
||||
} else if ("error".equals(event)) {
|
||||
logger.error("{} stream error event, taskId={}, workflowRunId={}, event={}",
|
||||
stopType, taskId, workflowRunId, briefUpstreamError(json));
|
||||
throw new RuntimeException(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalEventSeen) {
|
||||
// 没收到 workflow_finished / message_end 就结束:上游提前断流。
|
||||
// 这里不加「空正文」告警——competitionHistoryPreprocess 等应用
|
||||
// 正常收场时 outputs 就是空的,空正文并不等于出错。
|
||||
logger.error("{} stream ended without finish event, taskId={}, workflowRunId={}, lastEvent={}",
|
||||
stopType, taskId, workflowRunId, lastEvent);
|
||||
}
|
||||
if (streamToSocket && !endSent) {
|
||||
sendWorkflowSocketEnd(taskId, workflowRunId, stopType, loginUserId);
|
||||
}
|
||||
@@ -2059,6 +2167,160 @@ public class AiController extends BaseController {
|
||||
return "failed".equalsIgnoreCase(StrUtil.trimToEmpty(status));
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次流式工作流执行里的失败现场,用来把「只有 taskId 一行」的失败日志补全。
|
||||
*
|
||||
* <p>Dify 把失败信息拆在两类事件里,只取其一都会缺一半:
|
||||
* <ul>
|
||||
* <li>{@code node_finished}(status=failed):带<b>节点名</b>和该节点的异常原文,
|
||||
* 这是判断「哪个环节挂了」的唯一来源;</li>
|
||||
* <li>{@code workflow_finished}(status=failed):带 {@code error}(上游整包文案,
|
||||
* 如 {@code doc_type is required in input form})与 {@code elapsed_time},
|
||||
* 但没有节点名。</li>
|
||||
* </ul>
|
||||
* 所以每个已解析的 SSE 事件都交给 {@link #observe(Map)} 收集,收尾时由
|
||||
* {@link #describe()} 拼成一行可直接 grep 的现场描述。
|
||||
*
|
||||
* <p>不变量:只有真的见过 {@code failed} 才产出内容({@link #happened()}),
|
||||
* 成功路径的日志里不会冒出 {@code failedNode=null} 这种噪音。
|
||||
*/
|
||||
private class WorkflowFailure {
|
||||
|
||||
/** 最后一次明确的失败状态;未失败时保持 {@code null}。 */
|
||||
private String status;
|
||||
/** 失败节点在编排界面上的名字,可比 nodeId 直接对上「哪个环节」。 */
|
||||
private String nodeTitle;
|
||||
/** 失败节点的内部 id,能直接对上 Dify 的 node_finished 日志。 */
|
||||
private String nodeId;
|
||||
/** 节点级异常原文,语义比工作流级更精确,工作流级缺失时才顶上。 */
|
||||
private String nodeError;
|
||||
/** 工作流级异常原文。 */
|
||||
private String workflowError;
|
||||
/** 工作流级耗时(秒),失败太快(如 0.0s)往往意味着入参校验就挂了。 */
|
||||
private String elapsedTime;
|
||||
|
||||
/**
|
||||
* 吸收一个已解析的 SSE 事件。
|
||||
*
|
||||
* <p>对不认识的事件静默忽略:正常路径上大多数事件(text_chunk、
|
||||
* node_started 等)与本类无关,逐条打日志只会淹没真正的失败。
|
||||
*/
|
||||
void observe(Map<?, ?> event) {
|
||||
if (event == null) {
|
||||
return;
|
||||
}
|
||||
String name = stringValue(event.get("event"));
|
||||
if ("node_finished".equals(name)) {
|
||||
observeNodeFinished(event);
|
||||
return;
|
||||
}
|
||||
if ("workflow_finished".equals(name) || "message_end".equals(name)) {
|
||||
observeWorkflowFinished(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void observeNodeFinished(Map<?, ?> event) {
|
||||
Object body = event.get("data");
|
||||
if (!(body instanceof Map)) {
|
||||
return;
|
||||
}
|
||||
Map<?, ?> node = (Map<?, ?>) body;
|
||||
if (!isWorkflowFailed(stringValue(node.get("status")))) {
|
||||
return;
|
||||
}
|
||||
status = "failed";
|
||||
// node_id 是内部 id,title 才是编排界面上的名字;两者都留:
|
||||
// id 能直接对上 Dify 日志,title 能让人一眼看出是哪个环节。
|
||||
String title = stringValue(node.get("title"));
|
||||
if (StrUtil.isNotBlank(title)) {
|
||||
nodeTitle = title;
|
||||
}
|
||||
String id = firstNonBlank(stringValue(node.get("node_id")), stringValue(node.get("id")));
|
||||
if (id != null) {
|
||||
nodeId = id;
|
||||
}
|
||||
// 不同版本的 Dify 把节点异常放在不同键上,按「最具体 → 最泛化」的顺序取。
|
||||
String error = firstNonBlank(stringValue(node.get("error")),
|
||||
stringValue(node.get("error_message")), stringValue(node.get("message")));
|
||||
if (error != null) {
|
||||
nodeError = error;
|
||||
}
|
||||
}
|
||||
|
||||
private void observeWorkflowFinished(Map<?, ?> event) {
|
||||
Object body = event.get("data");
|
||||
Map<?, ?> payload = body instanceof Map ? (Map<?, ?>) body : event;
|
||||
// 状态既可能在 data.status,也可能在顶层 status,两处都看(同 workflowStatus)。
|
||||
String eventStatus = firstNonBlank(stringValue(payload.get("status")),
|
||||
stringValue(event.get("status")));
|
||||
if (!isWorkflowFailed(eventStatus)) {
|
||||
return;
|
||||
}
|
||||
status = "failed";
|
||||
String error = firstNonBlank(stringValue(payload.get("error")),
|
||||
stringValue(payload.get("error_message")),
|
||||
stringValue(event.get("error")), stringValue(event.get("message")));
|
||||
if (error != null) {
|
||||
workflowError = error;
|
||||
}
|
||||
String elapsed = stringValue(payload.get("elapsed_time"));
|
||||
if (StrUtil.isNotBlank(elapsed)) {
|
||||
elapsedTime = elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
/** 本轮是否见过明确失败。 */
|
||||
boolean happened() {
|
||||
return "failed".equals(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一行现场描述,未失败时为空串。
|
||||
*
|
||||
* <p>错误原文按 {@link #UPSTREAM_ERROR_LOG_MAX_LENGTH} 截断:上游会把整段
|
||||
* provider 报错(含换行、含 {@code b'{"code":50500,...}'} 这类裸 repr)塞进
|
||||
* {@code error},个别情况下可达数 KB,必须压成单行才不至于撑爆日志。
|
||||
*/
|
||||
String describe() {
|
||||
if (!happened()) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder("status=failed");
|
||||
if (nodeTitle == null && nodeId == null) {
|
||||
sb.append(", failedNode=<unknown>");
|
||||
} else {
|
||||
sb.append(", failedNode=").append(StrUtil.blankToDefault(nodeTitle, "?"));
|
||||
if (nodeId != null) {
|
||||
sb.append("(").append(nodeId).append(")");
|
||||
}
|
||||
}
|
||||
String error = workflowError;
|
||||
if (error == null) {
|
||||
error = nodeError;
|
||||
}
|
||||
sb.append(", upstreamError=")
|
||||
.append(error == null ? "<事件未带 error 字段>" : briefUpstreamError(error));
|
||||
// 节点级原文常常比工作流级的更具体(含 provider 的状态码与报错体),
|
||||
// 与工作流级不同时一并带上,否则只剩一句概括,排不到根因。
|
||||
if (nodeError != null && !nodeError.equals(error)) {
|
||||
sb.append(", nodeError=").append(briefUpstreamError(nodeError));
|
||||
}
|
||||
if (elapsedTime != null) {
|
||||
sb.append(", elapsed=").append(elapsedTime).append("s");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (StrUtil.isNotBlank(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> buildChatMessageResult(Map<String, Object> responseData, String responseBody) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
if (responseData == null) {
|
||||
|
||||
@@ -28,6 +28,15 @@ public class ManuscriptGenInputs implements Serializable {
|
||||
|
||||
private Integer number;
|
||||
|
||||
/**
|
||||
* 自由模式(未选文稿模板)下用户的原话。
|
||||
*
|
||||
* <p>未选 {@code docType} 时后端不调「内容创作与宣传助手」(它的 doc_type
|
||||
* 是上游必填 select,空值直接 failed),而是转「AI 创意助手」,把这段原话
|
||||
* 作为它唯一的必填入参 {@code user_content} 下发。选了模板时该字段被忽略。
|
||||
*/
|
||||
private String userContent;
|
||||
|
||||
/**
|
||||
* 附件材料。
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user