news 2026/7/26 12:08:04

怎么搞一个间隔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/7/23 0:04:12

Clawdbot汉化版效果展示:企业微信中AI实时翻译跨国会议对话

Clawdbot汉化版效果展示&#xff1a;企业微信中AI实时翻译跨国会议对话 你有没有经历过这样的会议场景&#xff1a; 会议室里坐着来自德国、日本、巴西的同事&#xff0c;大家语速飞快&#xff0c;专业术语满天飞&#xff0c;而你一边盯着PPT&#xff0c;一边在脑内疯狂翻译&a…

作者头像 李华
网站建设 2026/7/26 2:30:19

零基础入门MGeo,手把手教你做中文地址匹配

零基础入门MGeo&#xff0c;手把手教你做中文地址匹配 1. 为什么你该花15分钟学会用MGeo&#xff1f; 你有没有遇到过这些情况&#xff1a; 用户注册填的“北京朝阳区建国路8号”和后台数据库里的“北京市朝阳区建国门外大街8号”明明是同一个地方&#xff0c;系统却判定为不…

作者头像 李华
网站建设 2026/7/26 11:27:54

新手必看!用gpt-oss-20b-WEBUI轻松搭建本地大模型

新手必看&#xff01;用gpt-oss-20b-WEBUI轻松搭建本地大模型 你是不是也想过&#xff1a;不用登录网页、不依赖服务器、不担心隐私泄露&#xff0c;就能在自己电脑上跑一个真正像样的大模型&#xff1f;不是玩具级的“小模型”&#xff0c;而是OpenAI开源、vLLM加速、带完整W…

作者头像 李华
网站建设 2026/7/22 14:58:19

Qwen3Guard-Gen-WEB开箱即用,企业安全接入省心省力

Qwen3Guard-Gen-WEB开箱即用&#xff0c;企业安全接入省心省力 内容安全不是锦上添花的附加项&#xff0c;而是AIGC落地的生死线。当企业把大模型接入客服、创作、营销等核心业务时&#xff0c;一次未被拦截的歧视性回复、一段隐晦但违规的生成内容、一条绕过关键词过滤的诱导…

作者头像 李华
网站建设 2026/7/23 2:20:43

3个秘诀破解QQ音乐格式限制,让音频文件重获自由

3个秘诀破解QQ音乐格式限制&#xff0c;让音频文件重获自由 【免费下载链接】QMCDecode QQ音乐QMC格式转换为普通格式(qmcflac转flac&#xff0c;qmc0,qmc3转mp3, mflac,mflac0等转flac)&#xff0c;仅支持macOS&#xff0c;可自动识别到QQ音乐下载目录&#xff0c;默认转换结果…

作者头像 李华
网站建设 2026/7/23 1:52:21

Pi0视觉语言动作模型实战:3步完成机器人动作生成

Pi0视觉语言动作模型实战&#xff1a;3步完成机器人动作生成 你有没有想过&#xff0c;让机器人看懂你的指令、理解眼前的场景&#xff0c;然后直接执行动作&#xff1f;不是靠预设程序&#xff0c;而是像人类一样"看-想-做"的完整闭环。Pi0模型就是为这个目标而生的…

作者头像 李华