refactor(framework): add Result chain APIs and align runtime exception handling

This commit is contained in:
2026-04-12 16:58:36 +08:00
parent 94d91d9746
commit 19f56d11f0
14 changed files with 274 additions and 190 deletions

View File

@@ -14,6 +14,7 @@ import work.slhaf.partner.core.action.exception.ActionLookupException;
import work.slhaf.partner.core.action.runner.LocalRunnerClient;
import work.slhaf.partner.core.action.runner.RunnerClient;
import work.slhaf.partner.framework.agent.config.ConfigCenter;
import work.slhaf.partner.framework.agent.exception.AgentRuntimeException;
import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler;
import work.slhaf.partner.framework.agent.factory.capability.annotation.CapabilityCore;
import work.slhaf.partner.framework.agent.factory.capability.annotation.CapabilityMethod;
@@ -184,31 +185,32 @@ public class ActionCore implements StateSerializable {
}
private void applyInterventions(List<MetaIntervention> interventions, ExecutableAction executableAction) {
boolean rebuildCleanTag = false;
boolean[] rebuildCleanTag = {false};
interventions.sort(Comparator.comparingInt(MetaIntervention::getOrder));
for (MetaIntervention intervention : interventions) {
Result<List<MetaAction>> actionsResult = resolveInterventionActions(intervention);
if (actionsResult.isFailure()) {
reportLookupFailure(actionsResult.exceptionOrNull());
continue;
}
List<MetaAction> actions = actionsResult.getOrNull();
switch (intervention.getType()) {
case InterventionType.APPEND -> handleAppend(executableAction, intervention.getOrder(), actions);
case InterventionType.INSERT -> handleInsert(executableAction, intervention.getOrder(), actions);
case InterventionType.DELETE -> handleDelete(executableAction, intervention.getOrder(), actions);
case InterventionType.CANCEL -> handleCancel(executableAction);
case InterventionType.REBUILD -> {
if (!rebuildCleanTag) {
cleanActionData(executableAction);
rebuildCleanTag = true;
}
handleRebuild(executableAction, intervention.getOrder(), actions);
}
}
actionsResult
.onFailure(ExceptionReporterHandler.INSTANCE::report)
.onSuccess(actions -> {
switch (intervention.getType()) {
case InterventionType.APPEND ->
handleAppend(executableAction, intervention.getOrder(), actions);
case InterventionType.INSERT ->
handleInsert(executableAction, intervention.getOrder(), actions);
case InterventionType.DELETE ->
handleDelete(executableAction, intervention.getOrder(), actions);
case InterventionType.CANCEL -> handleCancel(executableAction);
case InterventionType.REBUILD -> {
if (!rebuildCleanTag[0]) {
cleanActionData(executableAction);
rebuildCleanTag[0] = true;
}
handleRebuild(executableAction, intervention.getOrder(), actions);
}
}
});
}
}
@@ -217,23 +219,14 @@ public class ActionCore implements StateSerializable {
List<MetaAction> actions = new ArrayList<>();
for (String actionKey : intervention.getActions()) {
Result<MetaAction> metaActionResult = loadMetaAction(actionKey);
if (metaActionResult.isFailure()) {
Throwable throwable = metaActionResult.exceptionOrNull();
return Result.failure(throwable == null
? new ActionLookupException("Meta action lookup failed: " + actionKey, actionKey, "META_ACTION")
: throwable);
AgentRuntimeException failure = metaActionResult.onSuccess(actions::add).exceptionOrNull();
if (failure != null) {
return Result.failure(failure);
}
actions.add(metaActionResult.getOrNull());
}
return Result.success(actions);
}
private void reportLookupFailure(Throwable throwable) {
if (throwable instanceof ActionLookupException lookupException) {
ExceptionReporterHandler.INSTANCE.report(lookupException);
}
}
/**
* 在未进入执行阶段的行动单元组新增新的行动
*/

View File

@@ -8,6 +8,7 @@ import org.w3c.dom.Element;
import work.slhaf.partner.core.action.ActionCapability;
import work.slhaf.partner.core.action.entity.Action;
import work.slhaf.partner.core.action.entity.ExecutableAction;
import work.slhaf.partner.core.action.entity.MetaAction;
import work.slhaf.partner.core.action.entity.MetaActionInfo;
import work.slhaf.partner.core.action.entity.intervention.InterventionType;
import work.slhaf.partner.core.action.entity.intervention.MetaIntervention;
@@ -15,7 +16,7 @@ import work.slhaf.partner.core.cognition.BlockContent;
import work.slhaf.partner.core.cognition.CognitionCapability;
import work.slhaf.partner.core.cognition.ContextBlock;
import work.slhaf.partner.core.cognition.ContextWorkspace;
import work.slhaf.partner.framework.agent.exception.AgentException;
import work.slhaf.partner.framework.agent.exception.AgentRuntimeException;
import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler;
import work.slhaf.partner.framework.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.framework.agent.factory.component.annotation.AgentComponent;
@@ -310,13 +311,9 @@ class BuiltinInterventionActionProvider implements BuiltinActionProvider {
List<String> actions = requireActions(params, type);
ExecutableAction target = requireTargetAction(targetId);
Result<Void> validationResult = validateActionKeys(actions);
if (validationResult.isFailure()) {
reportFailure(validationResult.exceptionOrNull());
Throwable throwable = validationResult.exceptionOrNull();
return JSONObject.of(
"ok", false,
"result", throwable == null ? "Intervention action validation failed" : throwable.getLocalizedMessage()
).toJSONString();
AgentRuntimeException validationFailure = validationResult.onFailure(ExceptionReporterHandler.INSTANCE::report).exceptionOrNull();
if (validationFailure != null) {
return JSONObject.of("ok", false, "result", validationFailure.getLocalizedMessage()).toJSONString();
}
MetaIntervention intervention = new MetaIntervention();
@@ -398,24 +395,13 @@ class BuiltinInterventionActionProvider implements BuiltinActionProvider {
private Result<Void> validateActionKeys(List<String> actions) {
for (String actionKey : actions) {
Result<work.slhaf.partner.core.action.entity.MetaAction> metaActionResult = actionCapability.loadMetaAction(actionKey);
if (metaActionResult.isFailure()) {
Throwable throwable = metaActionResult.exceptionOrNull();
return Result.failure(throwable == null
? new work.slhaf.partner.core.action.exception.ActionLookupException(
"Meta action lookup failed: " + actionKey,
actionKey,
"META_ACTION"
) : throwable);
Result<MetaAction> metaActionResult = actionCapability.loadMetaAction(actionKey);
AgentRuntimeException failure = metaActionResult.exceptionOrNull();
if (failure != null) {
return Result.failure(failure);
}
}
return Result.success(null);
}
private void reportFailure(Throwable throwable) {
if (throwable instanceof AgentException agentException) {
ExceptionReporterHandler.INSTANCE.report(agentException);
}
}
}

View File

@@ -7,7 +7,7 @@ import work.slhaf.partner.core.action.ActionCore;
import work.slhaf.partner.core.action.entity.*;
import work.slhaf.partner.core.action.runner.RunnerClient;
import work.slhaf.partner.core.cognition.CognitionCapability;
import work.slhaf.partner.framework.agent.exception.AgentException;
import work.slhaf.partner.framework.agent.exception.AgentRuntimeException;
import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler;
import work.slhaf.partner.framework.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.framework.agent.factory.component.abstracts.AbstractAgentModule;
@@ -314,14 +314,15 @@ public class ActionExecutor extends AbstractAgentModule.Standalone {
val executingStage = actionData.getExecutingStage();
Result<ExtractorInput> extractorInputResult = assemblyHelper.buildExtractorInput(metaAction.getKey(), actionData.getUuid(), actionData.getDescription());
if (extractorInputResult.isFailure()) {
reportFailure(extractorInputResult.exceptionOrNull());
Throwable throwable = extractorInputResult.exceptionOrNull();
failureReason = buildAttemptFailureReason("参数提取失败", throwable == null ? null : throwable.getLocalizedMessage());
Result<ExtractorInput> extractorInputResult = assemblyHelper.buildExtractorInput(metaAction.getKey(), actionData.getUuid(), actionData.getDescription())
.onFailure(ExceptionReporterHandler.INSTANCE::report);
AgentRuntimeException exception = extractorInputResult.exceptionOrNull();
if (exception != null) {
failureReason = exception.getMessage();
break;
}
val extractorInput = extractorInputResult.getOrNull();
ExtractorInput extractorInput = extractorInputResult.getOrThrow();
ExtractorResult extractorResult = paramsExtractor.execute(extractorInput);
if (extractorResult == null || !extractorResult.isOk()) {
@@ -508,21 +509,12 @@ public class ActionExecutor extends AbstractAgentModule.Standalone {
}
private String resolveHistoryDescription(String actionKey) {
Result<MetaActionInfo> metaActionInfoResult = actionCapability.loadMetaActionInfo(actionKey);
if (metaActionInfoResult.isFailure()) {
reportFailure(metaActionInfoResult.exceptionOrNull());
return actionKey;
}
MetaActionInfo metaActionInfo = metaActionInfoResult.getOrNull();
return metaActionInfo == null || metaActionInfo.getDescription().isBlank()
? actionKey
: metaActionInfo.getDescription();
}
private void reportFailure(Throwable throwable) {
if (throwable instanceof AgentException agentException) {
ExceptionReporterHandler.INSTANCE.report(agentException);
}
return actionCapability.loadMetaActionInfo(actionKey)
.onFailure(ExceptionReporterHandler.INSTANCE::report)
.fold(
metaActionInfo -> metaActionInfo.getDescription().isBlank() ? actionKey : metaActionInfo.getDescription(),
exception -> actionKey
);
}
private record MetaActionsListeningRecord(AtomicBoolean accepting, int phase) {
@@ -540,21 +532,16 @@ public class ActionExecutor extends AbstractAgentModule.Standalone {
}
private Result<ExtractorInput> buildExtractorInput(String actionKey, @NotNull String uuid, @NotNull String description) {
Result<MetaActionInfo> metaActionInfoResult = actionCapability.loadMetaActionInfo(actionKey);
if (metaActionInfoResult.isFailure()) {
Throwable throwable = metaActionInfoResult.exceptionOrNull();
return Result.failure(throwable == null
? new work.slhaf.partner.core.action.exception.ActionLookupException(
"Meta action description not found for action key: " + actionKey,
actionKey,
"META_ACTION_INFO"
) : throwable);
}
ExtractorInput input = new ExtractorInput();
input.setMetaActionInfo(metaActionInfoResult.getOrNull());
input.setTargetActionId(uuid);
input.setTargetActionDesc(description);
return Result.success(input);
return actionCapability.loadMetaActionInfo(actionKey).fold(
metaActionInfo -> {
ExtractorInput input = new ExtractorInput();
input.setMetaActionInfo(metaActionInfo);
input.setTargetActionId(uuid);
input.setTargetActionDesc(description);
return Result.success(input);
},
Result::failure
);
}
private CorrectorInput buildCorrectorInput(ExecutableAction executableAction) {

View File

@@ -34,14 +34,16 @@ public class ParamsExtractor extends AbstractAgentModule.Sub<ExtractorInput, Ext
resolveTaskMessage(input)
);
Result<ExtractorResult> result = formattedChat(messages, ExtractorResult.class);
if (result.isFailure()) {
log.error("ParamsExtractor解析结果失败", result.exceptionOrNull());
ExtractorResult fallback = new ExtractorResult();
fallback.setOk(false);
fallback.setParams(new HashMap<>());
return fallback;
}
return result.getOrThrow();
return result.fold(
extractorResult -> extractorResult,
exception -> {
log.error("ParamsExtractor解析结果失败", exception);
ExtractorResult fallback = new ExtractorResult();
fallback.setOk(false);
fallback.setParams(new HashMap<>());
return fallback;
}
);
}
private Message resolveTaskMessage(ExtractorInput input) {

View File

@@ -11,6 +11,7 @@ import work.slhaf.partner.core.cognition.BlockContent;
import work.slhaf.partner.core.cognition.CognitionCapability;
import work.slhaf.partner.core.cognition.CommunicationBlockContent;
import work.slhaf.partner.core.cognition.ContextBlock;
import work.slhaf.partner.framework.agent.exception.AgentRuntimeException;
import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler;
import work.slhaf.partner.framework.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.framework.agent.factory.component.abstracts.AbstractAgentModule;
@@ -384,11 +385,12 @@ public class ActionPlanner extends AbstractAgentModule.Running<PartnerRunningFlo
List<MetaAction> metaActions = new ArrayList<>();
for (String actionKey : entry.getValue()) {
Result<MetaAction> metaActionResult = actionCapability.loadMetaAction(actionKey);
if (metaActionResult.isFailure()) {
reportFailure(metaActionResult);
AgentRuntimeException failure = metaActionResult.onSuccess(metaActions::add)
.onFailure(ExceptionReporterHandler.INSTANCE::report)
.exceptionOrNull();
if (failure != null) {
return null;
}
metaActions.add(metaActionResult.getOrNull());
}
actionChain.put(entry.getKey(), metaActions);
}
@@ -408,12 +410,14 @@ public class ActionPlanner extends AbstractAgentModule.Running<PartnerRunningFlo
List<String> actionKeys = primaryActionChain.get(fixedOrder);
for (String actionKey : actionKeys) {
// 根据 actionKey 加载行动信息,并检查是否存在必需前置依赖
Result<MetaActionInfo> metaActionInfoResult = actionCapability.loadMetaActionInfo(actionKey);
if (metaActionInfoResult.isFailure()) {
reportFailure(metaActionInfoResult);
Result<MetaActionInfo> infoResult = actionCapability.loadMetaActionInfo(actionKey)
.onFailure(ExceptionReporterHandler.INSTANCE::report);
if (infoResult.exceptionOrNull() != null) {
return false;
}
MetaActionInfo metaActionInfo = metaActionInfoResult.getOrNull();
MetaActionInfo metaActionInfo = infoResult.getOrThrow();
Set<String> preActions = metaActionInfo.getPreActions();
boolean preActionsExist = preActions.isEmpty();
if (!preActionsExist) {
@@ -444,12 +448,6 @@ public class ActionPlanner extends AbstractAgentModule.Running<PartnerRunningFlo
return true;
}
private void reportFailure(Result<?> result) {
if (result.exceptionOrNull() instanceof work.slhaf.partner.framework.agent.exception.AgentException agentException) {
ExceptionReporterHandler.INSTANCE.report(agentException);
}
}
private void fixOrder(Map<Integer, List<String>> primaryActionChain) {
Map<Integer, List<String>> tempChain = new HashMap<>(primaryActionChain);
primaryActionChain.clear();

View File

@@ -66,15 +66,14 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
messages,
EvaluatorResult.class
);
if (result.isFailure()) {
log.error("ActionEvaluator评估失败: {}", tendency, result.exceptionOrNull());
return;
}
EvaluatorResult evaluatorResult = result.getOrThrow();
evaluatorResult.setTendency(tendency);
synchronized (evaluatorResults) {
evaluatorResults.add(evaluatorResult);
}
result
.onFailure(exception -> log.error("ActionEvaluator评估失败: {}", tendency, exception))
.onSuccess(evaluatorResult -> {
evaluatorResult.setTendency(tendency);
synchronized (evaluatorResults) {
evaluatorResults.add(evaluatorResult);
}
});
} finally {
latch.countDown();
}

View File

@@ -27,11 +27,13 @@ public class ActionExtractor extends AbstractAgentModule.Sub<String, ExtractorRe
new Message(Message.Character.USER, input)
);
Result<ExtractorResult> result = formattedChat(messages, ExtractorResult.class);
if (result.isSuccess()) {
return result.getOrThrow();
}
log.error("提取信息出错", result.exceptionOrNull());
return new ExtractorResult();
return result.fold(
extractorResult -> extractorResult,
exception -> {
log.error("提取信息出错", exception);
return new ExtractorResult();
}
);
}
@NotNull

View File

@@ -6,13 +6,13 @@ import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import work.slhaf.partner.core.cognition.*;
import work.slhaf.partner.framework.agent.exception.ExceptionReporterHandler;
import work.slhaf.partner.framework.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.framework.agent.factory.component.abstracts.AbstractAgentModule;
import work.slhaf.partner.framework.agent.factory.component.annotation.Init;
import work.slhaf.partner.framework.agent.model.ActivateModel;
import work.slhaf.partner.framework.agent.model.StreamChatMessageConsumer;
import work.slhaf.partner.framework.agent.model.pojo.Message;
import work.slhaf.partner.framework.agent.support.Result;
import work.slhaf.partner.runtime.PartnerRunningFlowContext;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -67,11 +67,11 @@ public class CommunicationProducer extends AbstractAgentModule.Running<PartnerRu
private void executeChat(PartnerRunningFlowContext runningFlowContext) {
StreamChatMessageConsumer consumer = ReplyDispatcher.INSTANCE.createConsumer(runningFlowContext.getTarget());
Result<kotlin.Unit> result = this.streamChat(buildChatMessages(runningFlowContext), consumer);
if (result.isFailure()) {
log.error("Streaming response failed", result.exceptionOrNull());
consumer.onDelta(INTERRUPTED_MARKER);
}
this.streamChat(buildChatMessages(runningFlowContext), consumer)
.onFailure(exception -> {
ExceptionReporterHandler.INSTANCE.report(exception);
consumer.onDelta(INTERRUPTED_MARKER);
});
updateChatMessages(runningFlowContext, consumer.collectResponse());
updateContext();
}

View File

@@ -15,7 +15,6 @@ import work.slhaf.partner.framework.agent.factory.component.abstracts.AbstractAg
import work.slhaf.partner.framework.agent.factory.component.annotation.Init;
import work.slhaf.partner.framework.agent.model.ActivateModel;
import work.slhaf.partner.framework.agent.model.pojo.Message;
import work.slhaf.partner.framework.agent.support.Result;
import work.slhaf.partner.module.TaskBlock;
import work.slhaf.partner.module.memory.selector.ActivatedMemorySlice;
import work.slhaf.partner.module.memory.selector.evaluator.entity.EvaluatorBatchInput;
@@ -65,16 +64,15 @@ public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput
contextMessage,
resolveTaskMessage(batchInput)
);
Result<EvaluatorBatchResult> batchResult = formattedChat(messages, EvaluatorBatchResult.class);
if (batchResult.isFailure()) {
log.debug("切片评估失败,已跳过当前切片", batchResult.exceptionOrNull());
return;
}
if (batchResult.getOrThrow().isPassed()) {
synchronized (result) {
result.add(slice);
}
}
formattedChat(messages, EvaluatorBatchResult.class)
.onFailure(exception -> log.debug("切片评估失败,已跳过当前切片", exception))
.onSuccess(evaluatorBatchResult -> {
if (evaluatorBatchResult.isPassed()) {
synchronized (result) {
result.add(slice);
}
}
});
} finally {
latch.countDown();
}

View File

@@ -43,15 +43,19 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<ExtractorInpu
messages,
ExtractorResult.class
);
if (result.isSuccess()) {
extractorResult = result.getOrThrow();
log.debug("[MemorySelectExtractor] 主题提取结果: {}", extractorResult);
} else {
log.error("[MemorySelectExtractor] 主题提取出错: ", result.exceptionOrNull());
extractorResult = new ExtractorResult();
extractorResult.setRecall(false);
extractorResult.setMatches(List.of());
}
extractorResult = result.fold(
value -> {
log.debug("[MemorySelectExtractor] 主题提取结果: {}", value);
return value;
},
exception -> {
log.error("[MemorySelectExtractor] 主题提取出错: ", exception);
ExtractorResult fallback = new ExtractorResult();
fallback.setRecall(false);
fallback.setMatches(List.of());
return fallback;
}
);
return fix(extractorResult);
}