保姆级教程:用阿里开源的MemoryScope和硅基流动免费API,给你的AI助手装上“长期记忆”

张开发
2026/6/18 2:44:21 15 分钟阅读
保姆级教程:用阿里开源的MemoryScope和硅基流动免费API,给你的AI助手装上“长期记忆”
零成本构建AI长期记忆系统基于MemoryScope与硅基流动API的实战指南当你的AI助手能够记住三个月前你提过的宠物名字或是半年前讨论过的旅行计划这种体验是否让你感觉它更像一个真实的伙伴这正是长期记忆技术为AI对话系统带来的变革。本文将带你从零开始用完全免费的方案构建这样一个有记忆的AI系统。1. 长期记忆技术解析从理论到开源方案在传统对话系统中AI的记忆往往局限在单次会话的上下文窗口内。这种短期记忆机制就像金鱼的大脑每次对话都是全新的开始。要实现真正的长期记忆我们需要解决三个核心问题信息压缩如何从海量对话中提取关键信息高效检索如何在需要时快速找到相关记忆动态更新如何让记忆随用户成长而进化目前主流的解决方案是向量数据库技术它通过将文本转化为高维向量实现了语义级别的相似性搜索。阿里开源的MemoryScope项目在此基础上更进一步提供了完整的内存管理框架# MemoryScope核心架构示例 class MemorySystem: def __init__(self): self.vector_db ElasticsearchVectorStore() # 向量存储 self.workers [ObservationWorker(), InsightWorker()] # 记忆处理单元 self.workflows MemoryWorkflow() # 记忆处理流水线与付费方案相比这套开源架构具有三大优势完整的技术栈透明度灵活的可扩展接口零成本的部署方案2. 环境搭建从零开始的免费基础设施2.1 基础组件安装我们选择完全免费的硅基流动(SiliconFlow)API作为大模型服务配合Docker化的Elasticsearch实现向量存储。以下是具体部署步骤# 安装MemoryScope核心库 git clone https://github.com/modelscope/memoryscope cd memoryscope conda create -n memoryscope python3.10 -y conda activate memoryscope pip install -e . # 启动Elasticsearch服务 docker run -d -p 9200:9200 \ -e discovery.typesingle-node \ -e xpack.security.enabledfalse \ --name es docker.elastic.co/elasticsearch/elasticsearch:8.13.22.2 硅基流动API配置硅基流动提供了媲美商业API的免费服务注册后即可获取API Key。以下是各模块的推荐配置模块类型推荐模型端点地址LLMQwen-7Bhttps://api.siliconflow.cn/v1Embeddingbge-m3https://api.siliconflow.cn/v1/embeddingsReRankbge-reranker-v2https://api.siliconflow.cn/v1/rerank提示免费账号可能有QPS限制生产环境建议申请企业级权限3. 深度适配改造MemoryScope核心模块3.1 大模型接口重写原始代码仅支持阿里云和OpenAI接口我们需要新增硅基流动的适配层# memoryscope/core/models/llama_index_generation_model.py from llama_index.llms.openai_like import OpenAILike class SiliconFlowLLM(OpenAILike): def __init__(self, model: str, api_key: str): super().__init__( modelmodel, api_keyapi_key, api_basehttps://api.siliconflow.cn/v1, is_chat_modelTrue )对应的YAML配置修改为# demo_config_local.yaml generation_model: class: core.models.llama_index_generation_model module_name: SiliconFlowLLM model_name: Qwen-7B-Chat api_key: your_api_key_here3.2 嵌入模型优化硅基流动的bge-m3模型在中文场景表现优异我们需要实现专用的Embedding类class BGEEmbedding(BaseEmbedding): def get_text_embedding(self, text: str) - List[float]: response requests.post( https://api.siliconflow.cn/v1/embeddings, headers{Authorization: fBearer {self.api_key}}, json{input: text, model: BAAI/bge-m3} ) return response.json()[data][0][embedding]3.3 记忆工作流调优默认的记忆固化策略可能过于频繁建议调整触发条件# memoryscope/core/workflows/consolidation.py class CustomConsolidationWorkflow(MemoryWorkflow): def should_trigger(self) - bool: return len(self.new_observations) 5 # 积累5条新观察再触发4. 实战测试构建有记忆的AI助手4.1 基础对话测试启动记忆聊天服务并测试基础功能from memoryscope import MemoryScope config memoryscope/core/config/demo_config_local.yaml agent MemoryScope(config_pathconfig).default_memory_chat # 第一次对话 response agent.chat_with_memory(我最喜欢的颜色是深蓝色) print(response.message.content) # 好的已记住您喜欢深蓝色 # 第二次对话 response agent.chat_with_memory(你知道我喜欢什么颜色吗) print(response.message.content) # 您之前提到过喜欢深蓝色4.2 记忆检索验证检查系统是否正确存储和检索记忆片段memories agent.run_service_operation(query_memory, query用户喜欢的颜色 ) print(memories[0].content) # 用户最喜欢的颜色是深蓝色4.3 长期记忆测试模拟跨会话记忆保持# 第一天对话 agent.chat_with_memory(我计划下个月去日本旅行) # 模拟系统重启 del agent agent MemoryScope(config_pathconfig).default_memory_chat # 一周后对话 response agent.chat_with_memory(我之前说的旅行计划是去哪) print(response.message.content) # 您计划下个月去日本旅行5. 高级应用打造个性化记忆系统5.1 记忆分类策略通过自定义元数据实现记忆分类存储from memoryscope.core import MemoryEntry class PersonalizedMemory(MemoryEntry): category: str Field(defaultgeneral) importance: int Field(default1)5.2 情感记忆增强结合情感分析提升记忆质量def enrich_memory(text: str) - dict: return { text: text, sentiment: analyze_sentiment(text), # 调用情感分析API keywords: extract_keywords(text) }5.3 记忆衰减机制实现符合人类记忆规律的衰减算法def apply_forgetting_curve(memory: MemoryEntry) - float: 基于艾宾浩斯遗忘曲线计算记忆强度 elapsed_days (datetime.now() - memory.timestamp).days return memory.base_weight * (0.56 ** (elapsed_days/1.1))在项目实际落地过程中最耗时的环节往往是记忆触发策略的调优。我们发现将记忆检索阈值设置为0.72记忆固化间隔设为5条新观察时能在响应速度和记忆准确性间取得最佳平衡。

更多文章