AI项目博客
记录 AI 工程实践与大模型应用

Spring AI Alibaba 58|记忆管理 · 概述

Spring AI Alibaba 的 Agent 使用持久化机制来实现长期记忆功能。这是一个高级主题,需要对 Spring AI Alibaba 的 Agent 框架有一定了解。

┌─────────────────────────────────────────────────────────┐
│                     ReactAgent                          │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌──────────────────┐        ┌────────────────────┐   │
│  │  短期记忆         │        │   长期记忆          │   │
│  │  Short-term      │        │   Long-term        │   │
│  │  (MemorySaver)   │        │   (MemoryStore)    │   │
│  └──────────────────┘        └────────────────────┘   │
│         │                             │                │
│         │ threadId                    │ namespace/key  │
│         ↓                             ↓                │
│  ┌──────────────────┐        ┌────────────────────┐   │
│  │  对话历史         │        │  用户画像          │   │
│  │  Conversation    │        │  User Profiles     │   │
│  │  History         │        │  Preferences       │   │
│  │  Message State   │        │  Persistent Data   │   │
│  └──────────────────┘        └────────────────────┘   │
│                                                         │
│  ┌─────────────────────────────────────────────────┐  │
│  │            ModelHook / 拦截器                    │  │
│  │  - beforeModel: 加载并注入记忆                   │  │
│  │  - afterModel: 保存并学习交互内容                │  │
│  └─────────────────────────────────────────────────┘  │
│                                                         │
│  ┌─────────────────────────────────────────────────┐  │
│  │            记忆工具 Tools                        │  │
│  │  - saveMemory: 显式保存到长期记忆                │  │
│  │  - getMemory: 显式从长期记忆检索                 │  │
│  └─────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Spring AI Alibaba 将长期记忆以 JSON 文档的形式存储在 Store 中。

每个记忆都在自定义的 namespace(类似于文件夹)下组织,并使用唯一的 key(类似于文件名)。命名空间通常包含用户或组织 ID 或其他标签,以便更容易地组织信息。

这种结构支持记忆的层次化组织。通过内容过滤器支持跨命名空间搜索。

import com.alibaba.cloud.ai.graph.store.stores.MemoryStore;
import com.alibaba.cloud.ai.graph.store.StoreItem;

import java.util.*;

// MemoryStore 将数据保存到内存字典中。在生产环境中请使用基于数据库的存储实现
MemoryStore store = new MemoryStore();

String userId = "my-user";
String applicationContext = "chitchat";
List<String> namespace = List.of(userId, applicationContext);

// 保存记忆
Map<String, Object> memoryData = new HashMap<>();
memoryData.put("rules", List.of(
  "用户喜欢简短直接的语言",
  "用户只说中文和Java"
));
memoryData.put("my-key", "my-value");

StoreItem item = StoreItem.of(namespace, "a-memory", memoryData);
store.putItem(item);

// 通过ID获取记忆
Optional<StoreItem> retrievedItem = store.getItem(namespace, "a-memory");

// 在此命名空间内搜索记忆,通过内容等价性过滤,按向量相似度排序
List<StoreItem> items = store.searchItems(
  namespace,
  Map.of("my-key", "my-value")
);

下面的示例展示了如何创建一个工具,让 Agent 能够查询用户信息。

import com.alibaba.cloud.ai.graph.agent.ReactAgent;
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.model.ChatModel;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.function.FunctionToolCallback;

import java.util.*;
import java.util.function.BiFunction;

// 定义请求和响应记录
public record GetMemoryRequest(List<String> namespace, String key) {}
public record MemoryResponse(String message, Map<String, Object> value) {}

// 创建内存存储
MemoryStore store = new MemoryStore();

// 向存储中写入示例数据
Map<String, Object> userData = new HashMap<>();
userData.put("name", "张三");
userData.put("language", "中文");

StoreItem userItem = StoreItem.of(List.of("users"), "user_123", userData);
store.putItem(userItem);

// 创建获取用户信息的工具
BiFunction<GetMemoryRequest, ToolContext, MemoryResponse> getUserInfoFunction =
  (request, context) -> {
      RunnableConfig runnableConfig = (RunnableConfig) context.getContext().get("config");
      Store store = runnableConfig.store();
      Optional<StoreItem> itemOpt = store.getItem(request.namespace(), request.key());
      if (itemOpt.isPresent()) {
          Map<String, Object> value = itemOpt.get().getValue();
          return new MemoryResponse("找到用户信息", value);
      }
      return new MemoryResponse("未找到用户", Map.of());
  };

ToolCallback getUserInfoTool = FunctionToolCallback.builder("getUserInfo", getUserInfoFunction)
  .description("查询用户信息")
  .inputType(GetMemoryRequest.class)
  .build();

// 创建Agent
ReactAgent agent = ReactAgent.builder()
  .name("memory_agent")
  .model(chatModel)
  .tools(getUserInfoTool)
  .saver(new MemorySaver())
  .build();

// 创建内存存储
MemoryStore store = new MemoryStore();
// 向存储中写入示例数据
Map<String, Object> userData = new HashMap<>();
userData.put("name", "张三");
userData.put("language", "中文");

StoreItem userItem = StoreItem.of(List.of("users"), "user_123", userData);
store.putItem(userItem);

// 运行Agent
RunnableConfig config = RunnableConfig.builder()
  .threadId("session_001")
  .addMetadata("user_id", "user_123")
  .store(store)
  .build();

agent.invoke("查询用户信息,namespace=['users'], key='user_123'", config);

下面的示例展示了如何创建一个更新用户信息的工具。

import com.alibaba.cloud.ai.graph.agent.ReactAgent;
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.model.ChatModel;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.function.FunctionToolCallback;

import java.util.*;
import java.util.function.BiFunction;

// 定义请求记录
public record SaveMemoryRequest(List<String> namespace, String key, Map<String, Object> value) {}
public record MemoryResponse(String message, Map<String, Object> value) {}

// 创建内存存储
MemoryStore store = new MemoryStore();

// 创建保存用户信息的工具
BiFunction<SaveMemoryRequest, ToolContext, MemoryResponse> saveUserInfoFunction =
  (request, context) -> {
      RunnableConfig runnableConfig = (RunnableConfig) context.getContext().get("config");
      Store store = runnableConfig.store();
      StoreItem item = StoreItem.of(request.namespace(), request.key(), request.value());
      store.putItem(item);
      return new MemoryResponse("成功保存用户信息", request.value());
  };

ToolCallback saveUserInfoTool = FunctionToolCallback.builder("saveUserInfo", saveUserInfoFunction)
  .description("保存用户信息")
  .inputType(SaveMemoryRequest.class)
  .build();

// 创建Agent
ReactAgent agent = ReactAgent.builder()
  .name("save_memory_agent")
  .model(chatModel)
  .tools(saveUserInfoTool)
  .saver(new MemorySaver())
  .build();

// 创建内存存储
MemoryStore store = new MemoryStore();
RunnableConfig config = RunnableConfig.builder()
  .threadId("session_001")
  .addMetadata("user_id", "user_123")
  .store(store)
  .build();

// 运行Agent
agent.invoke(
  "我叫张三,请保存我的信息。使用 saveUserInfo 工具,namespace=['users'], key='user_123', value={'name': '张三'}",
  config
);

// 可以直接访问存储获取值
Optional<StoreItem> savedItem = store.getItem(List.of("users"), "user_123");
if (savedItem.isPresent()) {
  Map<String, Object> savedValue = savedItem.get().getValue();
}

本文整理自 Spring AI Alibaba 官方文档《记忆管理》:https://java2ai.com/docs/frameworks/agent-framework/advanced/memory

赞(0)
未经允许不得转载:AI项目博客 » Spring AI Alibaba 58|记忆管理 · 概述

评论 抢沙发

AI项目博客

专注 AI 工程化落地 —— 覆盖智能体、大模型、Java AI 与 Python 的学习笔记,以及 AI 平台的项目实战记录。

关于本站文章归档

登录

找回密码

注册