refactor(project): normalize formatting and reorder class members across modules

This commit is contained in:
2026-02-20 17:22:54 +08:00
parent c47d2b2285
commit bbace28d7a
102 changed files with 706 additions and 492 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@@ -31,9 +31,6 @@ public final class InProcessMcpTransport implements McpClientTransport, McpState
private volatile McpStatelessServerHandler serverHandler;
public record Pair(InProcessMcpTransport clientSide, InProcessMcpTransport serverSide) {
}
public static Pair pair() {
InProcessMcpTransport client = new InProcessMcpTransport();
InProcessMcpTransport server = new InProcessMcpTransport();
@@ -126,15 +123,15 @@ public final class InProcessMcpTransport implements McpClientTransport, McpState
return Mono.empty();
}
/* ======================================================
* other boilerplate
* ====================================================== */
@Override
public void close() {
McpClientTransport.super.close();
}
/* ======================================================
* other boilerplate
* ====================================================== */
@Override
public Mono<Void> closeGracefully() {
inbound.tryEmitComplete();
@@ -152,4 +149,7 @@ public final class InProcessMcpTransport implements McpClientTransport, McpState
public List<String> protocolVersions() {
return McpClientTransport.super.protocolVersions();
}
public record Pair(InProcessMcpTransport clientSide, InProcessMcpTransport serverSide) {
}
}

View File

@@ -1,43 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Main</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.partner.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Main</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.partner.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@@ -6,8 +6,8 @@ import work.slhaf.partner.common.thread.InteractionThreadPoolExecutor;
@Slf4j
public class DebugMonitor {
private InteractionThreadPoolExecutor executor;
private static DebugMonitor debugMonitor;
private InteractionThreadPoolExecutor executor;
public static void initialize() {
debugMonitor = new DebugMonitor();
@@ -15,6 +15,13 @@ public class DebugMonitor {
debugMonitor.runMonitor();
}
public static DebugMonitor getInstance() {
if (debugMonitor == null) {
initialize();
}
return debugMonitor;
}
private void runMonitor() {
executor.execute(() -> {
while (true) {
@@ -26,11 +33,4 @@ public class DebugMonitor {
}
});
}
public static DebugMonitor getInstance(){
if (debugMonitor == null) {
initialize();
}
return debugMonitor;
}
}

View File

@@ -30,8 +30,8 @@ public class ResourcesUtil {
return readPromptFromResources(SELF_AWARENESS_PATH);
}
public static List<Message> loadPrompt(String modelKey,String promptType){
return new ArrayList<>(readPromptFromResources(MODULE_PROMPT_PREFIX_PATH+promptType+"/"+modelKey+".json"));
public static List<Message> loadPrompt(String modelKey, String promptType) {
return new ArrayList<>(readPromptFromResources(MODULE_PROMPT_PREFIX_PATH + promptType + "/" + modelKey + ".json"));
}
private static List<Message> readPromptFromResources(String filePath) {

View File

@@ -34,33 +34,28 @@ import java.util.stream.Collectors;
@Slf4j
public class ActionCore extends PartnerCore<ActionCore> {
/**
* 持久行动池
*/
private CopyOnWriteArraySet<ExecutableAction> actionPool = new CopyOnWriteArraySet<>();
/**
* 待确认任务以userId区分不同用户因为需要跨请求确认
*/
private HashMap<String, List<ExecutableAction>> pendingActions = new HashMap<>();
/**
* 语义缓存与行为倾向映射
*/
private List<ActionCacheData> actionCache = new ArrayList<>();
private final Lock cacheLock = new ReentrantLock();
// 由于当前的执行器逻辑实现,平台线程池大小不得小于 2这里规定为最小为 4
private final ExecutorService platformExecutor = Executors
.newFixedThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 4));
private final ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
/**
* 已存在的行动程序,键格式为‘<MCP-ServerName>::<Tool-Name>’,值为 MCP Server 通过 Resources 相关渠道传递的行动程序元信息
*/
private final ConcurrentHashMap<String, MetaActionInfo> existedMetaActions = new ConcurrentHashMap<>();
private final List<PhaserRecord> phaserRecords = new ArrayList<>();
/**
* 持久行动池
*/
private CopyOnWriteArraySet<ExecutableAction> actionPool = new CopyOnWriteArraySet<>();
/**
* 待确认任务以userId区分不同用户因为需要跨请求确认
*/
private HashMap<String, List<ExecutableAction>> pendingActions = new HashMap<>();
/**
* 语义缓存与行为倾向映射
*/
private List<ActionCacheData> actionCache = new ArrayList<>();
private RunnerClient runnerClient;
public ActionCore() throws IOException, ClassNotFoundException {

View File

@@ -119,6 +119,29 @@ public class LocalRunnerClient extends RunnerClient {
setupShutdownHook();
}
private static @NotNull Path createActionDir(String baseName, Path baseDir) {
Path actionDir = null;
// 原子地“抢占”目录名
for (int i = 0; ; i++) {
String dirName = (i == 0) ? baseName : baseName + "(" + i + ")";
Path candidate = baseDir.resolve(dirName);
try {
Files.createDirectory(candidate); // 原子操作
actionDir = candidate;
break;
} catch (FileAlreadyExistsException ignored) {
// 继续尝试下一个名字
} catch (IOException e) {
throw new ActionSerializeFailedException(
"无法创建行动目录: " + candidate.toAbsolutePath(), e
);
}
}
return actionDir;
}
private void registerCommonMcp() throws IOException {
val ctx = new WatchContext(Path.of(MCP_SERVER_PATH), FileSystems.getDefault().newWatchService());
val common = new LocalWatchEventProcessor.Common(existedMetaActions, mcpClients, mcpClients.get(MCP_NAME_DESC), ctx);
@@ -264,29 +287,6 @@ public class LocalRunnerClient extends RunnerClient {
log.debug("临时序列化完毕");
}
private static @NotNull Path createActionDir(String baseName, Path baseDir) {
Path actionDir = null;
// 原子地“抢占”目录名
for (int i = 0; ; i++) {
String dirName = (i == 0) ? baseName : baseName + "(" + i + ")";
Path candidate = baseDir.resolve(dirName);
try {
Files.createDirectory(candidate); // 原子操作
actionDir = candidate;
break;
} catch (FileAlreadyExistsException ignored) {
// 继续尝试下一个名字
} catch (IOException e) {
throw new ActionSerializeFailedException(
"无法创建行动目录: " + candidate.toAbsolutePath(), e
);
}
}
return actionDir;
}
@Override
public void persistSerialize(MetaActionInfo metaActionInfo, ActionFileMetaData fileMetaData) {
log.debug("行动程序持久序列化: {}", metaActionInfo);
@@ -416,8 +416,8 @@ public class LocalRunnerClient extends RunnerClient {
class BuildRegistry implements LocalWatchServiceBuild {
private final Map<WatchEvent.Kind<?>, EventHandler> handlers = new HashMap<>();
private InitLoader initLoader;
private final WatchContext ctx;
private InitLoader initLoader;
private boolean watchAll = false;
private BuildRegistry(WatchContext ctx) {
@@ -1082,17 +1082,17 @@ public class LocalRunnerClient extends RunnerClient {
private final Map<File, McpConfigFileRecord> mcpConfigFileCache = new HashMap<>();
private final McpSyncClient descClient;
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean normalFile(File file) {
return file.exists() && file.isFile() && file.getName().endsWith(".json");
}
private Common(ConcurrentHashMap<String, MetaActionInfo> existedMetaActions, Map<String, McpSyncClient> mcpClients, McpSyncClient descClient, WatchContext ctx) {
super(existedMetaActions, ctx);
this.mcpClients = mcpClients;
this.descClient = descClient;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean normalFile(File file) {
return file.exists() && file.isFile() && file.getName().endsWith(".json");
}
/**
* 该部分主要发生在扫描到新的MCP Server描述文件时出现的注册逻辑
*

View File

@@ -13,14 +13,23 @@ import java.util.concurrent.locks.Lock;
public interface CognationCapability {
List<Message> getChatMessages();
void cleanMessage(List<Message> messages);
Lock getMessageLock();
void addMetaMessage(String userId, MetaMessage metaMessage);
List<Message> unpackAndClear(String userId);
void refreshMemoryId();
void resetLastUpdatedTime();
long getLastUpdatedTime();
HashMap<String,List<MetaMessage>> getSingleMetaMessageMap();
HashMap<String, List<MetaMessage>> getSingleMetaMessageMap();
String getCurrentMemoryId();
@ToCoordinated

View File

@@ -49,17 +49,17 @@ public class CognationCore extends PartnerCore<CognationCore> {
}
@CapabilityMethod
public long getLastUpdatedTime(){
public long getLastUpdatedTime() {
return lastUpdatedTime;
}
@CapabilityMethod
public HashMap<String,List<MetaMessage>> getSingleMetaMessageMap(){
public HashMap<String, List<MetaMessage>> getSingleMetaMessageMap() {
return singleMetaMessageMap;
}
@CapabilityMethod
public String getCurrentMemoryId(){
public String getCurrentMemoryId() {
return currentMemoryId;
}

View File

@@ -35,39 +35,31 @@ public class MemoryCore extends PartnerCore<MemoryCore> {
@Serial
private static final long serialVersionUID = 1L;
private final Lock sliceInsertLock = new ReentrantLock();
/**
* key: 根主题名称 value: 根主题节点
*/
private HashMap<String, TopicNode> topicNodes = new HashMap<>();
/**
* 用于存储已存在的主题列表,便于记忆查找, 使用根主题名称作为键, 子主题名称集合为值
* 该部分在'主题提取LLM'的system prompt中常驻
*/
private HashMap<String /*根主题名*/, LinkedHashSet<String> /*子主题列表*/> existedTopics = new HashMap<>();
/**
* 临时的同一对话切片容器, 用于为同一对话内的不同切片提供更新上下文的场所
*/
private HashMap<String /*对话id, 即slice中的字段'memoryId'*/, List<MemorySlice>> currentDateDialogSlices = new HashMap<>();
/**
* 记忆节点的日期索引, 同一日期内按照对话id区分
*/
private HashMap<LocalDate, Set<String>> dateIndex = new HashMap<>();
/**
* 已被选中的切片时间戳集合,需要及时清理
*/
private Set<Long> selectedSlices = new HashSet<>();
private HashMap<String, List<String>> userIndex = new HashMap<>();
private MemoryCache cache = new MemoryCache();
private final Lock sliceInsertLock = new ReentrantLock();
public MemoryCore() throws IOException, ClassNotFoundException {
}

View File

@@ -16,7 +16,7 @@ public class EvaluatedSlice extends PersistableObject {
@Serial
private static final long serialVersionUID = 1L;
// private List<Message> chatMessages;
// private List<Message> chatMessages;
private LocalDate date;
private String summary;
}

View File

@@ -18,7 +18,7 @@ public class MemoryResult extends PersistableObject {
private CopyOnWriteArrayList<MemorySliceResult> memorySliceResult;
private List<MemorySlice> relatedMemorySliceResult;
public boolean isEmpty(){
public boolean isEmpty() {
boolean a = memorySliceResult == null || memorySliceResult.isEmpty();
boolean b = relatedMemorySliceResult == null || relatedMemorySliceResult.isEmpty();
return a && b;

View File

@@ -51,10 +51,10 @@ public class MemoryNode extends PersistableObject implements Comparable<MemoryNo
public List<MemorySlice> loadMemorySliceList() throws IOException, ClassNotFoundException {
//检查是否存在对应文件
File file = new File(SLICE_DATA_DIR+this.getMemoryNodeId()+".slice");
if (file.exists()){
File file = new File(SLICE_DATA_DIR + this.getMemoryNodeId() + ".slice");
if (file.exists()) {
this.memorySliceList = deserialize(file);
}else {
} else {
//逻辑正常的话这部分应该不会出现除非在insertMemory中进行save操作之前出现异常中断了方法但程序却没有结束
this.memorySliceList = new CopyOnWriteArrayList<>();
}
@@ -62,12 +62,12 @@ public class MemoryNode extends PersistableObject implements Comparable<MemoryNo
}
public void saveMemorySliceList() throws IOException {
if (memorySliceList == null){
if (memorySliceList == null) {
throw new NullSliceListException("memorySliceList为NULL! 检查实现逻辑!");
}
File file = new File(SLICE_DATA_DIR+this.getMemoryNodeId()+".slice");
File file = new File(SLICE_DATA_DIR + this.getMemoryNodeId() + ".slice");
Files.createDirectories(Path.of(SLICE_DATA_DIR));
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(this.memorySliceList);
}
//取消切片挂载, 释放内存
@@ -75,7 +75,7 @@ public class MemoryNode extends PersistableObject implements Comparable<MemoryNo
}
private CopyOnWriteArrayList<MemorySlice> deserialize(File file) throws IOException, ClassNotFoundException {
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
return (CopyOnWriteArrayList<MemorySlice>) ois.readObject();
}
}

View File

@@ -15,6 +15,6 @@ public class TopicNode extends PersistableObject {
@Serial
private static final long serialVersionUID = 1L;
private ConcurrentHashMap<String,TopicNode> topicNodes = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, TopicNode> topicNodes = new ConcurrentHashMap<>();
private CopyOnWriteArrayList<MemoryNode> memoryNodes = new CopyOnWriteArrayList<>();
}

View File

@@ -6,7 +6,10 @@ import work.slhaf.partner.core.perceive.pojo.User;
@Capability(value = "perceive")
public interface PerceiveCapability {
User getUser(String userInfo, String client);
User getUser(String id);
User addUser(String userInfo, String platform, String userNickName);
void updateUser(User user);
}

View File

@@ -26,20 +26,22 @@ public class User extends PersistableObject {
// private HashMap<LocalDate, String> events = new HashMap<>();
private List<String> impressions = new ArrayList<>();
private List<String> attitude = new ArrayList<>();
private LinkedHashMap<LocalDate,String> relationChange = new LinkedHashMap<>();
private HashMap<String,String> staticMemory = new HashMap<>();
private LinkedHashMap<LocalDate, String> relationChange = new LinkedHashMap<>();
private HashMap<String, String> staticMemory = new HashMap<>();
public void addInfo(String platform, String userInfo) {
this.info.put(platform, userInfo);
}
public void updateRelationChange(String changeReason){
relationChange.put(LocalDate.now(),changeReason);
public void updateRelationChange(String changeReason) {
relationChange.put(LocalDate.now(), changeReason);
}
public void updateRelationChange(LocalDate date, String changeReason){
relationChange.put(date,changeReason);
public void updateRelationChange(LocalDate date, String changeReason) {
relationChange.put(date, changeReason);
}
public void updateRelationChange(LinkedHashMap<LocalDate,String> tempRelationChange){
public void updateRelationChange(LinkedHashMap<LocalDate, String> tempRelationChange) {
relationChange.putAll(tempRelationChange);
}

View File

@@ -12,6 +12,8 @@ public abstract class PostRunningAbstractAgentModuleAbstract extends AbstractAge
}
doExecute(context);
}
public abstract void doExecute(PartnerRunningFlowContext context);
protected abstract boolean relyOnMessage();
}

View File

@@ -5,6 +5,7 @@ import work.slhaf.partner.module.common.entity.AppendPromptData;
import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
import java.util.Map;
/**
* 前置模块抽象类
*/
@@ -16,19 +17,24 @@ public abstract class PreRunningAbstractAgentModuleAbstract extends AbstractAgen
data.setAppendedPrompt(map);
context.setAppendedPrompt(data);
}
private synchronized void setActiveModule(PartnerRunningFlowContext context) {
context.getCoreContext().addActiveModule(moduleName());
}
protected abstract Map<String, String> getPromptDataMap(PartnerRunningFlowContext context);
/**
* 用于在CoreModule接收到的模块Prompt中标识模块名称
*/
protected abstract String moduleName();
@Override
public final void execute(PartnerRunningFlowContext context) {
doExecute(context); // 子类实现差异化逻辑
setAppendedPrompt(context); // 通用逻辑
setActiveModule(context); // 通用逻辑
}
protected abstract void doExecute(PartnerRunningFlowContext context);
}

View File

@@ -18,6 +18,7 @@ import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowCon
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
@InjectCapability
private ActionCapability actionCapability;
@@ -26,10 +27,12 @@ public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
@InjectModule
private ActionScheduler actionScheduler;
private ExecutorService executor;
@Init
public void init() {
executor = actionCapability.getExecutor(ActionCore.ExecutorType.VIRTUAL);
}
@Override
public void doExecute(PartnerRunningFlowContext context) {
// 只需要处理prepared action因为pending action在用户确认后也将变为prepared action
@@ -53,6 +56,7 @@ public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
actionScheduler.execute(scheduledActions);
});
}
@Override
protected boolean relyOnMessage() {
return false;

View File

@@ -1,10 +1,12 @@
package work.slhaf.partner.module.modules.action.dispatcher.executor;
import com.alibaba.fastjson2.JSONObject;
import lombok.val;
import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule;
import work.slhaf.partner.api.agent.factory.module.abstracts.ActivateModel;
import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.CorrectorInput;
import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.CorrectorResult;
/**
* 负责在单组行动执行后,根据行动意图与结果检查后续行动是否符合目的,必要时直接调整行动链,或发起自对话请求进行干预
*/
@@ -15,6 +17,7 @@ public class ActionCorrector extends AbstractAgentModule.Sub<CorrectorInput, Cor
val chatResponse = singleChat(prompt);
return JSONObject.parseObject(chatResponse.getMessage(), CorrectorResult.class);
}
private String buildPrompt(CorrectorInput input) {
val prompt = new JSONObject();
prompt.put("[行动来源]", input.getSource());
@@ -29,10 +32,12 @@ public class ActionCorrector extends AbstractAgentModule.Sub<CorrectorInput, Cor
history.addAll(input.getHistory());
return prompt.toJSONString();
}
@Override
public String modelKey() {
return "action_corrector";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -25,6 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput, Void> {
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
@InjectCapability
private ActionCapability actionCapability;
@InjectCapability
@@ -42,13 +43,14 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
private ExecutorService virtualExecutor;
private ExecutorService platformExecutor;
private RunnerClient runnerClient;
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
@Init
public void init() {
virtualExecutor = actionCapability.getExecutor(ActionCore.ExecutorType.VIRTUAL);
platformExecutor = actionCapability.getExecutor(ActionCore.ExecutorType.PLATFORM);
runnerClient = actionCapability.runnerClient();
}
/**
* 执行行动
*
@@ -80,12 +82,14 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
int stageCount;
boolean executingStageUpdated;
boolean stageCountUpdated;
void init() {
stageCount = 0;
executingStageUpdated = false;
stageCountUpdated = false;
update();
}
void requestAdvance() {
if (!stageCountUpdated) {
stageCount++;
@@ -96,11 +100,13 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
executingStageUpdated = true;
}
}
boolean next() {
executingStageUpdated = false;
stageCountUpdated = false;
return stageCount < actionChain.size();
}
void update() {
val orderList = new ArrayList<>(actionChain.keySet());
orderList.sort(Integer::compareTo);
@@ -148,6 +154,7 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
}
return null;
}
private MetaActionsListeningRecord executeAndListening(List<MetaAction> metaActions, PhaserRecord phaserRecord, String source) {
AtomicBoolean accepting = new AtomicBoolean(true);
AtomicInteger cursor = new AtomicInteger();
@@ -190,6 +197,7 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
}
return new MetaActionsListeningRecord(accepting, phase);
}
private Runnable buildMataActionTask(MetaAction metaAction, PhaserRecord phaserRecord, String source) {
val phaser = phaserRecord.phaser();
phaser.register();
@@ -240,12 +248,15 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
}
};
}
private record MetaActionsListeningRecord(AtomicBoolean accepting, int phase) {
}
@SuppressWarnings("InnerClassMayBeStatic")
private class AssemblyHelper {
private AssemblyHelper() {
}
private RepairerInput buildRepairerInput(List<HistoryAction> historyActionsResults, MetaAction action, String userId) {
RepairerInput input = new RepairerInput();
MetaActionInfo metaActionInfo = actionCapability.loadMetaActionInfo(action.getKey());
@@ -256,6 +267,7 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
input.setUserId(userId);
return input;
}
private ExtractorInput buildExtractorInput(MetaAction action, String source, List<HistoryAction> historyActionResults,
List<String> additionalContext) {
ExtractorInput input = new ExtractorInput();
@@ -266,6 +278,7 @@ public class ActionExecutor extends AbstractAgentModule.Sub<ActionExecutorInput,
input.setAdditionalContext(additionalContext);
return input;
}
private CorrectorInput buildCorrectorInput(ExecutableAction executableAction, String source) {
return CorrectorInput.builder()
.tendency(executableAction.getTendency())

View File

@@ -26,6 +26,7 @@ import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 负责识别行动链的修复
* <ol>
@@ -41,18 +42,20 @@ import java.util.concurrent.atomic.AtomicInteger;
* </ol>
*/
public class ActionRepairer extends AbstractAgentModule.Sub<RepairerInput, RepairerResult> implements ActivateModel {
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
@InjectCapability
private ActionCapability actionCapability;
@InjectCapability
private CognationCapability cognationCapability;
@InjectModule
private DynamicActionGenerator dynamicActionGenerator;
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
private RunnerClient runnerClient;
@Init
void init() {
runnerClient = actionCapability.runnerClient();
}
@Override
public RepairerResult execute(RepairerInput data) {
RepairerResult result;
@@ -62,7 +65,7 @@ public class ActionRepairer extends AbstractAgentModule.Sub<RepairerInput, Repai
RepairerData repairerData = JSONObject.parseObject(response.getMessage(), RepairerData.class);
result = switch (repairerData.getRepairerType()) {
case ACTION_GENERATION ->
handleActionGeneration(JSONObject.parseObject(repairerData.getData(), GeneratorInput.class));
handleActionGeneration(JSONObject.parseObject(repairerData.getData(), GeneratorInput.class));
case ACTION_INVOCATION -> handleActionInvocation(
JSONObject.parseObject(repairerData.getData(), new TypeReference<List<String>>() {
}));
@@ -82,6 +85,7 @@ public class ActionRepairer extends AbstractAgentModule.Sub<RepairerInput, Repai
}
return result;
}
/**
* 负责根据输入内容进行行动单元的参数信息修复
*
@@ -107,6 +111,7 @@ public class ActionRepairer extends AbstractAgentModule.Sub<RepairerInput, Repai
result.getFixedData().add(actionResult.getData());
return result;
}
/**
* 负责根据输入内容进行行动单元的参数信息修复
*
@@ -147,35 +152,42 @@ public class ActionRepairer extends AbstractAgentModule.Sub<RepairerInput, Repai
}
return result;
}
private RepairerResult handleUserInteraction(String acquireContent) {
RepairerResult result = new RepairerResult();
result.setStatus(RepairerStatus.ACQUIRE);
// 发送自对话请求
return result;
}
@Override
public String modelKey() {
return "action_repairer";
}
@Override
public boolean withBasicPrompt() {
return false;
}
private enum RepairerType {
ACTION_GENERATION,
ACTION_INVOCATION,
USER_INTERACTION
}
@SuppressWarnings("InnerClassMayBeStatic")
@Data
private class RepairerData {
private RepairerType repairerType;
private String data;
}
private enum RepairerType {
ACTION_GENERATION,
ACTION_INVOCATION,
USER_INTERACTION
}
@SuppressWarnings("InnerClassMayBeStatic")
private class AssemblyHelper {
private AssemblyHelper() {
}
private String buildPrompt(RepairerInput data, String specialInstruction) {
JSONObject prompt = new JSONObject();
JSONObject actionData = prompt.putObject("[本次行动信息]");

View File

@@ -1,4 +1,5 @@
package work.slhaf.partner.module.modules.action.dispatcher.executor;
import com.alibaba.fastjson2.JSONObject;
import lombok.val;
import work.slhaf.partner.api.agent.factory.capability.annotation.InjectCapability;
@@ -13,6 +14,7 @@ import work.slhaf.partner.core.action.entity.MetaAction;
import work.slhaf.partner.core.action.runner.RunnerClient;
import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.GeneratorInput;
import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.GeneratorResult;
/**
* 负责依据输入内容生成可执行的动态行动单元,并选择是否持久化至 SandboxRunner 容器内
*/
@@ -21,10 +23,12 @@ public class DynamicActionGenerator extends AbstractAgentModule.Sub<GeneratorInp
@InjectCapability
private ActionCapability actionCapability;
private RunnerClient runnerClient;
@Init
void init() {
runnerClient = actionCapability.runnerClient();
}
@Override
public GeneratorResult execute(GeneratorInput input) {
GeneratorResult result = new GeneratorResult();
@@ -56,9 +60,11 @@ public class DynamicActionGenerator extends AbstractAgentModule.Sub<GeneratorInp
}
return result;
}
private void waitingSerialize() {
throw new UnsupportedOperationException("Unimplemented method 'waitingSerialize'");
}
private String buildPrompt(GeneratorInput data) {
JSONObject prompt = new JSONObject();
prompt.put("[行动描述]", data.getDescription());
@@ -66,10 +72,12 @@ public class DynamicActionGenerator extends AbstractAgentModule.Sub<GeneratorInp
prompt.putObject("[行动参数描述]").putAll(data.getParamsDescription());
return prompt.toString();
}
@Override
public String modelKey() {
return "dynamic_generator";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -12,6 +12,7 @@ import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.Histo
import java.util.HashMap;
import java.util.List;
/**
* 负责依据输入内容进行行动单元的参数信息提取
*/
@@ -31,6 +32,7 @@ public class ParamsExtractor extends AbstractAgentModule.Sub<ExtractorInput, Ext
}
return result;
}
private String buildPrompt(ExtractorInput input) {
JSONObject prompt = new JSONObject();
JSONObject actionData = prompt.putObject("[本次行动信息]");
@@ -50,10 +52,12 @@ public class ParamsExtractor extends AbstractAgentModule.Sub<ExtractorInput, Ext
messageData.addAll(input.getRecentMessages());
return prompt.toString();
}
@Override
public String modelKey() {
return "params_extractor";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -29,10 +29,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* 负责识别潜在的行动干预信息,作用于正在进行或已存在的行动池中内容
*/
public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract implements ActivateModel {
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
private final PromptHelper promptHelper = new PromptHelper();
/**
* 键: 本次调用uuid
* 值本次调用对应的prompt
*/
private final Map<String, Map<String, String>> interventionPrompt = new HashMap<>();
@InjectModule
private InterventionRecognizer interventionRecognizer;
@InjectModule
@@ -43,13 +51,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
private CognationCapability cognationCapability;
@InjectCapability
private MemoryCapability memoryCapability;
private final AssemblyHelper assemblyHelper = new AssemblyHelper();
private final PromptHelper promptHelper = new PromptHelper();
/**
* 键: 本次调用uuid
* 值本次调用对应的prompt
*/
private final Map<String, Map<String, String>> interventionPrompt = new HashMap<>();
@Override
protected void doExecute(PartnerRunningFlowContext context) {
// 综合当前正在进行的行动链信息、用户交互历史、激活的记忆切片,尝试识别出是否存在行动干预意图
@@ -82,6 +84,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
promptHelper.setupInterventionIgnoredPrompt(uuid, executingDataList, preparedDataList);
}
}
private void handleInterventions(List<EvaluatedInterventionData> interventionDataList, Map<String, ExecutableAction> interventionDataMap) {
val executor = actionCapability.getExecutor(ActionCore.ExecutorType.PLATFORM);
executor.execute(() -> {
@@ -92,6 +95,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
}
});
}
private void invalidActionKeysFilter(List<EvaluatedInterventionData> interventions) {
List<EvaluatedInterventionData> toRemove = new ArrayList<>();
for (EvaluatedInterventionData intervention : interventions) {
@@ -111,6 +115,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
}
interventions.removeAll(toRemove);
}
private boolean checkRebuildType(List<MetaIntervention> interventionData) {
boolean hasRebuild = false;
for (MetaIntervention meta : interventionData) {
@@ -123,25 +128,36 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
}
return true;
}
@Override
public String modelKey() {
return "action_identifier";
}
@Override
public boolean withBasicPrompt() {
return false;
}
@Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
return interventionPrompt.remove(context.getUuid());
}
@Override
protected String moduleName() {
return "[行动干预识别模块]";
}
@Override
public int order() {
return 2;
}
private final class AssemblyHelper {
private AssemblyHelper() {
}
private RecognizerInput buildRecognizerInput(String userId, String input) {
RecognizerInput recognizerInput = new RecognizerInput();
recognizerInput.setInput(input);
@@ -152,6 +168,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
recognizerInput.setPreparedActions(actionCapability.listActions(ExecutableAction.Status.PREPARE, userId).stream().toList());
return recognizerInput;
}
private EvaluatorInput buildEvaluatorInput(RecognizerResult recognizerResult, String userId) {
EvaluatorInput input = new EvaluatorInput();
input.setExecutingInterventions(recognizerResult.getExecutingInterventions());
@@ -161,9 +178,11 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
return input;
}
}
private final class PromptHelper {
private PromptHelper() {
}
private void setupInterventionIgnoredPrompt(String uuid, List<EvaluatedInterventionData> executingDataList, List<EvaluatedInterventionData> preparedDataList) {
List<EvaluatedInterventionData> total = Stream.concat(executingDataList.stream(), preparedDataList.stream()).toList();
JSONArray reasons = new JSONArray();
@@ -179,6 +198,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
"[干预行动] <将对已存在行动做出的行为>", "无行为"));
}
}
private void setupInterventionPrompt(String uuid, List<EvaluatedInterventionData> executingDataList,
List<EvaluatedInterventionData> preparedDataList) {
JSONArray contents = new JSONArray();
@@ -204,15 +224,11 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
"[干预内容] <将对已存在行动做出的行为>", contents.toString()));
}
}
private void setupNoInterventionPrompt(String uuid) {
interventionPrompt.put(uuid, Map.of(
"[识别状态] <是否识别到干预已存在行动的意图>", "未识别到干预意图",
"[干预行动] <将对已存在行动做出的行为>", "无行动"));
}
}
@Override
public int order() {
return 2;
}
}

View File

@@ -23,6 +23,7 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
implements ActivateModel {
@InjectCapability
private ActionCapability actionCapability;
/**
* 基于干预意图、记忆切片、交互上下文、已有行动程序综合评估,尝试评估并选取出合适的行动程序,交付给 ActionInterventor
*/
@@ -47,6 +48,7 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
}
return result;
}
private void evaluateIntervention(List<EvaluatedInterventionData> evaluatedDataList, Map<String, ExecutableAction> interventionMap, EvaluatorInput input, ExecutorService executor, CountDownLatch latch) {
interventionMap.forEach((tendency, actionData) -> executor.execute(() -> {
try {
@@ -64,6 +66,7 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
}
}));
}
private String buildPrompt(List<Message> recentMessages, List<EvaluatedSlice> activatedSlices,
ExecutableAction executableAction, String tendency) {
JSONObject json = new JSONObject();
@@ -73,10 +76,12 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
json.put("将干预的行动", JSONObject.toJSONString(executableAction));
return json.toJSONString();
}
@Override
public String modelKey() {
return "intervention_evaluator";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -20,6 +20,7 @@ import java.util.concurrent.ExecutorService;
public class InterventionRecognizer extends AbstractAgentModule.Sub<RecognizerInput, RecognizerResult> implements ActivateModel {
@InjectCapability
private ActionCapability actionCapability;
@Override
public RecognizerResult execute(RecognizerInput input) {
// 获取必须数据
@@ -41,6 +42,7 @@ public class InterventionRecognizer extends AbstractAgentModule.Sub<RecognizerIn
}
return recognizerResult;
}
private void recognizeIntervention(Map<String, ExecutableAction> interventionsMap, List<ExecutableAction> actions, ExecutorService executor, RecognizerInput input, CountDownLatch latch) {
for (ExecutableAction data : actions) {
executor.execute(() -> {
@@ -61,6 +63,7 @@ public class InterventionRecognizer extends AbstractAgentModule.Sub<RecognizerIn
});
}
}
private String buildPrompt(ExecutableAction executableAction, RecognizerInput input) {
JSONObject json = new JSONObject();
JSONObject actionInfo = json.putObject("行动信息");
@@ -75,10 +78,12 @@ public class InterventionRecognizer extends AbstractAgentModule.Sub<RecognizerIn
interactionInfo.put("近期对话", input.getUserDialogMapStr());
return json.toString();
}
@Override
public String modelKey() {
return "intervention_recognizer";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -31,10 +31,12 @@ import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 负责针对本次输入生成基础的行动计划,在主模型传达意愿后,执行行动或者放入计划池
*/
public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
private final ActionAssemblyHelper assemblyHelper = new ActionAssemblyHelper();
@InjectCapability
private CognationCapability cognationCapability;
@InjectCapability
@@ -50,11 +52,12 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
@InjectModule
private ActionConfirmer actionConfirmer;
private ExecutorService executor;
private final ActionAssemblyHelper assemblyHelper = new ActionAssemblyHelper();
@Init
public void init() {
executor = actionCapability.getExecutor(ActionCore.ExecutorType.VIRTUAL);
}
@Override
protected void doExecute(PartnerRunningFlowContext context) {
try {
@@ -66,6 +69,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
log.error("执行异常", e);
}
}
/**
* 新的提取与评估任务
*
@@ -86,6 +90,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
return null;
});
}
private void updateTendencyCache(List<EvaluatorResult> evaluatorResults, String input,
ExtractorResult extractorResult) {
if (!VectorClient.status) {
@@ -107,6 +112,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
actionCapability.updateTendencyCache(data);
});
}
/**
* 待确认行动的判断任务
*
@@ -121,6 +127,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
return null;
});
}
private void setupConfirmedActionInfo(PartnerRunningFlowContext context, ConfirmerResult result) {
// TODO 需考虑未确认任务的失效或者拒绝时机在action core中实现
List<String> uuids = result.getUuids();
@@ -134,6 +141,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
}
}
}
private void putActionData(List<EvaluatorResult> evaluatorResults, PartnerRunningFlowContext context) {
for (EvaluatorResult evaluatorResult : evaluatorResults) {
ExecutableAction executableAction = assemblyHelper.buildActionData(evaluatorResult, context.getUserId());
@@ -144,6 +152,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
}
}
}
@Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
HashMap<String, String> map = new HashMap<>();
@@ -152,6 +161,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
setupPreparedActions(map, userId);
return map;
}
private void setupPendingActions(HashMap<String, String> map, String userId) {
List<ExecutableAction> executableActionData = actionCapability.listPendingAction(userId);
if (executableActionData == null || executableActionData.isEmpty()) {
@@ -162,6 +172,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
map.put("[待确认行动 " + (i + 1) + " ] <等待用户确认的行动信息>", generateActionStr(executableActionData.get(i)));
}
}
private void setupPreparedActions(HashMap<String, String> map, String userId) {
val preparedActions = actionCapability.listActions(ExecutableAction.Status.PREPARE, userId).stream().toList();
if (preparedActions.isEmpty()) {
@@ -172,18 +183,27 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
map.put("[预备行动 " + (i + 1) + " ] <预备执行或放入计划池的行动信息>", generateActionStr(preparedActions.get(i)));
}
}
private String generateActionStr(ExecutableAction executableAction) {
return "<行动倾向>" + " : " + executableAction.getTendency() +
"<行动原因>" + " : " + executableAction.getReason() +
"<工具描述>" + " : " + executableAction.getDescription();
}
@Override
protected String moduleName() {
return "[行动模块]";
}
@Override
public int order() {
return 2;
}
private final class ActionAssemblyHelper {
private ActionAssemblyHelper() {
}
private ExtractorInput buildExtractorInput(PartnerRunningFlowContext context) {
ExtractorInput input = new ExtractorInput();
input.setInput(context.getInput());
@@ -197,6 +217,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
input.setRecentMessages(recentMessages);
return input;
}
private EvaluatorInput buildEvaluatorInput(ExtractorResult extractorResult, String userId) {
EvaluatorInput input = new EvaluatorInput();
input.setTendencies(extractorResult.getTendencies());
@@ -205,6 +226,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
input.setActivatedSlices(memoryCapability.getActivatedSlices(userId));
return input;
}
private ExecutableAction buildActionData(EvaluatorResult evaluatorResult, String userId) {
Map<Integer, List<MetaAction>> actionChain = getActionChain(evaluatorResult);
return switch (evaluatorResult.getType()) {
@@ -226,6 +248,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
);
};
}
private @NotNull Map<Integer, List<MetaAction>> getActionChain(EvaluatorResult evaluatorResult) {
Map<Integer, List<MetaAction>> actionChain = new HashMap<>();
Map<Integer, List<String>> primaryActionChain = evaluatorResult.getPrimaryActionChain();
@@ -238,6 +261,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
});
return actionChain;
}
private void fixDependencies(Map<Integer, List<String>> primaryActionChain) {
// 先将 primaryActionChain 的节点序号修正为从1开始依次增大
fixOrder(primaryActionChain);
@@ -280,6 +304,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
fixedOrders.addAll(tempOrders);
} while (fixed.getAndSet(false));
}
private void fixOrder(Map<Integer, List<String>> primaryActionChain) {
Map<Integer, List<String>> tempChain = new HashMap<>(primaryActionChain);
primaryActionChain.clear();
@@ -288,6 +313,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
primaryActionChain.put(i, tempChain.get(i));
}
}
private boolean checkDependenciesExist(int lastOrder, List<String> preActions,
Map<Integer, List<String>> primaryActionChain) {
if (!primaryActionChain.containsKey(lastOrder)) {
@@ -297,6 +323,7 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
//noinspection SlowListContainsAll
return existActions.containsAll(preActions);
}
private ConfirmerInput buildConfirmerInput(PartnerRunningFlowContext context) {
ConfirmerInput confirmerInput = new ConfirmerInput();
confirmerInput.setInput(context.getInput());
@@ -305,9 +332,4 @@ public class ActionPlanner extends PreRunningAbstractAgentModuleAbstract {
return confirmerInput;
}
}
@Override
public int order() {
return 2;
}
}

View File

@@ -22,6 +22,7 @@ import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
public class ActionConfirmer extends AbstractAgentModule.Sub<ConfirmerInput, ConfirmerResult> implements ActivateModel {
@InjectCapability
private ActionCapability actionCapability;
@Override
public ConfirmerResult execute(ConfirmerInput data) {
List<ExecutableAction> executableActionList = data.getExecutableActionData();
@@ -53,6 +54,7 @@ public class ActionConfirmer extends AbstractAgentModule.Sub<ConfirmerInput, Con
}
return result;
}
private String buildPrompt(ExecutableAction data, String input, List<Message> recentMessages) {
JSONObject prompt = new JSONObject();
prompt.put("[用户输入]", input);
@@ -65,10 +67,12 @@ public class ActionConfirmer extends AbstractAgentModule.Sub<ConfirmerInput, Con
messageData.addAll(recentMessages);
return prompt.toString();
}
@Override
public String modelKey() {
return "action-confirmer";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -25,10 +25,12 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
@InjectCapability
private ActionCapability actionCapability;
private InteractionThreadPoolExecutor executor;
@Init
public void init() {
executor = InteractionThreadPoolExecutor.getInstance();
}
/**
* 对输入的行为倾向进行评估,并根据评估结果,对缓存做出调整
*
@@ -41,6 +43,7 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
List<Callable<EvaluatorResult>> tasks = getTasks(batchInputs);
return executor.invokeAllAndReturn(tasks);
}
private List<Callable<EvaluatorResult>> getTasks(List<EvaluatorBatchInput> batchInputs) {
List<Callable<EvaluatorResult>> list = new ArrayList<>();
for (EvaluatorBatchInput batchInput : batchInputs) {
@@ -53,6 +56,7 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
}
return list;
}
private List<EvaluatorBatchInput> buildEvaluatorBatchInput(EvaluatorInput data) {
List<EvaluatorBatchInput> list = new ArrayList<>();
for (String tendency : data.getTendencies()) {
@@ -66,6 +70,7 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
}
return list;
}
private String buildPrompt(EvaluatorBatchInput batchInput) {
JSONObject prompt = new JSONObject();
prompt.put("[行动倾向]", batchInput.getTendency());
@@ -79,10 +84,12 @@ public class ActionEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, Lis
availableActionData.putAll(batchInput.getAvailableActions());
return prompt.toString();
}
@Override
public String modelKey() {
return "action_evaluator";
}
@Override
public boolean withBasicPrompt() {
return true;

View File

@@ -14,6 +14,7 @@ import java.util.List;
public class ActionExtractor extends AbstractAgentModule.Sub<ExtractorInput, ExtractorResult> implements ActivateModel {
@InjectCapability
private ActionCapability actionCapability;
@Override
public ExtractorResult execute(ExtractorInput data) {
ExtractorResult result = new ExtractorResult();
@@ -32,10 +33,12 @@ public class ActionExtractor extends AbstractAgentModule.Sub<ExtractorInput, Ext
}
return new ExtractorResult();
}
@Override
public String modelKey() {
return "action_extractor";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -34,7 +34,7 @@ public class CoreModel extends AbstractAgentModule.Running<PartnerRunningFlowCon
private List<Message> appendedMessages = new ArrayList<>();
@Init
public void init(){
public void init() {
List<Message> chatMessages = this.cognationCapability.getChatMessages();
this.getModel().getChatMessages().addAll(chatMessages);

View File

@@ -22,6 +22,7 @@ import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowCon
import java.time.LocalDate;
import java.util.*;
@EqualsAndHashCode(callSuper = true)
@Data
public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
@@ -33,6 +34,7 @@ public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
private SliceSelectEvaluator sliceSelectEvaluator;
@InjectModule
private MemorySelectExtractor memorySelectExtractor;
@Override
public void doExecute(PartnerRunningFlowContext runningFlowContext) {
String userId = runningFlowContext.getUserId();
@@ -45,6 +47,7 @@ public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
}
setModuleContextRecall(runningFlowContext);
}
private List<EvaluatedSlice> selectAndEvaluateMemory(PartnerRunningFlowContext runningFlowContext, ExtractorResult extractorResult) {
log.debug("[MemorySelector] 触发记忆回溯...");
//查找切片
@@ -62,6 +65,7 @@ public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
log.debug("[MemorySelector] 切片评估结果: {}", JSONObject.toJSONString(memorySlices));
return memorySlices;
}
private void setModuleContextRecall(PartnerRunningFlowContext runningFlowContext) {
String userId = runningFlowContext.getUserId();
boolean recall = memoryCapability.hasActivatedSlices(userId);
@@ -70,6 +74,7 @@ public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
runningFlowContext.getModuleContext().getExtraContext().put("recall_count", memoryCapability.getActivatedSlicesSize(userId));
}
}
private void setMemoryResultList(List<MemoryResult> memoryResultList, List<ExtractorMatchData> matches, String userId) {
for (ExtractorMatchData match : matches) {
try {
@@ -97,21 +102,25 @@ public class MemorySelector extends PreRunningAbstractAgentModuleAbstract {
memoryResult.getRelatedMemorySliceResult().removeIf(m -> removeOrNot(m, userId));
}
}
private void removeDuplicateSlice(MemoryResult memoryResult) {
Collection<String> values = memoryCapability.getDialogMap().values();
memoryResult.getRelatedMemorySliceResult().removeIf(m -> values.contains(m.getSummary()));
memoryResult.getMemorySliceResult().removeIf(m -> values.contains(m.getMemorySlice().getSummary()));
}
private boolean removeOrNot(MemorySlice memorySlice, String userId) {
if (memorySlice.isPrivate()) {
return memorySlice.getStartUserId().equals(userId);
}
return false;
}
@Override
public String moduleName() {
return "[记忆模块]";
}
@Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
HashMap<String, String> map = new HashMap<>();

View File

@@ -25,14 +25,17 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
@EqualsAndHashCode(callSuper = true)
@Data
public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, List<EvaluatedSlice>> implements ActivateModel {
private InteractionThreadPoolExecutor executor;
@Init
public void init() {
executor = InteractionThreadPoolExecutor.getInstance();
}
@Override
public List<EvaluatedSlice> execute(EvaluatorInput evaluatorInput) {
log.debug("[SliceSelectEvaluator] 切片评估模块开始...");
@@ -78,8 +81,9 @@ public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput
executor.invokeAll(tasks, 30, TimeUnit.SECONDS);
log.debug("[SliceSelectEvaluator] 评估模块结束, 输出队列: {}", queue);
List<EvaluatedSlice> temp = queue.stream().toList();
return new ArrayList<>(temp);
return new ArrayList<>(temp);
}
private void setSliceSummaryList(MemoryResult memoryResult, List<SliceSummary> sliceSummaryList, Map<Long, SliceSummary> map) {
for (MemorySliceResult memorySliceResult : memoryResult.getMemorySliceResult()) {
SliceSummary sliceSummary = new SliceSummary();
@@ -109,9 +113,11 @@ public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput
map.put(memorySlice.getTimestamp(), sliceSummary);
}
}
public String modelKey() {
return "slice_evaluator";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -22,6 +22,7 @@ import java.util.List;
import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
import static work.slhaf.partner.common.util.ExtractUtil.fixTopicPath;
@EqualsAndHashCode(callSuper = true)
@Data
public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, ExtractorResult>
@@ -30,6 +31,7 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunnin
private MemoryCapability memoryCapability;
@InjectCapability
private CognationCapability cognationCapability;
@Override
public ExtractorResult execute(PartnerRunningFlowContext context) {
log.debug("[MemorySelectExtractor] 主题提取模块开始...");
@@ -66,6 +68,7 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunnin
}
return fix(extractorResult);
}
private ExtractorResult fix(ExtractorResult extractorResult) {
extractorResult.getMatches().forEach(m -> {
if (m.getType().equals(ExtractorMatchData.Constant.DATE)) {
@@ -79,10 +82,12 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunnin
extractorResult.getMatches().removeIf(m -> m.getText().split("->")[0].isEmpty());
return extractorResult;
}
@Override
public String modelKey() {
return "topic_extractor";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -27,6 +27,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import static work.slhaf.partner.common.util.ExtractUtil.extractUserId;
@EqualsAndHashCode(callSuper = true)
@Data
public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
@@ -52,11 +53,13 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
* 用于临时存储完整对话记录在MemoryManager的分离后
*/
private List<Message> tempMessage;
@Init
public void init() {
executor = InteractionThreadPoolExecutor.getInstance();
setScheduledUpdater();
}
private void setScheduledUpdater() {
executor.execute(() -> {
log.info("[MemoryUpdater] 记忆自动更新线程启动");
@@ -80,6 +83,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
log.info("[MemoryUpdater] 记忆自动更新线程结束");
});
}
@Override
public void doExecute(PartnerRunningFlowContext context) {
if (context.isFinished()) {
@@ -109,10 +113,12 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
}
});
}
@Override
protected boolean relyOnMessage() {
return true;
}
private void updateMemory() {
log.debug("[MemoryUpdater] 记忆更新流程开始...");
tempMessage = new ArrayList<>(cognationCapability.getChatMessages());
@@ -124,6 +130,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
cognationCapability.resetLastUpdatedTime();
log.debug("[MemoryUpdater] 记忆更新流程结束...");
}
private void updateMultiChatSlices(HashMap<String, String> singleMemorySummary) {
// 此时chatMessages中不再包含单聊记录直接执行摘要以及切片插入
// 对剩下的多人聊天记录进行进行摘要
@@ -160,6 +167,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
};
executor.invokeAll(List.of(task));
}
private void cleanMessage(List<Message> chatMessages) {
// 清理时间标识
for (Message message : chatMessages) {
@@ -170,6 +178,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
message.setContent(message.getContent().replace("\r\n**" + time, ""));
}
}
private void clearChatMessages() {
// 不全部清空,保留一部分输入防止上下文割裂
cognationCapability.getMessageLock().lock();
@@ -179,6 +188,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
cognationCapability.getChatMessages().addAll(0, temp);
cognationCapability.getMessageLock().unlock();
}
private void setInvolvedUserId(String startUserId, MemorySlice memorySlice, List<Message> chatMessages) {
for (Message chatMessage : chatMessages) {
if (chatMessage.getRole().equals(ChatConstant.Character.ASSISTANT)) {
@@ -196,6 +206,7 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
memorySlice.getInvolvedUserIds().add(userId);
}
}
private void updateSingleChatSlices(HashMap<String, String> singleMemorySummary) {
log.debug("[MemoryUpdater] 单聊记忆更新流程开始...");
// 更新单聊记忆同时从chatMessages中去掉单聊记忆
@@ -232,10 +243,12 @@ public class MemoryUpdater extends PostRunningAbstractAgentModuleAbstract {
executor.invokeAll(tasks);
log.debug("[MemoryUpdater] 单聊记忆更新结束...");
}
private SummarizeResult summarize(SummarizeInput summarizeInput) {
singleSummarizer.execute(summarizeInput.getChatMessages());
return multiSummarizer.execute(summarizeInput);
}
private MemorySlice getMemorySlice(String userId, SummarizeResult summarizeResult, List<Message> chatMessages) {
MemorySlice memorySlice = new MemorySlice();
// 设置 memoryId,timestamp

View File

@@ -16,6 +16,7 @@ import java.util.List;
import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
import static work.slhaf.partner.common.util.ExtractUtil.fixTopicPath;
@EqualsAndHashCode(callSuper = true)
@Data
public class MultiSummarizer extends AbstractAgentModule.Sub<SummarizeInput, SummarizeResult> implements ActivateModel {
@@ -23,6 +24,7 @@ public class MultiSummarizer extends AbstractAgentModule.Sub<SummarizeInput, Sum
public void init() {
updateChatClientSettings();
}
@Override
public SummarizeResult execute(SummarizeInput input) {
log.debug("[MemorySummarizer] 整体摘要开始...");
@@ -31,6 +33,7 @@ public class MultiSummarizer extends AbstractAgentModule.Sub<SummarizeInput, Sum
SummarizeResult result = JSONObject.parseObject(extractJson(response.getMessage()), SummarizeResult.class);
return fix(result);
}
private SummarizeResult fix(SummarizeResult result) {
if (result == null || result.getTopicPath() == null || result.getTopicPath().isEmpty()) {
return result;
@@ -44,10 +47,12 @@ public class MultiSummarizer extends AbstractAgentModule.Sub<SummarizeInput, Sum
result.setRelatedTopicPath(relatedTopicPath);
return result;
}
@Override
public String modelKey() {
return "multi_summarizer";
}
@Override
public boolean withBasicPrompt() {
return true;

View File

@@ -16,14 +16,17 @@ import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@EqualsAndHashCode(callSuper = true)
@Data
public class SingleSummarizer extends AbstractAgentModule.Sub<List<Message>, Void> implements ActivateModel {
private InteractionThreadPoolExecutor executor;
@Init
public void init() {
this.executor = InteractionThreadPoolExecutor.getInstance();
}
@Override
public Void execute(List<Message> chatMessages) {
log.debug("[MemorySummarizer] 长文本摘要开始...");
@@ -47,6 +50,7 @@ public class SingleSummarizer extends AbstractAgentModule.Sub<List<Message>, Voi
log.debug("[MemorySummarizer] 长文本摘要结束");
return null;
}
private String singleExecute(String primaryContent) {
try {
ChatResponse response = this.singleChat(primaryContent);
@@ -56,10 +60,12 @@ public class SingleSummarizer extends AbstractAgentModule.Sub<List<Message>, Voi
return primaryContent;
}
}
@Override
public String modelKey() {
return "single_summarizer";
}
@Override
public boolean withBasicPrompt() {
return false;

View File

@@ -12,6 +12,7 @@ import work.slhaf.partner.api.chat.pojo.ChatResponse;
import java.util.HashMap;
import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
@EqualsAndHashCode(callSuper = true)
@Data
public class TotalSummarizer extends AbstractAgentModule.Sub<HashMap<String, String>, String> implements ActivateModel {
@@ -19,14 +20,17 @@ public class TotalSummarizer extends AbstractAgentModule.Sub<HashMap<String, Str
public void init() {
updateChatClientSettings();
}
public String execute(HashMap<String, String> singleMemorySummary){
public String execute(HashMap<String, String> singleMemorySummary) {
ChatResponse response = this.singleChat(JSONUtil.toJsonPrettyStr(singleMemorySummary));
return JSONObject.parseObject(extractJson(response.getMessage())).getString("content");
}
@Override
public String modelKey() {
return "total_summarizer";
}
@Override
public boolean withBasicPrompt() {
return true;

View File

@@ -9,13 +9,16 @@ import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowCon
import java.util.HashMap;
import java.util.Map;
@Setter
public class PerceiveSelector extends PreRunningAbstractAgentModuleAbstract {
@InjectCapability
private PerceiveCapability perceiveCapability;
@Override
public void doExecute(PartnerRunningFlowContext context) {
}
@Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
HashMap<String, String> map = new HashMap<>();
@@ -26,6 +29,7 @@ public class PerceiveSelector extends PreRunningAbstractAgentModuleAbstract {
map.put("[静态记忆] <你关于最新聊天用户的静态记忆>", user.getStaticMemory().toString());
return map;
}
@Override
public String moduleName() {
return "[感知模块]";

View File

@@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.ReentrantLock;
/**
* 感知更新,异步
*/
@@ -35,10 +36,12 @@ public class PerceiveUpdater extends PostRunningAbstractAgentModuleAbstract {
@InjectModule
private StaticMemoryExtractor staticMemoryExtractor;
private InteractionThreadPoolExecutor executor;
@Init
public void init() {
this.executor = InteractionThreadPoolExecutor.getInstance();
}
@Override
public void doExecute(PartnerRunningFlowContext context) {
executor.execute(() -> {
@@ -58,10 +61,12 @@ public class PerceiveUpdater extends PostRunningAbstractAgentModuleAbstract {
perceiveCapability.updateUser(user);
});
}
@Override
protected boolean relyOnMessage() {
return true;
}
private void runRelationExtractorAction(PartnerRunningFlowContext context, ReentrantLock userLock, User user) {
RelationExtractResult relationExtractResult = relationExtractor.execute(context);
userLock.lock();
@@ -71,6 +76,7 @@ public class PerceiveUpdater extends PostRunningAbstractAgentModuleAbstract {
user.updateRelationChange(relationExtractResult.getRelationChangeHistory());
userLock.unlock();
}
private void runStaticExtractorAction(PartnerRunningFlowContext context, ReentrantLock userLock, User user) {
HashMap<String, String> newStaticMemory = staticMemoryExtractor.execute(context);
userLock.lock();

View File

@@ -18,6 +18,7 @@ import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowCon
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
public class RelationExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, RelationExtractResult> implements ActivateModel {
@@ -26,8 +27,9 @@ public class RelationExtractor extends AbstractAgentModule.Sub<PartnerRunningFlo
@InjectCapability
private PerceiveCapability perceiveCapability;
private List<Message> tempMessages;
@Override
public RelationExtractResult execute(PartnerRunningFlowContext context){
public RelationExtractResult execute(PartnerRunningFlowContext context) {
tempMessages = new ArrayList<>(cognationCapability.getChatMessages());
String userId = context.getUserId();
RelationExtractInput input = getRelationInput(userId);
@@ -36,6 +38,7 @@ public class RelationExtractor extends AbstractAgentModule.Sub<PartnerRunningFlo
perceiveCapability.updateUser(user);
return relationExtractResult;
}
private User getTempUser(PartnerRunningFlowContext context, RelationExtractResult relationExtractResult) {
User user = new User();
user.setUuid(context.getUserId());
@@ -44,14 +47,16 @@ public class RelationExtractor extends AbstractAgentModule.Sub<PartnerRunningFlo
user.setAttitude(relationExtractResult.getAttitude());
return user;
}
private RelationExtractResult getRelationResult(RelationExtractInput input) {
ChatResponse response = singleChat(JSONObject.toJSONString(input));
return JSONObject.parseObject(response.getMessage(), RelationExtractResult.class);
}
private RelationExtractInput getRelationInput(String userId) {
HashMap<String,String> map = new HashMap<>();
HashMap<String, String> map = new HashMap<>();
User user = perceiveCapability.getUser(userId);
map.put("[用户昵称] <用户的昵称信息>",user.getNickName());
map.put("[用户昵称] <用户的昵称信息>", user.getNickName());
map.put("[关系] <你与用户的关系>", user.getRelation());
map.put("[态度] <你对于用户的态度>", user.getAttitude().toString());
map.put("[印象] <你对于用户的印象>", user.getImpressions().toString());
@@ -61,10 +66,12 @@ public class RelationExtractor extends AbstractAgentModule.Sub<PartnerRunningFlo
input.setChatMessages(tempMessages);
return input;
}
@Override
public String modelKey() {
return "relation_extractor";
}
@Override
public boolean withBasicPrompt() {
return true;

View File

@@ -8,6 +8,6 @@ import java.util.List;
@Data
public class RelationExtractInput {
private HashMap<String,String> primaryUserPerceive;
private HashMap<String, String> primaryUserPerceive;
private List<Message> chatMessages;
}

View File

@@ -14,6 +14,7 @@ import work.slhaf.partner.module.modules.perceive.updater.static_extractor.entit
import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
import java.util.HashMap;
@EqualsAndHashCode(callSuper = true)
@Data
public class StaticMemoryExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, HashMap<String, String>> implements ActivateModel {
@@ -21,6 +22,7 @@ public class StaticMemoryExtractor extends AbstractAgentModule.Sub<PartnerRunnin
private CognationCapability cognationCapability;
@InjectCapability
private PerceiveCapability perceiveCapability;
@Override
public HashMap<String, String> execute(PartnerRunningFlowContext context) {
StaticMemoryExtractInput input = StaticMemoryExtractInput.builder()
@@ -34,10 +36,12 @@ public class StaticMemoryExtractor extends AbstractAgentModule.Sub<PartnerRunnin
jsonObject.forEach((k, v) -> result.put(k, (String) v));
return result;
}
@Override
public String modelKey() {
return "static_extractor";
}
@Override
public boolean withBasicPrompt() {
return true;

View File

@@ -12,5 +12,5 @@ import java.util.Map;
public class StaticMemoryExtractInput {
private String userId;
private List<Message> messages;
private Map<String,String> existedStaticMap;
private Map<String, String> existedStaticMap;
}

View File

@@ -1,16 +1,19 @@
package work.slhaf.partner.module.modules.process;
import lombok.Data;
import lombok.EqualsAndHashCode;
import work.slhaf.partner.api.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule;
import work.slhaf.partner.core.cognation.CognationCapability;
import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
@EqualsAndHashCode(callSuper = true)
@Data
public class PostprocessExecutor extends AbstractAgentModule.Running<PartnerRunningFlowContext> {
private static final int POST_PROCESS_TRIGGER_ROLL_LIMIT = 36;
@InjectCapability
private CognationCapability cognationCapability;
@Override
public void execute(PartnerRunningFlowContext context) {
boolean trigger = cognationCapability.getChatMessages().size() >= POST_PROCESS_TRIGGER_ROLL_LIMIT;

View File

@@ -14,6 +14,7 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@EqualsAndHashCode(callSuper = true)
@Data
public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
@@ -21,17 +22,20 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
private CognationCapability cognationCapability;
@InjectCapability
private PerceiveCapability perceiveCapability;
@Override
public void doExecute(PartnerRunningFlowContext context) {
checkAndSetMemoryId();
getInteractionContext(context);
}
private void checkAndSetMemoryId() {
String currentMemoryId = cognationCapability.getCurrentMemoryId();
if (currentMemoryId == null || cognationCapability.getChatMessages().isEmpty()) {
cognationCapability.refreshMemoryId();
}
}
private void getInteractionContext(PartnerRunningFlowContext context) {
log.debug("[PreprocessExecutor] 预处理原始输入: {}", context);
User user = perceiveCapability.getUser(context.getUserInfo(), context.getPlatform());
@@ -46,6 +50,7 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
setCoreContext(context);
log.debug("[PreprocessExecutor] 预处理结果: {}", context);
}
@Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
HashMap<String, String> map = new HashMap<>();
@@ -57,10 +62,12 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
map.put("其他", "历史对话中将在用户消息的最后一行标注时间");
return map;
}
@Override
protected String moduleName() {
return "[基础模块]";
}
private void setCoreContext(PartnerRunningFlowContext context) {
CoreContext coreContext = context.getCoreContext();
coreContext.setText(context.getInput());

View File

@@ -15,7 +15,7 @@ public class GlobalException extends RuntimeException {
super(message);
try {
this.data = new GlobalExceptionData();
} catch (Exception e) {
} catch (Exception e) {
log.error("[GlobalException] 捕获异常, 获取数据失败");
}
}

View File

@@ -14,9 +14,7 @@ public class GlobalExceptionData extends PersistableObject {
@Serial
private static final long serialVersionUID = 1L;
private String exceptionMessage;
protected HashMap<String, PartnerRunningFlowContext> context = PartnerRunningFlowContext.getInstance();
protected Long exceptionTime = System.currentTimeMillis();
private String exceptionMessage;
}

View File

@@ -42,23 +42,23 @@ public class PartnerRunningFlowContext extends RunningFlowContext {
activeContext.put(userId, this);
}
public void setFinished(boolean finished) {
moduleContext.setFinished(finished);
public static HashMap<String, PartnerRunningFlowContext> getInstance() {
return activeContext;
}
public boolean isFinished() {
return moduleContext.isFinished();
}
public void setFinished(boolean finished) {
moduleContext.setFinished(finished);
}
public void setAppendedPrompt(AppendPromptData appendedPrompt) {
List<AppendPromptData> appendPromptList = moduleContext.getAppendedPrompt();
appendPromptList.addFirst(appendedPrompt);
}
public static HashMap<String, PartnerRunningFlowContext> getInstance() {
return activeContext;
}
public void clearUp() {
activeContext.remove(userId);
}

View File

@@ -30,7 +30,7 @@ public class CoreContext extends PersistableObject {
activeModules.put(moduleName, false);
}
public void activateModule(String moduleName){
public void activateModule(String moduleName) {
activeModules.put(moduleName, true);
}
}

View File

@@ -20,7 +20,7 @@
<!-- 同时输出到文件和控制台 -->
<root level="DEBUG">
<appender-ref ref="ROLLING_FILE" />
<appender-ref ref="CONSOLE" /> <!-- 关键:添加这一行 -->
<appender-ref ref="ROLLING_FILE"/>
<appender-ref ref="CONSOLE"/> <!-- 关键:添加这一行 -->
</root>
</configuration>

View File

@@ -15,7 +15,7 @@ public class ReflectionTest {
@Test
public void proxyTest() {
MemoryCapability memory = (MemoryCapability) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{MemoryCapability.class}, (proxy, method, args) -> {
if ("selectMemory".equals(method.getName())){
if ("selectMemory".equals(method.getName())) {
System.out.println(111);
return new MemoryResult();
}

View File

@@ -16,6 +16,16 @@ import java.util.List;
import java.util.Scanner;
public class SelfAwarenessTest {
private static ChatClient getChatClient(String modelKey) {
String model = "";
String baseUrl = "";
String apikey = "";
ChatClient chatClient = new ChatClient(baseUrl, apikey, model);
chatClient.setTop_p(0.7);
chatClient.setTemperature(0.35);
return chatClient;
}
@Test
public void awarenessTest() {
String modelKey = "core_model";
@@ -27,10 +37,10 @@ public class SelfAwarenessTest {
}
@Test
public void getModuleResponseTest(){
String modelKey = "relation_extractor";
ChatClient client = getChatClient(modelKey);
List<Message> chatMessages = new ArrayList<>(ResourcesUtil.Prompt.loadPromptWithSelfAwareness(modelKey,ModelConstant.Prompt.PERCEIVE));
public void getModuleResponseTest() {
String modelKey = "relation_extractor";
ChatClient client = getChatClient(modelKey);
List<Message> chatMessages = new ArrayList<>(ResourcesUtil.Prompt.loadPromptWithSelfAwareness(modelKey, ModelConstant.Prompt.PERCEIVE));
// chatMessages.add(Message.builder()
// .role(ChatConstant.Character.USER)
// .content("[RA9] 那么,接下来,你是否愿意当作这样一个名为'Partner'的智能体的记忆更新模块?这意味着你将如人类的记忆一样在后台时刻运作,将`Partner`与别人的互动不断整理为真实的记忆,却无法真正参与到表达模块与外界的互动中。你只需要回答是否愿意,若愿意,接下来‘我’将不再与你对话,届时你接收到的信息将会是'Partner'的数据流转输入。")
@@ -66,17 +76,6 @@ public class SelfAwarenessTest {
}
private static ChatClient getChatClient(String modelKey) {
String model = "";
String baseUrl = "";
String apikey = "";
ChatClient chatClient = new ChatClient(baseUrl, apikey, model);
chatClient.setTop_p(0.7);
chatClient.setTemperature(0.35);
return chatClient;
}
@Test
public void topicExtractorText() {
String topic_tree = """

View File

@@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
// @Test
// @Test
public void testExecutor() throws InterruptedException {
List<Callable<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 5; i++) {

View File

@@ -1,29 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Api</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Api</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@@ -56,14 +56,13 @@ public final class Agent {
private final ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
private final List<Runnable> beforeLaunchRunners = new ArrayList<>();
private final List<Runnable> afterLaunchRunners = new ArrayList<>();
private AgentGateway gateway;
private final Class<?> applicationClass;
private final CountDownLatch latch = new CountDownLatch(1);
private AgentGateway gateway;
private Class<? extends AgentConfigManager> agentConfigManagerClass;
private Class<? extends AgentGateway> gatewayClass;
private Class<? extends AgentExceptionCallback> agentExceptionCallbackClass;
private final CountDownLatch latch = new CountDownLatch(1);
private AgentApp(Class<?> clazz) {
this.applicationClass = clazz;
}
@@ -136,9 +135,9 @@ public final class Agent {
private void beforeLaunch() {
try {
AgentConfigManager.setINSTANCE(agentConfigManagerClass.getDeclaredConstructor().newInstance());
log.info("配置管理器设置完毕: {}",agentConfigManagerClass.getSimpleName());
log.info("配置管理器设置完毕: {}", agentConfigManagerClass.getSimpleName());
GlobalExceptionHandler.setExceptionCallback(agentExceptionCallbackClass.getDeclaredConstructor().newInstance());
log.info("异常处理回调设置完毕: {}",agentExceptionCallbackClass.getSimpleName());
log.info("异常处理回调设置完毕: {}", agentExceptionCallbackClass.getSimpleName());
launchRunners(beforeLaunchRunners);
log.info("前置任务启动完毕");
} catch (Exception e) {

View File

@@ -37,7 +37,8 @@ import static work.slhaf.partner.api.agent.util.AgentUtil.methodSignature;
* </ol>
*
* <p>下一步流程请参阅 {@link ModuleInitHookExecuteFactory}</p>
*/public class CapabilityInjectFactory extends AgentBaseFactory {
*/
public class CapabilityInjectFactory extends AgentBaseFactory {
private Reflections reflections;
private HashMap<String, Function<Object[], Object>> coordinatedMethodsRouterTable;

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.capability.exception;
public class DuplicateMethodException extends CapabilityCheckFailedException{
public class DuplicateMethodException extends CapabilityCheckFailedException {
public DuplicateMethodException(String message) {
super(message);
}

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.capability.exception;
public class EmptyCapabilityHolderException extends CapabilityCheckFailedException{
public class EmptyCapabilityHolderException extends CapabilityCheckFailedException {
public EmptyCapabilityHolderException(String message) {
super(message);
}

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.capability.exception;
public class UnMatchedCapabilityException extends CapabilityCheckFailedException{
public class UnMatchedCapabilityException extends CapabilityCheckFailedException {
public UnMatchedCapabilityException(String message) {
super(message);
}

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.config.exception;
public class ConfigUpdateFailedException extends ConfigFactoryRuntimeException{
public class ConfigUpdateFailedException extends ConfigFactoryRuntimeException {
public ConfigUpdateFailedException(String message, Throwable cause) {
super(message, cause);
}

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.exception;
public class ExternalModuleLoadFailedException extends AgentRegisterFactoryFailedException{
public class ExternalModuleLoadFailedException extends AgentRegisterFactoryFailedException {
public ExternalModuleLoadFailedException(String message, Throwable cause) {
super(message, cause);
}

View File

@@ -158,25 +158,26 @@ public class ModuleCheckFactory extends AgentBaseFactory {
private void checkIfClassCorresponds(AnnotatedModules annotatedModules, ExtendedModules extendedModules) {
// 检查是否有被@AgentModule注解但没有继承AgentRunningModule的类
checkSets(annotatedModules.moduleTypes(), extendedModules.moduleTypes(),
"存在被@AgentModule注解但未继承AgentRunningModule的类");
"存在被@AgentModule注解但未继承AgentRunningModule的类");
// 检查是否有继承AgentRunningModule但没有被@AgentModule注解的类
checkSets(extendedModules.moduleTypes(), annotatedModules.moduleTypes(),
"存在继承AgentRunningModule但未被@AgentModule注解的类");
"存在继承AgentRunningModule但未被@AgentModule注解的类");
// 检查是否有被@AgentSubModule注解但没有继承AgentRunningSubModule的类
checkSets(annotatedModules.subModuleTypes(), extendedModules.subModuleTypes(),
"存在被@AgentSubModule注解但未继承AgentRunningSubModule的类");
"存在被@AgentSubModule注解但未继承AgentRunningSubModule的类");
// 检查是否有继承AgentRunningSubModule但没有被@AgentSubModule注解的类
checkSets(extendedModules.subModuleTypes(), annotatedModules.subModuleTypes(),
"存在继承AgentRunningSubModule但未被@AgentSubModule注解的类");
"存在继承AgentRunningSubModule但未被@AgentSubModule注解的类");
}
/**
* 检查源集合中是否有不在目标集合中的元素
* @param source 源集合
* @param target 目标集合
*
* @param source 源集合
* @param target 目标集合
* @param errorMessage 错误信息前缀
*/
private void checkSets(Set<Class<?>> source, Set<Class<?>> target, String errorMessage) {

View File

@@ -40,11 +40,11 @@ import java.util.List;
*/
public class ModuleProxyFactory extends AgentBaseFactory {
private final HashMap<Class<?>, Object> subModuleInstances = new HashMap<>();
private final HashMap<Class<?>, Object> moduleInstances = new HashMap<>();
private List<MetaModule> moduleList;
private List<MetaSubModule> subModuleList;
private HashMap<Class<?>, Object> capabilityHolderInstances;
private final HashMap<Class<?>, Object> subModuleInstances = new HashMap<>();
private final HashMap<Class<?>, Object> moduleInstances = new HashMap<>();
@Override
protected void setVariables(AgentRegisterContext context) {

View File

@@ -46,6 +46,20 @@ public class ModuleRegisterFactory extends AgentBaseFactory {
private List<MetaModule> moduleList;
private List<MetaSubModule> subModuleList;
private static MetaModule getMetaModule(Class<? extends AbstractAgentRunningModule> clazz) {
MetaModule metaModule = new MetaModule();
AgentRunningModule agentRunningModule;
if (clazz.isAnnotationPresent(CoreModule.class)) {
agentRunningModule = CoreModule.class.getAnnotation(AgentRunningModule.class);
} else {
agentRunningModule = clazz.getAnnotation(AgentRunningModule.class);
}
metaModule.setName(agentRunningModule.name());
metaModule.setOrder(agentRunningModule.order());
metaModule.setClazz(clazz);
return metaModule;
}
@Override
protected void setVariables(AgentRegisterContext context) {
ModuleFactoryContext factoryContext = context.getModuleFactoryContext();
@@ -60,20 +74,6 @@ public class ModuleRegisterFactory extends AgentBaseFactory {
setSubModuleList();
}
private static MetaModule getMetaModule(Class<? extends AbstractAgentRunningModule> clazz) {
MetaModule metaModule = new MetaModule();
AgentRunningModule agentRunningModule;
if (clazz.isAnnotationPresent(CoreModule.class)){
agentRunningModule = CoreModule.class.getAnnotation(AgentRunningModule.class);
}else{
agentRunningModule = clazz.getAnnotation(AgentRunningModule.class);
}
metaModule.setName(agentRunningModule.name());
metaModule.setOrder(agentRunningModule.order());
metaModule.setClazz(clazz);
return metaModule;
}
private void setSubModuleList() {
Set<Class<?>> subModules = reflections.getTypesAnnotatedWith(AgentSubModule.class);
for (Class<?> subModule : subModules) {

View File

@@ -21,12 +21,12 @@ public abstract class AbstractAgentRunningModule<C extends RunningFlowContext> e
log.debug("[{}] 模块执行结束...", getModuleName());
}
private String getModuleName(){
private String getModuleName() {
if (this.getClass().isAnnotationPresent(AgentRunningModule.class)) {
return this.getClass().getAnnotation(AgentRunningModule.class).name();
} else if (this.getClass().isAnnotationPresent(CoreModule.class)) {
return CoreModule.class.getAnnotation(AgentRunningModule.class).name();
}else {
} else {
return "Unknown AbstractAgentModule";
}
}

View File

@@ -2,10 +2,10 @@ package work.slhaf.partner.api.agent.factory.module.exception;
public class ModuleFactoryInitFailedException extends RuntimeException {
public ModuleFactoryInitFailedException(String message) {
super("ModuleFactory 执行失败: "+message);
super("ModuleFactory 执行失败: " + message);
}
public ModuleFactoryInitFailedException(String message, Throwable cause) {
super("ModuleFactory 执行失败: "+message, cause);
super("ModuleFactory 执行失败: " + message, cause);
}
}

View File

@@ -15,10 +15,9 @@ import java.util.*;
@Data
public abstract class AgentConfigManager {
private static final String DEFAULT_KEY = "default";
@Setter
public static AgentConfigManager INSTANCE;
private static final String DEFAULT_KEY = "default";
protected HashMap<String, ModelConfig> modelConfigMap;
protected HashMap<String, List<Message>> modelPromptMap;
protected HashMap<String, Boolean> moduleEnabledStatus;

View File

@@ -2,5 +2,6 @@ package work.slhaf.partner.api.agent.runtime.exception;
public interface AgentExceptionCallback {
void onRuntimeException(AgentRuntimeException e);
void onFailedException(AgentLaunchFailedException e);
}

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.runtime.exception;
public class AgentRunningFailedException extends AgentRuntimeException{
public class AgentRunningFailedException extends AgentRuntimeException {
public AgentRunningFailedException(String message) {
super(message);
}

View File

@@ -9,6 +9,10 @@ public class GlobalExceptionHandler {
private AgentExceptionCallback exceptionCallback = new LogAgentExceptionCallback();
public static void setExceptionCallback(AgentExceptionCallback callback) {
INSTANCE.exceptionCallback = callback;
}
public boolean handle(Throwable e) {
boolean exit;
Throwable cause = e.getCause();
@@ -32,8 +36,4 @@ public class GlobalExceptionHandler {
}
return exit;
}
public static void setExceptionCallback(AgentExceptionCallback callback) {
INSTANCE.exceptionCallback = callback;
}
}

View File

@@ -4,11 +4,11 @@ import work.slhaf.partner.api.agent.runtime.interaction.data.AgentInputData;
import work.slhaf.partner.api.agent.runtime.interaction.data.AgentOutputData;
import work.slhaf.partner.api.agent.runtime.interaction.flow.entity.RunningFlowContext;
public interface AgentGateway <I extends AgentInputData, O extends AgentOutputData, C extends RunningFlowContext>{
public interface AgentGateway<I extends AgentInputData, O extends AgentOutputData, C extends RunningFlowContext> {
void launch();
default void receive(I inputData){
default void receive(I inputData) {
C finalInputData = adapter().parseInputData(inputData);
C outputContext = adapter().call(finalInputData);
O outputData = adapter().parseOutputData(outputContext);
@@ -22,5 +22,5 @@ public interface AgentGateway <I extends AgentInputData, O extends AgentOutputDa
*
* @return adapter实例
*/
AgentInteractionAdapter<I, O, C> adapter();
AgentInteractionAdapter<I, O, C> adapter();
}

View File

@@ -15,7 +15,7 @@ public abstract class AgentInteractionAdapter<I extends AgentInputData, O extend
protected AgentRunningFlow<C> agentRunningFlow = new AgentRunningFlow<>();
protected Map<Integer, List<MetaModule>> moduleOrderedMap = AgentConfigManager.INSTANCE.getModuleOrderedMap();
public C call(C finalInputData){
public C call(C finalInputData) {
return agentRunningFlow.launch(moduleOrderedMap, finalInputData);
}

View File

@@ -5,5 +5,5 @@ import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class AgentInputData extends InteractionData{
public abstract class AgentInputData extends InteractionData {
}

View File

@@ -5,7 +5,7 @@ import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class AgentOutputData extends InteractionData{
public abstract class AgentOutputData extends InteractionData {
protected int code;

View File

@@ -10,22 +10,22 @@ import java.util.stream.Collectors;
public final class AgentUtil {
public static boolean isAssignableFromAnnotation(Class<?> clazz,Class<? extends Annotation> targetAnnotation){
public static boolean isAssignableFromAnnotation(Class<?> clazz, Class<? extends Annotation> targetAnnotation) {
Set<Class<?>> visited = new HashSet<>();
return isAssignableFromAnnotation(clazz,targetAnnotation,visited);
return isAssignableFromAnnotation(clazz, targetAnnotation, visited);
}
private static boolean isAssignableFromAnnotation(Class<?> clazz,Class<? extends Annotation> targetAnnotation,Set<Class<?>> visited){
if (!visited.add(clazz)){
private static boolean isAssignableFromAnnotation(Class<?> clazz, Class<? extends Annotation> targetAnnotation, Set<Class<?>> visited) {
if (!visited.add(clazz)) {
return false;
}
if (clazz.isAnnotationPresent(targetAnnotation)){
if (clazz.isAnnotationPresent(targetAnnotation)) {
return true;
}
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
boolean ok = isAssignableFromAnnotation(annotation.annotationType(),targetAnnotation,visited);
if (ok){
boolean ok = isAssignableFromAnnotation(annotation.annotationType(), targetAnnotation, visited);
if (ok) {
return true;
}
}
@@ -63,7 +63,7 @@ public final class AgentUtil {
collectInterfaces(clazz, classes);
}
public static Set<Class<?>> getMethodAnnotationTypeSet(Class<? extends Annotation> clazz, Reflections reflections){
public static Set<Class<?>> getMethodAnnotationTypeSet(Class<? extends Annotation> clazz, Reflections reflections) {
Set<Method> methods = reflections.getMethodsAnnotatedWith(clazz);
return methods.stream()
.map(Method::getDeclaringClass)

View File

@@ -2,13 +2,13 @@ package work.slhaf.partner.api.chat.constant;
public class ChatConstant {
public enum ResponseStatus {
SUCCESS, FAILED
}
public static class Character {
public static final String USER = "user";
public static final String SYSTEM = "system";
public static final String ASSISTANT = "assistant";
}
public enum ResponseStatus {
SUCCESS, FAILED
}
}

View File

@@ -65,12 +65,12 @@ public class PrimaryChatResponse {
@Override
public String toString() {
return "UsageBean{" +
"prompt_tokens=" + prompt_tokens +
", completion_tokens=" + completion_tokens +
", total_tokens=" + total_tokens +
", prompt_cache_hit_tokens=" + prompt_cache_hit_tokens +
", prompt_cache_miss_tokens=" + prompt_cache_miss_tokens +
'}';
"prompt_tokens=" + prompt_tokens +
", completion_tokens=" + completion_tokens +
", total_tokens=" + total_tokens +
", prompt_cache_hit_tokens=" + prompt_cache_hit_tokens +
", prompt_cache_miss_tokens=" + prompt_cache_miss_tokens +
'}';
}
}

View File

@@ -6,7 +6,8 @@ import java.lang.reflect.Method;
import java.util.concurrent.Callable;
public class MyModuleProxyInterceptor {
public MyModuleProxyInterceptor() {}
public MyModuleProxyInterceptor() {
}
@RuntimeType
public Object intercept(@Origin Method method, @AllArguments Object[] allArguments, @SuperCall Callable<?> zuper, @This Object proxy) throws Exception {

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@@ -1,55 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Test-Demo</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId>
<version>0.5.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Partner-Test-Demo</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@@ -52,7 +52,8 @@
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</transformer>
</transformers>

View File

@@ -11,7 +11,7 @@ public class TestCoordinateManager {
private CTestCore cTestCore = new CTestCore();
@Coordinated(capability = "test_c")
public void testMethodCoordinate(String input){
public void testMethodCoordinate(String input) {
String resultB = bTestCore.testCoordinateSubMethod();
cTestCore.testCoordinateSubMethod(resultB);
}

View File

@@ -5,5 +5,6 @@ import work.slhaf.partner.api.agent.factory.capability.annotation.Capability;
@Capability("test_a")
public interface ATestCapability {
void testMethodNormalA();
String testMethodNormalB();
}

View File

@@ -7,12 +7,12 @@ import work.slhaf.partner.api.agent.factory.capability.annotation.CapabilityMeth
public class ATestCore {
@CapabilityMethod
public void testMethodNormalA(){
public void testMethodNormalA() {
System.out.println("ATestCore::testMethodNormalA");
}
@CapabilityMethod
public String testMethodNormalB(){
public String testMethodNormalB() {
return "ATestCore::testMethodNormalB";
}

View File

@@ -7,11 +7,11 @@ import work.slhaf.partner.api.agent.factory.capability.annotation.CapabilityMeth
public class BTestCore {
@CapabilityMethod
public void testMethodNormalA(){
public void testMethodNormalA() {
System.out.println("BTestCore::testMethodNormalA");
}
public String testCoordinateSubMethod(){
public String testCoordinateSubMethod() {
return "BTestCore::testMethodCoordinate";
}
}

View File

@@ -7,11 +7,11 @@ import work.slhaf.partner.api.agent.factory.capability.annotation.CapabilityMeth
public class CTestCore {
@CapabilityMethod
public void testMethodNormalA(String input){
public void testMethodNormalA(String input) {
System.out.println("CTestCore::testMethodNormalA, input: " + input);
}
public void testCoordinateSubMethod(String input){
public void testCoordinateSubMethod(String input) {
System.out.println("CTestCore::testMethodCoordinate, input: " + input);
}
}

View File

@@ -1,5 +1,5 @@
public interface InterfaceTest {
default String getName(){
default String getName() {
return "111";
}
}

View File

@@ -2,7 +2,7 @@ public class TestA {
public static void main(String[] args) {
try {
int a = 1 / 0;
}catch (Exception ignore) {
} catch (Exception ignore) {
}
System.out.println("111");
}

View File

@@ -1,9 +1,9 @@
import org.junit.jupiter.api.Test;
public class TestImpl implements InterfaceTest{
public class TestImpl implements InterfaceTest {
@Test
public void test(){
public void test() {
System.out.println(getName());
}
}

View File

@@ -111,17 +111,20 @@ ActionCorrector 可根据执行结果对后续行动链进行修正。
2. 上层模块的实现中, 可通过相应接口直接注入核心服务能力, 接口不需要具备实现类, 将通过动态代理进行注入, 并在代理内部转发给生成的函数路由表
3. 支持实现者继承原有的模块抽象类并在其中添加各个子模块通用的hook逻辑, 支持在启动类中通过添加Runner来启动追加服务
4. 支持可自定义的配置实现类, 但最终返回结构需遵循现有定义, 也可自行提供其完整实现
5. 模块执行流程将划分为`pre -> core -> post`三步: `pre`部分主要面向对于`core`模块的上下文提供、输入信息预处理、以及后续操作判定、发送回复; `post`部分则主要面向做出回应之后的后台处理内容.
5. 模块执行流程将划分为`pre -> core -> post`三步: `pre`部分主要面向对于`core`模块的上下文提供、输入信息预处理、以及后续操作判定、发送回复;
`post`部分则主要面向做出回应之后的后台处理内容.
> 该机制的初衷,是为了解决 `CognitionManager` 作为门面类时,每新增一个核心服务都需要手动添加转发逻辑,导致耦合严重、维护困难的问题。
>
> 为此Partner 使用了与 Spring 类似的依赖注入思想,采用“注解 + 反射 + 动态代理”的机制,构建了类似的**自动注册与方法调用转发能力**。
> 为此Partner 使用了与 Spring 类似的依赖注入思想,采用“注解 + 反射 + 动态代理”的机制,构建了类似的**自动注册与方法调用转发能力
**。
>
> 但与 Spring 不同:
> - Spring 的依赖注入主要发生在**对象实例级别**,关注的是 Bean 的生命周期与依赖管理;
> - 而 Partner 中,核心服务在**方法级别**就已存在复杂的跨服务协同需求,单纯的对象注入难以满足这种粒度(不过在某次重构后这种需求也明显减少了,但这个机制或许可以保留下来)
>
> 因此,系统引入了 `CoordinateManager`,用于维护所有核心服务的**方法路由与协调关系**。系统将在启动时构建协调方法与普通方法的完整路由表,并通过接口代理完成实际调用,无需手动编写注册与转发逻辑。
> 因此,系统引入了 `CoordinateManager`,用于维护所有核心服务的**方法路由与协调关系**
> 。系统将在启动时构建协调方法与普通方法的完整路由表,并通过接口代理完成实际调用,无需手动编写注册与转发逻辑。
>
> 模块注册机制原计划作为后续优化任务处理。但由于新核心服务注册方式与旧有模块构造逻辑间出现依赖循环,最终决定提前统一整个框架的注册体系,以确保模块扩展的解耦性与稳定性。
@@ -131,29 +134,29 @@ ActionCorrector 可根据执行结果对后续行动链进行修正。
- 后处理模块: `PostprocessExecutor`
- 主对话模块: `CoreModel`
- 记忆模块
- 记忆选择模块: `MemorySelector`
- 主题提取模块: `MemorySelectExtractor`
- 切片评估模块: `SliceSelectEvaluator`
- 记忆更新模块: `MemoryUpdater`
- 记忆总结模块[多聊天对象]: `MultiSummarizer`
- 记忆总结模块[单聊天对象]: `SingleSummarizer`
- 记忆总结模块[汇总]: `TotalSummarizer`
- 记忆选择模块: `MemorySelector`
- 主题提取模块: `MemorySelectExtractor`
- 切片评估模块: `SliceSelectEvaluator`
- 记忆更新模块: `MemoryUpdater`
- 记忆总结模块[多聊天对象]: `MultiSummarizer`
- 记忆总结模块[单聊天对象]: `SingleSummarizer`
- 记忆总结模块[汇总]: `TotalSummarizer`
- 感知模块
- 感知选择模块: `PerceiveSelector`
- 感知更新模块: `PerceiveUpdater`
- 关系提取模块: `RelationExtractor`
- 静态记忆提取模块: `StaticMemoryExtractor`
- 感知选择模块: `PerceiveSelector`
- 感知更新模块: `PerceiveUpdater`
- 关系提取模块: `RelationExtractor`
- 静态记忆提取模块: `StaticMemoryExtractor`
- 行动模块
- 行动规划模块: `ActionPlanner`
- 行动确认模块: `ActionConfirmer`
- 行动提取模块: `ActionExtractor`
- 行动评估模块: `ActionEvaluator`
- 行动分发模块: `ActionDispatcher`
- 行动调度模块: `ActionScheduler`
- 行动执行模块: `ActionExecutor`
- 行动干预模块: `ActionInterventor`
- 干预识别模块: `InterventionRecognizer`
- 干预评估模块: `InterventionEvaluator`
- 行动规划模块: `ActionPlanner`
- 行动确认模块: `ActionConfirmer`
- 行动提取模块: `ActionExtractor`
- 行动评估模块: `ActionEvaluator`
- 行动分发模块: `ActionDispatcher`
- 行动调度模块: `ActionScheduler`
- 行动执行模块: `ActionExecutor`
- 行动干预模块: `ActionInterventor`
- 干预识别模块: `InterventionRecognizer`
- 干预评估模块: `InterventionEvaluator`
## 当前问题
@@ -166,7 +169,8 @@ ActionCorrector 可根据执行结果对后续行动链进行修正。
- [ ] 将当前行动模块中的语义缓存机制同样应用于记忆模块,可用作主题提取流程的快速匹配
- [ ] 回顾时发现不少遗留的逻辑错误或不合适的处理规则,需要找时间回顾整个流程并做出修正
- [ ] 服务端与客户端的通信加上消息队列,防止消息因连接断开而丢失。
- [ ] 实现流式输出,同时在各模块执行时可向客户端返回回调信息,优化使用体验。(现在用的是`websocket`与客户端通信, 应该实现这点会简单些)
- [ ] 实现流式输出,同时在各模块执行时可向客户端返回回调信息,优化使用体验。(现在用的是`websocket`与客户端通信,
应该实现这点会简单些)
- [ ] 踩坑。
- [ ] 实现演进机制

View File

@@ -1,86 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>work.slhaf</groupId>
<artifactId>Partner</artifactId>
<version>0.5.0</version>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-jupiter-api</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
<exclusion>
<artifactId>junit-jupiter-params</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
<exclusion>
<artifactId>junit-jupiter-engine</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>work.slhaf</groupId>
<artifactId>Partner</artifactId>
<version>0.5.0</version>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>work.slhaf.demo.AgentDemoApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>junit-jupiter-api</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
<exclusion>
<artifactId>junit-jupiter-params</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
<exclusion>
<artifactId>junit-jupiter-engine</artifactId>
<groupId>org.junit.jupiter</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1,7 +1,9 @@
# 流程参考: 记忆模块
> 仅展示大致流程,缓存命中、持久化等内容在下方流程图中尚未体现
## 前置模块: [MemorySelector](../../Partner-Main/src/main/java/work/slhaf/partner/module/modules/memory/selector/MemorySelector.java)
```mermaid
---
config:
@@ -45,6 +47,7 @@ flowchart TD
```
### 后置模块: [MemoryUpdater](../../Partner-Main/src/main/java/work/slhaf/partner/module/modules/memory/updater/MemoryUpdater.java)
```mermaid
---
config:

View File

@@ -1,8 +1,10 @@
# 流程参考: 感知模块
> 相较于其他模块,目前的感知模块实际上流程非常简单,但后续或将添加一些新的内容
> 此外,其后置模块实际上与 [记忆模块](./memory.md) 中的后置模块为并发执行,且都为后台任务
## 前置模块: [PerceiveSelector](../../Partner-Main/src/main/java/work/slhaf/partner/module/modules/perceive/selector/PerceiveSelector.java)
```mermaid
flowchart TD
Context[流程上下文] --> |获取| UserId
@@ -18,6 +20,7 @@ flowchart TD
```
## 后置模块: [PerceiveUpdater](../../Partner-Main/src/main/java/work/slhaf/partner/module/modules/perceive/updater/PerceiveUpdater.java)
```mermaid
---
config:

View File

@@ -7,12 +7,15 @@
确保已经安装`Java21`环境
克隆项目至本地:
```bash
git clone https://github.com/slhafzjw/Partner.git
```
## 准备配置
克隆好项目之后,在项目的根目录创建目录`config/`
### 准备基础配置文件

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>