news 2026/5/14 1:13:05

怎么搞一个间隔1分钟循环的vlm带记忆的agent

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
怎么搞一个间隔1分钟循环的vlm带记忆的agent

基于AgentScope框架,你可以创建一个带有长期记忆功能的定时循环Agent。不过需要说明的是,当前代码库中没有直接的VLM(视觉语言模型)实现,你需要自己集成视觉处理功能。

基本实现方案

1. 创建带长期记忆的ReActAgent

fromagentscope.agentimportReActAgentfromagentscope.memoryimportMem0LongTermMemory,InMemoryMemoryfromagentscope.modelimportDashScopeChatModelfromagentscope.formatterimportDashScopeChatFormatterfromagentscope.embeddingimportDashScopeTextEmbeddingfromagentscope.toolimportToolkitimportosimportasyncioimporttime# 创建长期记忆实例long_term_memory=Mem0LongTermMemory(agent_name="VLM_Agent",user_name="user_001",model=DashScopeChatModel(model_name="qwen-max-latest",api_key=os.environ.get("DASHSCOPE_API_KEY"),stream=False,),embedding_model=DashScopeTextEmbedding(model_name="text-embedding-v2",api_key=os.environ.get("DASHSCOPE_API_KEY"),),on_disk=False,)# 创建带记忆的Agentagent=ReActAgent(name="VLM_Agent",sys_prompt="你是一个具有视觉处理能力和长期记忆的助手。",model=DashScopeChatModel(model_name="qwen-max-latest",api_key=os.environ.get("DASHSCOPE_API_KEY"),),formatter=DashScopeChatFormatter(),toolkit=Toolkit(),memory=InMemoryMemory(),long_term_memory=long_term_memory,long_term_memory_mode="agent_control",# 让agent自主管理记忆)

2. 添加定时循环机制

asyncdefperiodic_vlm_agent():"""每分钟执行一次的VLM Agent循环"""whileTrue:try:# 这里添加你的VLM处理逻辑# 例如:获取图像、分析、记录到记忆等# 模拟VLM任务task_msg=Msg(name="system",content="执行定时视觉分析任务",role="user")# 执行agent任务response=awaitagent(task_msg)print(f"Agent响应:{response.get_text_content()}")# 等待1分钟awaitasyncio.sleep(60)exceptExceptionase:print(f"执行出错:{e}")awaitasyncio.sleep(60)# 启动定时循环asyncio.run(periodic_vlm_agent())

3. 集成VLM功能(需要自定义实现)

由于当前代码库没有VLM实现,你需要创建自定义工具:

defanalyze_image(image_path:str)->str:"""分析图像内容的自定义工具"""# 这里集成你的VLM模型# 例如调用OpenAI GPT-4V、Google Gemini Vision等return"图像分析结果"# 注册到工具包toolkit=Toolkit()toolkit.register_tool_function(analyze_image)

关键组件说明

长期记忆配置

  • Mem0LongTermMemory提供基于向量的长期记忆存储 1
  • agent_control模式让Agent通过工具调用自主管理记忆 2

ReActAgent记忆管理

  • Agent会在每次回复时自动检索相关记忆 3
  • 支持记忆压缩功能,防止记忆无限增长 4

注意事项

  1. VLM集成:需要额外实现视觉处理工具,可以调用外部API如GPT-4V、Gemini Vision等
  2. 资源管理:定时循环要注意内存和API调用限制
  3. 记忆持久化:设置on_disk=True可以持久化记忆到磁盘
  4. 错误处理:添加适当的异常处理确保循环稳定运行

Notes

  • 当前AgentScope框架主要专注于文本对话Agent,VLM功能需要自定义实现
  • 长期记忆支持Mem0和ReMe两种实现,可根据需求选择
  • 定时循环建议在生产环境中使用更完善的任务调度系统如Celery或APScheduler

Wiki pages you might want to explore:

  • Quick Start: Building Your First Agent (agentscope-ai/agentscope)
  • Message System and Formatting (agentscope-ai/agentscope)

Citations

File:src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L72-139)

classMem0LongTermMemory(LongTermMemoryBase):"""A class that implements the LongTermMemoryBase interface using mem0."""def__init__(self,agent_name:str|None=None,user_name:str|None=None,run_name:str|None=None,model:ChatModelBase|None=None,embedding_model:EmbeddingModelBase|None=None,vector_store_config:VectorStoreConfig|None=None,mem0_config:MemoryConfig|None=None,default_memory_type:str|None=None,**kwargs:Any,)->None:"""Initialize the Mem0LongTermMemory instance Args: agent_name (`str | None`, optional): The name of the agent. Default is None. user_name (`str | None`, optional): The name of the user. Default is None. run_name (`str | None`, optional): The name of the run/session. Default is None. .. note:: 1. At least one of `agent_name`, `user_name`, or `run_name` is required. 2. During memory recording, these parameters become metadata for the stored memories. 3. **Important**: mem0 will extract memories from messages containing role of "user" by default. If you want to extract memories from messages containing role of "assistant", you need to provide `agent_name`. 4. During memory retrieval, only memories with matching metadata values will be returned. model (`ChatModelBase | None`, optional): The chat model to use for the long-term memory. If mem0_config is provided, this will override the LLM configuration. If mem0_config is None, this is required. embedding_model (`EmbeddingModelBase | None`, optional): The embedding model to use for the long-term memory. If mem0_config is provided, this will override the embedder configuration. If mem0_config is None, this is required. vector_store_config (`VectorStoreConfig | None`, optional): The vector store config to use for the long-term memory. If mem0_config is provided, this will override the vector store configuration. If mem0_config is None and this is not provided, defaults to Qdrant with on_disk=True. mem0_config (`MemoryConfig | None`, optional): The mem0 config to use for the long-term memory. If provided, individual model/embedding_model/vector_store_config parameters will override the corresponding configurations in mem0_config. If None, a new MemoryConfig will be created using the provided parameters. default_memory_type (`str | None`, optional): The type of memory to use. Default is None, to create a semantic memory. Raises: `ValueError`: If `mem0_config` is None and either `model` or `embedding_model` is None. """super().__init__()

File:docs/tutorial/zh_CN/src/task_long_term_memory.py (L78-103)

# 与 ReAct 智能体集成# ----------------------------------------# AgentScope 中的 ``ReActAgent`` 在构造函数中包含 ``long_term_memory`` 和 ``long_term_memory_mode`` 两个参数,# 其中 ``long_term_memory`` 用于指定长期记忆实例,``long_term_memory_mode`` 的取值为 ``"agent_control"``, ``"static_control"`` 或 ``"both"``。## 当 ``long_term_memory_mode`` 设置为 ``"agent_control"`` 或 ``both`` 时,在 ``ReActAgent`` 的构造函数中将# 注册两个工具函数:``record_to_memory`` 和 ``retrieve_from_memory``。# 从而使智能体能够自主的管理长期记忆。## .. note:: 为了达到最好的效果,``"agent_control"`` 模式可能还需要在系统提示(system prompt)中添加相应的说明。## 创建带有长期记忆的 ReAct 智能体agent=ReActAgent(name="Friday",sys_prompt="你是一个具有长期记忆功能的助手。",model=DashScopeChatModel(api_key=os.environ.get("DASHSCOPE_API_KEY"),model_name="qwen-max-latest",),formatter=DashScopeChatFormatter(),toolkit=Toolkit(),memory=InMemoryMemory(),long_term_memory=long_term_memory,long_term_memory_mode="static_control",# 使用 static_control 模式)

File:src/agentscope/agent/_react_agent.py (L870-894)

asyncdef_retrieve_from_long_term_memory(self,msg:Msg|list[Msg]|None,)->None:"""Insert the retrieved information from the long-term memory into the short-term memory as a Msg object. Args: msg (`Msg | list[Msg] | None`): The input message to the agent. """ifself._static_controlandmsg:# Retrieve information from the long-term memory if availableretrieved_info=awaitself.long_term_memory.retrieve(msg)ifretrieved_info:retrieved_msg=Msg(name="long_term_memory",content="<long_term_memory>The content below are ""retrieved from long-term memory, which maybe "f"useful:\n{retrieved_info}</long_term_memory>",role="user",)ifself.print_hint_msg:awaitself.print(retrieved_msg,True)awaitself.memory.add(retrieved_msg)

File:docs/tutorial/zh_CN/src/task_agent.py (L129-158)

# compression_config=ReActAgent.CompressionConfig(# enable=True,# agent_token_counter=CharTokenCounter(), # 智能体的 token 计数器# trigger_threshold=10000, # 超过 10000 个 token 时触发压缩# keep_recent=3, # 保持最近 3 条消息不被压缩# ),# )## 启用记忆压缩后,智能体会监控其记忆中的 token 数量。# 一旦超过 ``trigger_threshold``,智能体会自动:## 1. 识别尚未被压缩的消息(通过 ``exclude_mark``)# 2. 保持最近 ``keep_recent`` 条消息不被压缩(以保留最近的上下文)# 3. 将较早的消息发送给 LLM 生成结构化摘要# 4. 使用 ``MemoryMark.COMPRESSED`` 标记已压缩的消息(通过 ``update_messages_mark``)# 5. 将摘要存储在记忆中(通过 ``update_compressed_summary``)## .. important:: 压缩采用**标记机制**而非替换消息。旧消息被标记为已压缩,并通过 ``exclude_mark=MemoryMark.COMPRESSED`` 在后续检索中被排除,而生成的摘要则单独存储,在需要时检索。这种方式保留了原始消息,允许灵活的记忆管理。关于标记功能的更多详情,请参考 :ref:`memory`。## 默认情况下,压缩摘要被结构化为五个关键字段:## - **task_overview**:用户的核心请求和成功标准# - **current_state**:到目前为止已完成的工作,包括文件和输出# - **important_discoveries**:技术约束、决策、错误和失败的尝试# - **next_steps**:完成任务所需的具体操作# - **context_to_preserve**:用户偏好、领域细节和做出的承诺## **自定义压缩**## 可以通过指定 ``summary_schema``、``summary_template`` 和 ``compression_prompt`` 参数来自定义压缩的工作方式。
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/10 14:03:50

3步解锁Windows桌面改造:让任务栏颜值提升的实用指南

3步解锁Windows桌面改造&#xff1a;让任务栏颜值提升的实用指南 【免费下载链接】TranslucentTB A lightweight utility that makes the Windows taskbar translucent/transparent. 项目地址: https://gitcode.com/gh_mirrors/tr/TranslucentTB 每天面对电脑&#xff0…

作者头像 李华
网站建设 2026/5/13 14:13:18

ChatTTS最新整合包:从零搭建到生产环境部署的完整指南

ChatTTS最新整合包&#xff1a;从零搭建到生产环境部署的完整指南 背景与痛点&#xff1a;语音合成到底难在哪&#xff1f; 过去一年&#xff0c;我陆续给三个内部项目加了“张嘴说话”的能力。最早用某云厂商的 API&#xff0c;按字符计费&#xff0c;月底账单一看&#xff0…

作者头像 李华
网站建设 2026/5/12 7:03:24

还在为我的世界启动器配置浪费3小时?这款工具让你5分钟搞定

还在为我的世界启动器配置浪费3小时&#xff1f;这款工具让你5分钟搞定 【免费下载链接】PCL2-CE PCL2 社区版&#xff0c;可体验上游暂未合并的功能 项目地址: https://gitcode.com/gh_mirrors/pc/PCL2-CE 我的世界启动器哪个好用&#xff1f;PCL2-CE社区版给出了答案。…

作者头像 李华
网站建设 2026/5/9 21:02:55

CosyVoice v3.0接口服务启动实战:从配置优化到性能调优

CosyVoice v3.0接口服务启动实战&#xff1a;从配置优化到性能调优 摘要&#xff1a;本文针对CosyVoice v3.0接口服务启动过程中的常见痛点&#xff08;如配置复杂、冷启动慢等&#xff09;&#xff0c;提供一套完整的解决方案。通过详细解析服务启动流程、优化配置参数&#x…

作者头像 李华
网站建设 2026/5/9 21:02:46

解放双手:JX3Toy重构剑网3操作逻辑,开启自动化游戏新纪元

解放双手&#xff1a;JX3Toy重构剑网3操作逻辑&#xff0c;开启自动化游戏新纪元 【免费下载链接】JX3Toy 一个自动化测试DPS的小工具 项目地址: https://gitcode.com/GitHub_Trending/jx/JX3Toy 游戏操作的进化革命 当多数玩家仍在被重复的技能点击消耗精力时&#xf…

作者头像 李华
网站建设 2026/5/9 21:03:24

OFA-VE效果对比:OFA-VE与BLIP-2在视觉蕴含任务上的精度/速度权衡

OFA-VE效果对比&#xff1a;OFA-VE与BLIP-2在视觉蕴含任务上的精度/速度权衡 1. 什么是视觉蕴含&#xff1f;一个你每天都在用却没注意的AI能力 你有没有过这样的经历&#xff1a;刷短视频时看到一张图配着文字“这杯咖啡是今早手冲的”&#xff0c;你一眼就判断出这句话真不…

作者头像 李华