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"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>

View File

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

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <parent>
<artifactId>Partner</artifactId> <artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId> <groupId>work.slhaf</groupId>

View File

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

View File

@@ -6,8 +6,8 @@ import work.slhaf.partner.common.thread.InteractionThreadPoolExecutor;
@Slf4j @Slf4j
public class DebugMonitor { public class DebugMonitor {
private InteractionThreadPoolExecutor executor;
private static DebugMonitor debugMonitor; private static DebugMonitor debugMonitor;
private InteractionThreadPoolExecutor executor;
public static void initialize() { public static void initialize() {
debugMonitor = new DebugMonitor(); debugMonitor = new DebugMonitor();
@@ -15,6 +15,13 @@ public class DebugMonitor {
debugMonitor.runMonitor(); debugMonitor.runMonitor();
} }
public static DebugMonitor getInstance() {
if (debugMonitor == null) {
initialize();
}
return debugMonitor;
}
private void runMonitor() { private void runMonitor() {
executor.execute(() -> { executor.execute(() -> {
while (true) { 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); return readPromptFromResources(SELF_AWARENESS_PATH);
} }
public static List<Message> loadPrompt(String modelKey,String promptType){ public static List<Message> loadPrompt(String modelKey, String promptType) {
return new ArrayList<>(readPromptFromResources(MODULE_PROMPT_PREFIX_PATH+promptType+"/"+modelKey+".json")); return new ArrayList<>(readPromptFromResources(MODULE_PROMPT_PREFIX_PATH + promptType + "/" + modelKey + ".json"));
} }
private static List<Message> readPromptFromResources(String filePath) { private static List<Message> readPromptFromResources(String filePath) {

View File

@@ -34,33 +34,28 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
public class ActionCore extends PartnerCore<ActionCore> { 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(); private final Lock cacheLock = new ReentrantLock();
// 由于当前的执行器逻辑实现,平台线程池大小不得小于 2这里规定为最小为 4 // 由于当前的执行器逻辑实现,平台线程池大小不得小于 2这里规定为最小为 4
private final ExecutorService platformExecutor = Executors private final ExecutorService platformExecutor = Executors
.newFixedThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 4)); .newFixedThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 4));
private final ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor(); private final ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
/** /**
* 已存在的行动程序,键格式为‘<MCP-ServerName>::<Tool-Name>’,值为 MCP Server 通过 Resources 相关渠道传递的行动程序元信息 * 已存在的行动程序,键格式为‘<MCP-ServerName>::<Tool-Name>’,值为 MCP Server 通过 Resources 相关渠道传递的行动程序元信息
*/ */
private final ConcurrentHashMap<String, MetaActionInfo> existedMetaActions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, MetaActionInfo> existedMetaActions = new ConcurrentHashMap<>();
private final List<PhaserRecord> phaserRecords = new ArrayList<>(); 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; private RunnerClient runnerClient;
public ActionCore() throws IOException, ClassNotFoundException { public ActionCore() throws IOException, ClassNotFoundException {

View File

@@ -119,6 +119,29 @@ public class LocalRunnerClient extends RunnerClient {
setupShutdownHook(); 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 { private void registerCommonMcp() throws IOException {
val ctx = new WatchContext(Path.of(MCP_SERVER_PATH), FileSystems.getDefault().newWatchService()); 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); val common = new LocalWatchEventProcessor.Common(existedMetaActions, mcpClients, mcpClients.get(MCP_NAME_DESC), ctx);
@@ -264,29 +287,6 @@ public class LocalRunnerClient extends RunnerClient {
log.debug("临时序列化完毕"); 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 @Override
public void persistSerialize(MetaActionInfo metaActionInfo, ActionFileMetaData fileMetaData) { public void persistSerialize(MetaActionInfo metaActionInfo, ActionFileMetaData fileMetaData) {
log.debug("行动程序持久序列化: {}", metaActionInfo); log.debug("行动程序持久序列化: {}", metaActionInfo);
@@ -416,8 +416,8 @@ public class LocalRunnerClient extends RunnerClient {
class BuildRegistry implements LocalWatchServiceBuild { class BuildRegistry implements LocalWatchServiceBuild {
private final Map<WatchEvent.Kind<?>, EventHandler> handlers = new HashMap<>(); private final Map<WatchEvent.Kind<?>, EventHandler> handlers = new HashMap<>();
private InitLoader initLoader;
private final WatchContext ctx; private final WatchContext ctx;
private InitLoader initLoader;
private boolean watchAll = false; private boolean watchAll = false;
private BuildRegistry(WatchContext ctx) { private BuildRegistry(WatchContext ctx) {
@@ -1082,17 +1082,17 @@ public class LocalRunnerClient extends RunnerClient {
private final Map<File, McpConfigFileRecord> mcpConfigFileCache = new HashMap<>(); private final Map<File, McpConfigFileRecord> mcpConfigFileCache = new HashMap<>();
private final McpSyncClient descClient; 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) { private Common(ConcurrentHashMap<String, MetaActionInfo> existedMetaActions, Map<String, McpSyncClient> mcpClients, McpSyncClient descClient, WatchContext ctx) {
super(existedMetaActions, ctx); super(existedMetaActions, ctx);
this.mcpClients = mcpClients; this.mcpClients = mcpClients;
this.descClient = descClient; this.descClient = descClient;
} }
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean normalFile(File file) {
return file.exists() && file.isFile() && file.getName().endsWith(".json");
}
/** /**
* 该部分主要发生在扫描到新的MCP Server描述文件时出现的注册逻辑 * 该部分主要发生在扫描到新的MCP Server描述文件时出现的注册逻辑
* *

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -51,10 +51,10 @@ public class MemoryNode extends PersistableObject implements Comparable<MemoryNo
public List<MemorySlice> loadMemorySliceList() throws IOException, ClassNotFoundException { public List<MemorySlice> loadMemorySliceList() throws IOException, ClassNotFoundException {
//检查是否存在对应文件 //检查是否存在对应文件
File file = new File(SLICE_DATA_DIR+this.getMemoryNodeId()+".slice"); File file = new File(SLICE_DATA_DIR + this.getMemoryNodeId() + ".slice");
if (file.exists()){ if (file.exists()) {
this.memorySliceList = deserialize(file); this.memorySliceList = deserialize(file);
}else { } else {
//逻辑正常的话这部分应该不会出现除非在insertMemory中进行save操作之前出现异常中断了方法但程序却没有结束 //逻辑正常的话这部分应该不会出现除非在insertMemory中进行save操作之前出现异常中断了方法但程序却没有结束
this.memorySliceList = new CopyOnWriteArrayList<>(); this.memorySliceList = new CopyOnWriteArrayList<>();
} }
@@ -62,12 +62,12 @@ public class MemoryNode extends PersistableObject implements Comparable<MemoryNo
} }
public void saveMemorySliceList() throws IOException { public void saveMemorySliceList() throws IOException {
if (memorySliceList == null){ if (memorySliceList == null) {
throw new NullSliceListException("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)); 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); 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 { 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(); return (CopyOnWriteArrayList<MemorySlice>) ois.readObject();
} }
} }

View File

@@ -15,6 +15,6 @@ public class TopicNode extends PersistableObject {
@Serial @Serial
private static final long serialVersionUID = 1L; 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<>(); private CopyOnWriteArrayList<MemoryNode> memoryNodes = new CopyOnWriteArrayList<>();
} }

View File

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

View File

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

View File

@@ -12,6 +12,8 @@ public abstract class PostRunningAbstractAgentModuleAbstract extends AbstractAge
} }
doExecute(context); doExecute(context);
} }
public abstract void doExecute(PartnerRunningFlowContext context); public abstract void doExecute(PartnerRunningFlowContext context);
protected abstract boolean relyOnMessage(); 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 work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
import java.util.Map; import java.util.Map;
/** /**
* 前置模块抽象类 * 前置模块抽象类
*/ */
@@ -16,19 +17,24 @@ public abstract class PreRunningAbstractAgentModuleAbstract extends AbstractAgen
data.setAppendedPrompt(map); data.setAppendedPrompt(map);
context.setAppendedPrompt(data); context.setAppendedPrompt(data);
} }
private synchronized void setActiveModule(PartnerRunningFlowContext context) { private synchronized void setActiveModule(PartnerRunningFlowContext context) {
context.getCoreContext().addActiveModule(moduleName()); context.getCoreContext().addActiveModule(moduleName());
} }
protected abstract Map<String, String> getPromptDataMap(PartnerRunningFlowContext context); protected abstract Map<String, String> getPromptDataMap(PartnerRunningFlowContext context);
/** /**
* 用于在CoreModule接收到的模块Prompt中标识模块名称 * 用于在CoreModule接收到的模块Prompt中标识模块名称
*/ */
protected abstract String moduleName(); protected abstract String moduleName();
@Override @Override
public final void execute(PartnerRunningFlowContext context) { public final void execute(PartnerRunningFlowContext context) {
doExecute(context); // 子类实现差异化逻辑 doExecute(context); // 子类实现差异化逻辑
setAppendedPrompt(context); // 通用逻辑 setAppendedPrompt(context); // 通用逻辑
setActiveModule(context); // 通用逻辑 setActiveModule(context); // 通用逻辑
} }
protected abstract void doExecute(PartnerRunningFlowContext 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.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract { public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
@InjectCapability @InjectCapability
private ActionCapability actionCapability; private ActionCapability actionCapability;
@@ -26,10 +27,12 @@ public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
@InjectModule @InjectModule
private ActionScheduler actionScheduler; private ActionScheduler actionScheduler;
private ExecutorService executor; private ExecutorService executor;
@Init @Init
public void init() { public void init() {
executor = actionCapability.getExecutor(ActionCore.ExecutorType.VIRTUAL); executor = actionCapability.getExecutor(ActionCore.ExecutorType.VIRTUAL);
} }
@Override @Override
public void doExecute(PartnerRunningFlowContext context) { public void doExecute(PartnerRunningFlowContext context) {
// 只需要处理prepared action因为pending action在用户确认后也将变为prepared action // 只需要处理prepared action因为pending action在用户确认后也将变为prepared action
@@ -53,6 +56,7 @@ public class ActionDispatcher extends PostRunningAbstractAgentModuleAbstract {
actionScheduler.execute(scheduledActions); actionScheduler.execute(scheduledActions);
}); });
} }
@Override @Override
protected boolean relyOnMessage() { protected boolean relyOnMessage() {
return false; return false;

View File

@@ -1,10 +1,12 @@
package work.slhaf.partner.module.modules.action.dispatcher.executor; package work.slhaf.partner.module.modules.action.dispatcher.executor;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import lombok.val; import lombok.val;
import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule; import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule;
import work.slhaf.partner.api.agent.factory.module.abstracts.ActivateModel; 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.CorrectorInput;
import work.slhaf.partner.module.modules.action.dispatcher.executor.entity.CorrectorResult; 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); val chatResponse = singleChat(prompt);
return JSONObject.parseObject(chatResponse.getMessage(), CorrectorResult.class); return JSONObject.parseObject(chatResponse.getMessage(), CorrectorResult.class);
} }
private String buildPrompt(CorrectorInput input) { private String buildPrompt(CorrectorInput input) {
val prompt = new JSONObject(); val prompt = new JSONObject();
prompt.put("[行动来源]", input.getSource()); prompt.put("[行动来源]", input.getSource());
@@ -29,10 +32,12 @@ public class ActionCorrector extends AbstractAgentModule.Sub<CorrectorInput, Cor
history.addAll(input.getHistory()); history.addAll(input.getHistory());
return prompt.toJSONString(); return prompt.toJSONString();
} }
@Override @Override
public String modelKey() { public String modelKey() {
return "action_corrector"; return "action_corrector";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return false; return false;

View File

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

View File

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

View File

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

View File

@@ -29,10 +29,18 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* 负责识别潜在的行动干预信息,作用于正在进行或已存在的行动池中内容 * 负责识别潜在的行动干预信息,作用于正在进行或已存在的行动池中内容
*/ */
public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract implements ActivateModel { 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 @InjectModule
private InterventionRecognizer interventionRecognizer; private InterventionRecognizer interventionRecognizer;
@InjectModule @InjectModule
@@ -43,13 +51,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
private CognationCapability cognationCapability; private CognationCapability cognationCapability;
@InjectCapability @InjectCapability
private MemoryCapability memoryCapability; 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 @Override
protected void doExecute(PartnerRunningFlowContext context) { protected void doExecute(PartnerRunningFlowContext context) {
// 综合当前正在进行的行动链信息、用户交互历史、激活的记忆切片,尝试识别出是否存在行动干预意图 // 综合当前正在进行的行动链信息、用户交互历史、激活的记忆切片,尝试识别出是否存在行动干预意图
@@ -82,6 +84,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
promptHelper.setupInterventionIgnoredPrompt(uuid, executingDataList, preparedDataList); promptHelper.setupInterventionIgnoredPrompt(uuid, executingDataList, preparedDataList);
} }
} }
private void handleInterventions(List<EvaluatedInterventionData> interventionDataList, Map<String, ExecutableAction> interventionDataMap) { private void handleInterventions(List<EvaluatedInterventionData> interventionDataList, Map<String, ExecutableAction> interventionDataMap) {
val executor = actionCapability.getExecutor(ActionCore.ExecutorType.PLATFORM); val executor = actionCapability.getExecutor(ActionCore.ExecutorType.PLATFORM);
executor.execute(() -> { executor.execute(() -> {
@@ -92,6 +95,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
} }
}); });
} }
private void invalidActionKeysFilter(List<EvaluatedInterventionData> interventions) { private void invalidActionKeysFilter(List<EvaluatedInterventionData> interventions) {
List<EvaluatedInterventionData> toRemove = new ArrayList<>(); List<EvaluatedInterventionData> toRemove = new ArrayList<>();
for (EvaluatedInterventionData intervention : interventions) { for (EvaluatedInterventionData intervention : interventions) {
@@ -111,6 +115,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
} }
interventions.removeAll(toRemove); interventions.removeAll(toRemove);
} }
private boolean checkRebuildType(List<MetaIntervention> interventionData) { private boolean checkRebuildType(List<MetaIntervention> interventionData) {
boolean hasRebuild = false; boolean hasRebuild = false;
for (MetaIntervention meta : interventionData) { for (MetaIntervention meta : interventionData) {
@@ -123,25 +128,36 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
} }
return true; return true;
} }
@Override @Override
public String modelKey() { public String modelKey() {
return "action_identifier"; return "action_identifier";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return false; return false;
} }
@Override @Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) { protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
return interventionPrompt.remove(context.getUuid()); return interventionPrompt.remove(context.getUuid());
} }
@Override @Override
protected String moduleName() { protected String moduleName() {
return "[行动干预识别模块]"; return "[行动干预识别模块]";
} }
@Override
public int order() {
return 2;
}
private final class AssemblyHelper { private final class AssemblyHelper {
private AssemblyHelper() { private AssemblyHelper() {
} }
private RecognizerInput buildRecognizerInput(String userId, String input) { private RecognizerInput buildRecognizerInput(String userId, String input) {
RecognizerInput recognizerInput = new RecognizerInput(); RecognizerInput recognizerInput = new RecognizerInput();
recognizerInput.setInput(input); recognizerInput.setInput(input);
@@ -152,6 +168,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
recognizerInput.setPreparedActions(actionCapability.listActions(ExecutableAction.Status.PREPARE, userId).stream().toList()); recognizerInput.setPreparedActions(actionCapability.listActions(ExecutableAction.Status.PREPARE, userId).stream().toList());
return recognizerInput; return recognizerInput;
} }
private EvaluatorInput buildEvaluatorInput(RecognizerResult recognizerResult, String userId) { private EvaluatorInput buildEvaluatorInput(RecognizerResult recognizerResult, String userId) {
EvaluatorInput input = new EvaluatorInput(); EvaluatorInput input = new EvaluatorInput();
input.setExecutingInterventions(recognizerResult.getExecutingInterventions()); input.setExecutingInterventions(recognizerResult.getExecutingInterventions());
@@ -161,9 +178,11 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
return input; return input;
} }
} }
private final class PromptHelper { private final class PromptHelper {
private PromptHelper() { private PromptHelper() {
} }
private void setupInterventionIgnoredPrompt(String uuid, List<EvaluatedInterventionData> executingDataList, List<EvaluatedInterventionData> preparedDataList) { private void setupInterventionIgnoredPrompt(String uuid, List<EvaluatedInterventionData> executingDataList, List<EvaluatedInterventionData> preparedDataList) {
List<EvaluatedInterventionData> total = Stream.concat(executingDataList.stream(), preparedDataList.stream()).toList(); List<EvaluatedInterventionData> total = Stream.concat(executingDataList.stream(), preparedDataList.stream()).toList();
JSONArray reasons = new JSONArray(); JSONArray reasons = new JSONArray();
@@ -179,6 +198,7 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
"[干预行动] <将对已存在行动做出的行为>", "无行为")); "[干预行动] <将对已存在行动做出的行为>", "无行为"));
} }
} }
private void setupInterventionPrompt(String uuid, List<EvaluatedInterventionData> executingDataList, private void setupInterventionPrompt(String uuid, List<EvaluatedInterventionData> executingDataList,
List<EvaluatedInterventionData> preparedDataList) { List<EvaluatedInterventionData> preparedDataList) {
JSONArray contents = new JSONArray(); JSONArray contents = new JSONArray();
@@ -204,15 +224,11 @@ public class ActionInterventor extends PreRunningAbstractAgentModuleAbstract imp
"[干预内容] <将对已存在行动做出的行为>", contents.toString())); "[干预内容] <将对已存在行动做出的行为>", contents.toString()));
} }
} }
private void setupNoInterventionPrompt(String uuid) { private void setupNoInterventionPrompt(String uuid) {
interventionPrompt.put(uuid, Map.of( 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 { implements ActivateModel {
@InjectCapability @InjectCapability
private ActionCapability actionCapability; private ActionCapability actionCapability;
/** /**
* 基于干预意图、记忆切片、交互上下文、已有行动程序综合评估,尝试评估并选取出合适的行动程序,交付给 ActionInterventor * 基于干预意图、记忆切片、交互上下文、已有行动程序综合评估,尝试评估并选取出合适的行动程序,交付给 ActionInterventor
*/ */
@@ -47,6 +48,7 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
} }
return result; return result;
} }
private void evaluateIntervention(List<EvaluatedInterventionData> evaluatedDataList, Map<String, ExecutableAction> interventionMap, EvaluatorInput input, ExecutorService executor, CountDownLatch latch) { private void evaluateIntervention(List<EvaluatedInterventionData> evaluatedDataList, Map<String, ExecutableAction> interventionMap, EvaluatorInput input, ExecutorService executor, CountDownLatch latch) {
interventionMap.forEach((tendency, actionData) -> executor.execute(() -> { interventionMap.forEach((tendency, actionData) -> executor.execute(() -> {
try { try {
@@ -64,6 +66,7 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
} }
})); }));
} }
private String buildPrompt(List<Message> recentMessages, List<EvaluatedSlice> activatedSlices, private String buildPrompt(List<Message> recentMessages, List<EvaluatedSlice> activatedSlices,
ExecutableAction executableAction, String tendency) { ExecutableAction executableAction, String tendency) {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
@@ -73,10 +76,12 @@ public class InterventionEvaluator extends AbstractAgentModule.Sub<EvaluatorInpu
json.put("将干预的行动", JSONObject.toJSONString(executableAction)); json.put("将干预的行动", JSONObject.toJSONString(executableAction));
return json.toJSONString(); return json.toJSONString();
} }
@Override @Override
public String modelKey() { public String modelKey() {
return "intervention_evaluator"; return "intervention_evaluator";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return false; return false;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -25,14 +25,17 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static work.slhaf.partner.common.util.ExtractUtil.extractJson; import static work.slhaf.partner.common.util.ExtractUtil.extractJson;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, List<EvaluatedSlice>> implements ActivateModel { public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput, List<EvaluatedSlice>> implements ActivateModel {
private InteractionThreadPoolExecutor executor; private InteractionThreadPoolExecutor executor;
@Init @Init
public void init() { public void init() {
executor = InteractionThreadPoolExecutor.getInstance(); executor = InteractionThreadPoolExecutor.getInstance();
} }
@Override @Override
public List<EvaluatedSlice> execute(EvaluatorInput evaluatorInput) { public List<EvaluatedSlice> execute(EvaluatorInput evaluatorInput) {
log.debug("[SliceSelectEvaluator] 切片评估模块开始..."); log.debug("[SliceSelectEvaluator] 切片评估模块开始...");
@@ -80,6 +83,7 @@ public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput
List<EvaluatedSlice> temp = queue.stream().toList(); 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) { private void setSliceSummaryList(MemoryResult memoryResult, List<SliceSummary> sliceSummaryList, Map<Long, SliceSummary> map) {
for (MemorySliceResult memorySliceResult : memoryResult.getMemorySliceResult()) { for (MemorySliceResult memorySliceResult : memoryResult.getMemorySliceResult()) {
SliceSummary sliceSummary = new SliceSummary(); SliceSummary sliceSummary = new SliceSummary();
@@ -109,9 +113,11 @@ public class SliceSelectEvaluator extends AbstractAgentModule.Sub<EvaluatorInput
map.put(memorySlice.getTimestamp(), sliceSummary); map.put(memorySlice.getTimestamp(), sliceSummary);
} }
} }
public String modelKey() { public String modelKey() {
return "slice_evaluator"; return "slice_evaluator";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return false; 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.extractJson;
import static work.slhaf.partner.common.util.ExtractUtil.fixTopicPath; import static work.slhaf.partner.common.util.ExtractUtil.fixTopicPath;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, ExtractorResult> public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, ExtractorResult>
@@ -30,6 +31,7 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunnin
private MemoryCapability memoryCapability; private MemoryCapability memoryCapability;
@InjectCapability @InjectCapability
private CognationCapability cognationCapability; private CognationCapability cognationCapability;
@Override @Override
public ExtractorResult execute(PartnerRunningFlowContext context) { public ExtractorResult execute(PartnerRunningFlowContext context) {
log.debug("[MemorySelectExtractor] 主题提取模块开始..."); log.debug("[MemorySelectExtractor] 主题提取模块开始...");
@@ -66,6 +68,7 @@ public class MemorySelectExtractor extends AbstractAgentModule.Sub<PartnerRunnin
} }
return fix(extractorResult); return fix(extractorResult);
} }
private ExtractorResult fix(ExtractorResult extractorResult) { private ExtractorResult fix(ExtractorResult extractorResult) {
extractorResult.getMatches().forEach(m -> { extractorResult.getMatches().forEach(m -> {
if (m.getType().equals(ExtractorMatchData.Constant.DATE)) { 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()); extractorResult.getMatches().removeIf(m -> m.getText().split("->")[0].isEmpty());
return extractorResult; return extractorResult;
} }
@Override @Override
public String modelKey() { public String modelKey() {
return "topic_extractor"; return "topic_extractor";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return false; return false;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,6 +8,6 @@ import java.util.List;
@Data @Data
public class RelationExtractInput { public class RelationExtractInput {
private HashMap<String,String> primaryUserPerceive; private HashMap<String, String> primaryUserPerceive;
private List<Message> chatMessages; 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 work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
import java.util.HashMap; import java.util.HashMap;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class StaticMemoryExtractor extends AbstractAgentModule.Sub<PartnerRunningFlowContext, HashMap<String, String>> implements ActivateModel { 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; private CognationCapability cognationCapability;
@InjectCapability @InjectCapability
private PerceiveCapability perceiveCapability; private PerceiveCapability perceiveCapability;
@Override @Override
public HashMap<String, String> execute(PartnerRunningFlowContext context) { public HashMap<String, String> execute(PartnerRunningFlowContext context) {
StaticMemoryExtractInput input = StaticMemoryExtractInput.builder() StaticMemoryExtractInput input = StaticMemoryExtractInput.builder()
@@ -34,10 +36,12 @@ public class StaticMemoryExtractor extends AbstractAgentModule.Sub<PartnerRunnin
jsonObject.forEach((k, v) -> result.put(k, (String) v)); jsonObject.forEach((k, v) -> result.put(k, (String) v));
return result; return result;
} }
@Override @Override
public String modelKey() { public String modelKey() {
return "static_extractor"; return "static_extractor";
} }
@Override @Override
public boolean withBasicPrompt() { public boolean withBasicPrompt() {
return true; return true;

View File

@@ -12,5 +12,5 @@ import java.util.Map;
public class StaticMemoryExtractInput { public class StaticMemoryExtractInput {
private String userId; private String userId;
private List<Message> messages; 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; package work.slhaf.partner.module.modules.process;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import work.slhaf.partner.api.agent.factory.capability.annotation.InjectCapability; import work.slhaf.partner.api.agent.factory.capability.annotation.InjectCapability;
import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule; import work.slhaf.partner.api.agent.factory.module.abstracts.AbstractAgentModule;
import work.slhaf.partner.core.cognation.CognationCapability; import work.slhaf.partner.core.cognation.CognationCapability;
import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext; import work.slhaf.partner.runtime.interaction.data.context.PartnerRunningFlowContext;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class PostprocessExecutor extends AbstractAgentModule.Running<PartnerRunningFlowContext> { public class PostprocessExecutor extends AbstractAgentModule.Running<PartnerRunningFlowContext> {
private static final int POST_PROCESS_TRIGGER_ROLL_LIMIT = 36; private static final int POST_PROCESS_TRIGGER_ROLL_LIMIT = 36;
@InjectCapability @InjectCapability
private CognationCapability cognationCapability; private CognationCapability cognationCapability;
@Override @Override
public void execute(PartnerRunningFlowContext context) { public void execute(PartnerRunningFlowContext context) {
boolean trigger = cognationCapability.getChatMessages().size() >= POST_PROCESS_TRIGGER_ROLL_LIMIT; 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.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract { public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
@@ -21,17 +22,20 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
private CognationCapability cognationCapability; private CognationCapability cognationCapability;
@InjectCapability @InjectCapability
private PerceiveCapability perceiveCapability; private PerceiveCapability perceiveCapability;
@Override @Override
public void doExecute(PartnerRunningFlowContext context) { public void doExecute(PartnerRunningFlowContext context) {
checkAndSetMemoryId(); checkAndSetMemoryId();
getInteractionContext(context); getInteractionContext(context);
} }
private void checkAndSetMemoryId() { private void checkAndSetMemoryId() {
String currentMemoryId = cognationCapability.getCurrentMemoryId(); String currentMemoryId = cognationCapability.getCurrentMemoryId();
if (currentMemoryId == null || cognationCapability.getChatMessages().isEmpty()) { if (currentMemoryId == null || cognationCapability.getChatMessages().isEmpty()) {
cognationCapability.refreshMemoryId(); cognationCapability.refreshMemoryId();
} }
} }
private void getInteractionContext(PartnerRunningFlowContext context) { private void getInteractionContext(PartnerRunningFlowContext context) {
log.debug("[PreprocessExecutor] 预处理原始输入: {}", context); log.debug("[PreprocessExecutor] 预处理原始输入: {}", context);
User user = perceiveCapability.getUser(context.getUserInfo(), context.getPlatform()); User user = perceiveCapability.getUser(context.getUserInfo(), context.getPlatform());
@@ -46,6 +50,7 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
setCoreContext(context); setCoreContext(context);
log.debug("[PreprocessExecutor] 预处理结果: {}", context); log.debug("[PreprocessExecutor] 预处理结果: {}", context);
} }
@Override @Override
protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) { protected Map<String, String> getPromptDataMap(PartnerRunningFlowContext context) {
HashMap<String, String> map = new HashMap<>(); HashMap<String, String> map = new HashMap<>();
@@ -57,10 +62,12 @@ public class PreprocessExecutor extends PreRunningAbstractAgentModuleAbstract {
map.put("其他", "历史对话中将在用户消息的最后一行标注时间"); map.put("其他", "历史对话中将在用户消息的最后一行标注时间");
return map; return map;
} }
@Override @Override
protected String moduleName() { protected String moduleName() {
return "[基础模块]"; return "[基础模块]";
} }
private void setCoreContext(PartnerRunningFlowContext context) { private void setCoreContext(PartnerRunningFlowContext context) {
CoreContext coreContext = context.getCoreContext(); CoreContext coreContext = context.getCoreContext();
coreContext.setText(context.getInput()); coreContext.setText(context.getInput());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <parent>
<artifactId>Partner</artifactId> <artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId> <groupId>work.slhaf</groupId>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
package work.slhaf.partner.api.agent.factory.config.exception; 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) { public ConfigUpdateFailedException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }

View File

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

View File

@@ -175,6 +175,7 @@ public class ModuleCheckFactory extends AgentBaseFactory {
/** /**
* 检查源集合中是否有不在目标集合中的元素 * 检查源集合中是否有不在目标集合中的元素
*
* @param source 源集合 * @param source 源集合
* @param target 目标集合 * @param target 目标集合
* @param errorMessage 错误信息前缀 * @param errorMessage 错误信息前缀

View File

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

View File

@@ -46,6 +46,20 @@ public class ModuleRegisterFactory extends AgentBaseFactory {
private List<MetaModule> moduleList; private List<MetaModule> moduleList;
private List<MetaSubModule> subModuleList; 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 @Override
protected void setVariables(AgentRegisterContext context) { protected void setVariables(AgentRegisterContext context) {
ModuleFactoryContext factoryContext = context.getModuleFactoryContext(); ModuleFactoryContext factoryContext = context.getModuleFactoryContext();
@@ -60,20 +74,6 @@ public class ModuleRegisterFactory extends AgentBaseFactory {
setSubModuleList(); 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() { private void setSubModuleList() {
Set<Class<?>> subModules = reflections.getTypesAnnotatedWith(AgentSubModule.class); Set<Class<?>> subModules = reflections.getTypesAnnotatedWith(AgentSubModule.class);
for (Class<?> subModule : subModules) { for (Class<?> subModule : subModules) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,6 +9,10 @@ public class GlobalExceptionHandler {
private AgentExceptionCallback exceptionCallback = new LogAgentExceptionCallback(); private AgentExceptionCallback exceptionCallback = new LogAgentExceptionCallback();
public static void setExceptionCallback(AgentExceptionCallback callback) {
INSTANCE.exceptionCallback = callback;
}
public boolean handle(Throwable e) { public boolean handle(Throwable e) {
boolean exit; boolean exit;
Throwable cause = e.getCause(); Throwable cause = e.getCause();
@@ -32,8 +36,4 @@ public class GlobalExceptionHandler {
} }
return exit; 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.data.AgentOutputData;
import work.slhaf.partner.api.agent.runtime.interaction.flow.entity.RunningFlowContext; 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(); void launch();
default void receive(I inputData){ default void receive(I inputData) {
C finalInputData = adapter().parseInputData(inputData); C finalInputData = adapter().parseInputData(inputData);
C outputContext = adapter().call(finalInputData); C outputContext = adapter().call(finalInputData);
O outputData = adapter().parseOutputData(outputContext); O outputData = adapter().parseOutputData(outputContext);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <parent>
<artifactId>Partner</artifactId> <artifactId>Partner</artifactId>
<groupId>work.slhaf</groupId> <groupId>work.slhaf</groupId>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <modelVersion>4.0.0</modelVersion>
<groupId>work.slhaf</groupId> <groupId>work.slhaf</groupId>
<artifactId>Partner</artifactId> <artifactId>Partner</artifactId>

View File

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

View File

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

View File

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

View File

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