基于lamp网站建设实例seo综合查询工具可以查看哪些数据
基于lamp网站建设实例,seo综合查询工具可以查看哪些数据,网站不备案怎么办,网站模板免费下载记忆与知识#xff1a;RAG、Memory 与状态管理核心解析
请关注公众号【碳硅化合物AI】
摘要
智能体需要记忆才能持续对话#xff0c;需要知识才能回答专业问题。AgentScope 提供了完整的记忆系统和 RAG#xff08;检索增强生成#xff09;能力RAG、Memory 与状态管理核心解析请关注公众号【碳硅化合物AI】摘要智能体需要记忆才能持续对话需要知识才能回答专业问题。AgentScope 提供了完整的记忆系统和 RAG检索增强生成能力让智能体既能记住对话历史也能从知识库中检索相关信息。本文将深入分析 Memory、RAG 和状态管理三个核心系统的实现包括它们的类设计、工作流程以及嵌套状态管理这个巧妙的设计。通过阅读本文你会理解智能体如何管理短期和长期记忆如何从向量数据库中检索知识以及状态序列化的实现原理。入口类与类关系记忆系统的类层次AgentScope 的记忆系统分为短期记忆和长期记忆它们都继承自MemoryBaseRAG 系统的类层次RAG 系统由知识库、文档读取器和向量存储组成关键代码MemoryBase 接口让我们看看MemoryBase定义了哪些核心方法class MemoryBase(StateModule): The base class for memory in agentscope. abstractmethod async def add(self, *args: Any, **kwargs: Any) - None: Add items to the memory. abstractmethod async def delete(self, *args: Any, **kwargs: Any) - None: Delete items from the memory. abstractmethod async def retrieve(self, *args: Any, **kwargs: Any) - None: Retrieve items from the memory. abstractmethod async def size(self) - int: Get the size of the memory. abstractmethod async def clear(self) - None: Clear the memory content. abstractmethod async def get_memory(self, *args: Any, **kwargs: Any) - list[Msg]: Get the memory content.这个接口非常简洁但涵盖了记忆系统的所有核心操作。InMemoryMemory是内存实现直接存储Msg对象列表。关键流程分析Memory 存储和检索流程短期记忆的流程非常简单直接InMemoryMemory的实现非常直观async def add( self, memories: Union[list[Msg], Msg, None], allow_duplicates: bool False, ) - None: Add message into the memory. if memories is None: return if isinstance(memories, Msg): memories [memories] # 检查重复默认不允许重复 if not allow_duplicates: existing_ids [_.id for _ in self.content] memories [_ for _ in memories if _.id not in existing_ids] self.content.extend(memories) async def get_memory(self) - list[Msg]: Get the memory content. return self.content这种设计的好处是简单高效适合大多数场景。如果需要持久化可以使用长期记忆。RAG 检索流程RAG 的检索流程稍微复杂一些涉及向量化和相似度搜索让我们看看SimpleKnowledge的检索实现async def retrieve( self, query: str, limit: int 5, score_threshold: float | None None, **kwargs: Any, ) - list[Document]: Retrieve relevant documents by the given queries. # 1. 将查询向量化 res_embedding await self.embedding_model( [ TextBlock( typetext, textquery, ), ], ) # 2. 在向量数据库中搜索 res await self.embedding_store.search( res_embedding.embeddings[0], limitlimit, score_thresholdscore_threshold, **kwargs, ) return res这个过程分为两步向量化查询使用 EmbeddingModel 将文本查询转换为向量相似度搜索在向量数据库中找到最相似的文档向量数据库如 Qdrant、Milvus使用高效的近似最近邻ANN算法即使有百万级文档也能快速检索。状态管理流程状态管理的核心是序列化和反序列化关键技术点1. RAG 的向量化存储和检索RAG 系统的核心是向量相似度搜索。当你添加文档时# 1. 读取文档并分块documentsawaitreader(text...)# 2. 向量化并存储awaitknowledge.add_documents(documents)在add_documents内部会使用 EmbeddingModel 将每个文档块向量化将向量和元数据存储到向量数据库建立索引以支持快速检索检索时系统会将查询向量化在向量数据库中搜索最相似的文档根据相似度分数过滤结果这种设计让智能体能够从大量文档中快速找到相关信息而不需要遍历所有文档。2. 短期记忆和长期记忆的区别AgentScope 对短期记忆和长期记忆的区分很灵活短期记忆MemoryBase存储对话历史通常保存在内存中InMemoryMemory快速访问但会话结束后丢失适合存储当前对话的上下文长期记忆LongTermMemoryBase持久化存储重要信息支持语义检索如 Mem0、ReMe可以跨会话使用适合存储用户偏好、历史经验等实际上AgentScope 并不强制区分它们。你可以只使用一个强大的记忆系统也可以组合使用。这种设计体现了需求驱动的理念。3. 嵌套状态管理机制这是 AgentScope 的一个巧妙设计。StateModule通过__setattr__自动追踪子模块def __setattr__(self, key: str, value: Any) - None: Set attributes and record state modules. if isinstance(value, StateModule): if not hasattr(self, _module_dict): raise AttributeError(...) self._module_dict[key] value super().__setattr__(key, value)当你创建一个 ReActAgent 时agentReActAgent(memoryInMemoryMemory(),# 自动被追踪toolkitToolkit(),# 自动被追踪...)这些子模块会自动被纳入状态管理。当你调用agent.state_dict()时def state_dict(self) - dict: Get the state dictionary of the module. state {} for key in self._module_dict: attr getattr(self, key, None) if isinstance(attr, StateModule): state[key] attr.state_dict() # 递归调用 for key in self._attribute_dict: attr getattr(self, key) to_json_function self._attribute_dict[key].to_json if to_json_function is not None: state[key] to_json_function(attr) else: state[key] attr return state这种递归设计让状态管理变得非常强大。你可以保存整个智能体的状态包括它的记忆、工具集等所有子组件。4. 状态序列化和反序列化状态序列化支持两种方式自动序列化对于 JSON 可序列化的属性直接序列化自定义序列化通过register_state注册自定义的序列化函数def register_state( self, attr_name: str, custom_to_json: Callable[[Any], JSONSerializableObject] | None None, custom_from_json: Callable[[JSONSerializableObject], Any] | None None, ) - None: Register an attribute to be tracked as a state variable. attr getattr(self, attr_name) if custom_to_json is None: # 确保属性是 JSON 可序列化的 try: json.dumps(attr) except Exception as e: raise TypeError(...) self._attribute_dict[attr_name] _JSONSerializeFunction( to_jsoncustom_to_json, load_jsoncustom_from_json, )这种设计让你可以保存复杂对象的状态控制序列化的粒度实现自定义的序列化逻辑总结Memory、RAG 和状态管理是 AgentScope 框架中非常重要的三个系统Memory 系统提供了灵活的短期和长期记忆管理让智能体能够记住对话历史和重要信息RAG 系统通过向量相似度搜索让智能体能够从知识库中检索相关信息状态管理通过嵌套状态管理和自定义序列化让智能体的状态可以完整保存和恢复这三个系统的设计都体现了 AgentScope 的核心理念模块化、透明、可扩展。在下一篇文章中我们会分析模型、MCP 和工具系统的实现这些组件为智能体提供了与外部世界交互的能力。