Agent 可以随着时间的推移学习并存储用户偏好。
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.alibaba.cloud.ai.graph.agent.hook.ModelHook;
import com.alibaba.cloud.ai.graph.agent.hook.HookPosition;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver;
import com.alibaba.cloud.ai.graph.store.stores.MemoryStore;
import com.alibaba.cloud.ai.graph.store.StoreItem;
import org.springframework.ai.chat.messages.Message;
import java.util.*;
import java.util.concurrent.CompletableFuture;
MemoryStore memoryStore = new MemoryStore();
ModelHook preferenceLearningHook = new ModelHook() {
@Override
public String getName() {
return "preference_learning";
}
@Override
public HookPosition[] getHookPositions() {
return new HookPosition[]{HookPosition.AFTER_MODEL};
}
@Override
public CompletableFuture<Map<String, Object>> afterModel(OverAllState state, RunnableConfig config) {
String userId = (String) config.metadata("user_id").orElse(null);
if (userId == null) {
return CompletableFuture.completedFuture(Map.of());
}
// 提取用户输入
List<Message> messages = (List<Message>) state.value("messages").orElse(new ArrayList<>());
if (messages.isEmpty()) {
return CompletableFuture.completedFuture(Map.of());
}
// 加载现有偏好
Optional<StoreItem> prefsOpt = memoryStore.getItem(List.of("user_data"), userId + "_preferences");
List<String> prefs = new ArrayList<>();
if (prefsOpt.isPresent()) {
Map<String, Object> prefsData = prefsOpt.get().getValue();
prefs = (List<String>) prefsData.getOrDefault("items", new ArrayList<>());
}
// 简单的偏好提取(实际应用中使用NLP)
for (Message msg : messages) {
String content = msg.getText().toLowerCase();
if (content.contains("喜欢") || content.contains("偏好")) {
prefs.add(msg.getText());
Map<String, Object> prefsData = new HashMap<>();
prefsData.put("items", prefs);
StoreItem item = StoreItem.of(List.of("user_data"), userId + "_preferences", prefsData);
memoryStore.putItem(item);
System.out.println("学习到用户偏好 " + userId + ": " + msg.getText());
}
}
return CompletableFuture.completedFuture(Map.of());
}
};
ReactAgent agent = ReactAgent.builder()
.name("learning_agent")
.model(chatModel)
.hooks(preferenceLearningHook)
.saver(new MemorySaver())
.build();
RunnableConfig config = RunnableConfig.builder()
.threadId("learning_thread")
.addMetadata("user_id", "user_004")
.store(memoryStore)
.build();
// 用户表达偏好
agent.invoke("我喜欢喝绿茶。", config);
agent.invoke("我偏好早上运动。", config);
// 验证偏好已被存储
Optional<StoreItem> savedPrefs = memoryStore.getItem(List.of("user_data"), "user_004_preferences");
if (savedPrefs.isPresent()) {
// 偏好应该被保存到长期记忆中
}
本文整理自 Spring AI Alibaba 官方文档《记忆管理》:https://java2ai.com/docs/frameworks/agent-framework/advanced/memory

AI项目博客






