微软AutoGen高级功能——Memory

news/2025/2/15 7:10:31/

介绍

大家好,博主又来给大家分享知识了。这次又要给大家分享什么呢?哈哈。这次要给大家分享的是微软AutoGen框架的高级且重要的功能:Memory。在微软AutoGen中,Memory(记忆)是一个重要概念,它主要用于存储和管理智能体之间交互的历史信息,有助于智能体在对话和协作过程中参考过往内容,以更智能地推进任务。那我们直接进入正题。

Memory

在几种用例中,维护一个有用事实的存储库是很有价值的,这些事实能在特定步骤即将开始前被智能地添加到智能体的上下文中。这里的典型用例是检索增强生成(RAG)模式,在这种模式下,一个查询被用于从数据库中检索相关信息,然后这些信息会被添加到智能体的上下文中。

AgentChat提供了一种记忆协议,该协议可以进行扩展以实现这一功能。其关键方法包括查询(query)、更新上下文(update_context)、添加(add)、清除(clear)和关闭(close)。

  • 添加(add):向记忆存储中添加新的条目。
  • 查询(query):从记忆存储中检索相关信息。
  • 更新上下文(update_context):通过添加检索到的信息来改变智能体的内部模型上下文(在助理智能体类中使用)。
  • 清除(clear):从记忆存储中清除所有条目。
  • 关闭(close):清理记忆存储所使用的任何资源。

ListMemory示例

Pythonautogen_core.memory.ListMemory作为Pythonautogen_core.memory.Memory协议的一个示例实现被提供。它是一个基于简单列表的记忆实现方式,按时间顺序保存记忆内容,将最新的记忆添加到模型的上下文中。这种实现方式设计得简单直接且具有可预测性,便于理解和调试。我们通过一个示例来演示,我们将使用ListMemory来维护一个用户偏好的记忆库,并展示随着时间推移,它如何被用来为智能体的回复提供一致的上下文信息。

完整代码

python">import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_core.memory import ListMemory, MemoryContent, MemoryMimeType
from autogen_ext.models.openai import OpenAIChatCompletionClient# 初始化用户记忆
user_memory = ListMemory()async def get_weather(city: str, units: str = "imperial") -> str:if units == "imperial":return f"The weather in {city} is 73 °F and Sunny."elif units == "metric":return f"The weather in {city} is 23 °C and Sunny."else:return f"Sorry, I don't know the weather in {city}."async def run_stream() -> None:# 将用户偏好添加到记忆中await user_memory.add(MemoryContent(content="The weather should be in metric units", mime_type=MemoryMimeType.TEXT))await user_memory.add(MemoryContent(content="Meal recipe must be vegan", mime_type=MemoryMimeType.TEXT))assistant_agent = AssistantAgent(name="assistant_agent",model_client=OpenAIChatCompletionClient(model="gpt-4o",),tools=[get_weather],memory=[user_memory],)stream = assistant_agent.run_stream(task="What is the weather in Beijing?")await Console(stream)asyncio.run(run_stream())

运行结果

python">---------- user ----------
What is the weather in Beijing?
---------- assistant_agent ----------
[MemoryContent(content='The weather should be in metric units', mime_type=<MemoryMimeType.TEXT: 'text/plain'>, metadata=None), MemoryContent(content='Meal recipe must be vegan', mime_type=<MemoryMimeType.TEXT: 'text/plain'>, metadata=None)]
---------- assistant_agent ----------
[FunctionCall(id='call_pHq4p89gW6oGjGr3VsVETCYX', arguments='{"city":"Beijing","units":"metric"}', name='get_weather')]
---------- assistant_agent ----------
[FunctionExecutionResult(content='The weather in Beijing is 23 °C and Sunny.', call_id='call_pHq4p89gW6oGjGr3VsVETCYX')]
---------- assistant_agent ----------
The weather in Beijing is 23 °C and Sunny.进程已结束,退出代码为 0

我们可以查看发现,assistant_agent的模型上下文实际上已用检索到的记忆条目进行了更新。transform方法被用于将检索到的记忆条目格式化为可供智能体使用的字符串。在这种情况下,我们只是简单地将每个记忆条目的内容连接成一个单一的字符串。

从上述内容我们可以看到,正如用户偏好中所要求的那样,天气信息是以摄氏度为单位返回的。
同样地,假设我们另外提出一个关于制定一份餐食计划的问题,智能体能够从记忆存储中检索到相关信息,并给出个性化的回复。

完整代码

python">import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_core.memory import ListMemory, MemoryContent, MemoryMimeType
from autogen_ext.models.openai import OpenAIChatCompletionClient# 初始化用户记忆
user_memory = ListMemory()async def get_weather(city: str, units: str = "imperial") -> str:if units == "imperial":return f"The weather in {city} is 73 °F and Sunny."elif units == "metric":return f"The weather in {city} is 23 °C and Sunny."else:return f"Sorry, I don't know the weather in {city}."async def run_stream() -> None:# 将用户偏好添加到记忆中await user_memory.add(MemoryContent(content="The weather should be in metric units", mime_type=MemoryMimeType.TEXT))await user_memory.add(MemoryContent(content="Meal recipe must be vegan", mime_type=MemoryMimeType.TEXT))assistant_agent = AssistantAgent(name="assistant_agent",model_client=OpenAIChatCompletionClient(model="gpt-4o",),tools=[get_weather],memory=[user_memory],)await assistant_agent._model_context.get_messages()stream = assistant_agent.run_stream(task="Write brief meal recipe with broth")await Console(stream)asyncio.run(run_stream())

运行结果

python">---------- user ----------
Write brief meal recipe with broth
---------- assistant_agent ----------
[MemoryContent(content='The weather should be in metric units', mime_type=<MemoryMimeType.TEXT: 'text/plain'>, metadata=None), MemoryContent(content='Meal recipe must be vegan', mime_type=<MemoryMimeType.TEXT: 'text/plain'>, metadata=None)]
---------- assistant_agent ----------
Here's a simple vegan meal recipe using broth:**Vegan Vegetable Soup****Ingredients:**
- 1 liter vegetable broth
- 1 cup chopped carrots
- 1 cup chopped celery
- 1 cup diced tomatoes
- 1 cup chopped zucchini
- 1 cup cooked chickpeas (optional)
- 2 cloves garlic, minced
- 1 tablespoon olive oil
- Salt and pepper to taste
- Fresh parsley for garnish**Instructions:**
1. Heat olive oil in a large pot over medium heat.
2. Add minced garlic and sauté until fragrant (about 1 minute).
3. Add carrots, celery, zucchini, and diced tomatoes to the pot. Stir and cook for 5 minutes.
4. Pour in the vegetable broth and bring it to a boil.
5. Lower the heat and let the soup simmer for 20–25 minutes, until the vegetables are tender.
6. Add cooked chickpeas (if using), and season with salt and pepper.
7. Garnish with fresh parsley before serving. Enjoy your warm vegan vegetable soup! TERMINATE进程已结束,退出代码为 0

自定义记忆存储(向量数据库等)

我们可以基于记忆协议来实现更复杂的记忆存储方式。例如,我们可以实现一个自定义的记忆存储系统,利用向量数据库来存储和检索信息,或者创建一个使用机器学习模型的记忆存储系统,以便根据用户的偏好等生成个性化的回复。

具体来说,我们需要重载addqueryupdate_context方法,以实现所需的功能,并将记忆存储传递给你的智能体。

完整代码

python">import asyncio
from typing import Any
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_core import CancellationToken
from autogen_core.memory import Memory, MemoryContent, MemoryMimeType, UpdateContextResult
from autogen_core.model_context import ChatCompletionContext
from autogen_ext.models.openai import OpenAIChatCompletionClient# 自定义记忆存储类
class CustomMemory(Memory):def __init__(self):self.memory_store = []async def add(self, entry: MemoryContent, cancellation_token: CancellationToken | None = None) -> None:self.memory_store.append(entry)print(f"Added entry: {entry.content}")async def query(self, query_str: str | MemoryContent, cancellation_token: CancellationToken | None = None,**kwargs: Any) -> list[Any]:passasync def update_context(self, agent: ChatCompletionContext) -> UpdateContextResult:passasync def clear(self):self.memory_store = []print("Memory store cleared")async def close(self):print("Memory store closed")async def get_weather(city: str, units: str = "imperial") -> str:if units == "imperial":return f"The weather in {city} is 73 °F and Sunny."elif units == "metric":return f"The weather in {city} is 23 °C and Sunny."else:return f"Sorry, I don't know the weather in {city}."async def run_stream() -> None:# 初始化自定义用户记忆user_memory = CustomMemory()# 将用户偏好添加到记忆中await user_memory.add(MemoryContent(content="The weather should be in metric units", mime_type=MemoryMimeType.TEXT))await user_memory.add(MemoryContent(content="Meal recipe must be vegan", mime_type=MemoryMimeType.TEXT))assistant_agent = AssistantAgent(name="assistant_agent",model_client=OpenAIChatCompletionClient(model="gpt-4o",),tools=[get_weather],memory=[user_memory],)await assistant_agent._model_context.get_messages()stream = assistant_agent.run_stream(task="Write brief meal recipe with broth")await Console(stream)asyncio.run(run_stream())

运行结果

python">Added entry: The weather should be in metric units
Added entry: Meal recipe must be vegan
---------- user ----------
Write brief meal recipe with broth
---------- assistant_agent ----------
**Chicken Broth Soup****Ingredients:**
- 4 cups chicken broth
- 1 cup shredded cooked chicken
- 1 cup chopped vegetables (carrots, celery, peas)
- 1/2 cup small pasta or rice
- 1-2 garlic cloves (minced)
- Salt and pepper to taste
- 1 tbsp olive oil**Instructions:**
1. In a pot, heat olive oil over medium heat and sauté garlic until fragrant.
2. Add vegetables and cook for 2-3 minutes.
3. Pour in chicken broth and bring to a boil.
4. Add pasta or rice and cook according to package directions.
5. Stir in shredded chicken, season with salt and pepper, and simmer for 5-10 minutes.
6. Serve hot and enjoy!TERMINATE进程已结束,退出代码为 0

说明

如果大家在运行上述代码的时候有AutoGen相关的提示或报错(例如:该参数不存在,没有此类方法等),请尝试更新一下AutoGen,博主在分享这篇博文的时候,AutoGen的版本是0.4.6稳定版

安装或更新命令

python">pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"

另外大家要根据业务需求,设置使用的LLM,不一定要按照我给大家分享代码中的设置来,如果只是为了测试并看运行结果可直接复制粘贴代码(完整代码)

结束

好了,以上就是本次分享的全部内容,细心的小伙伴可能会发现该功能有点类似于之前博主给大家分享的Managing State(管理状态)机制。那么它们二者之间的区别是什么呢?博主在这里给大家整理如下:

在微软的AutoGen框架中,MemoryManaging State机制在功能和应用场景上存在一些区别。

Memory

  1. 功能特性:Memory主要用于存储和检索与交互过程相关的信息,它提供了一种结构化的方式来保存历史对话、用户偏好、任务相关的上下文等内容。通过记忆功能,智能体可以参考之前的交互信息,从而在后续的对话或任务处理中提供更连贯、更符合上下文的回复。例如,用户在之前的对话中提到了自己喜欢的食物类型(如素食),记忆模块可以存储这个信息,当后续询问关于餐食推荐的问题时,智能体能够从记忆中检索到该信息并据此给出合适的建议。
  2. 接口和方法:Memory通常定义了一系列接口和方法,如add(添加记忆条目)、query(根据特定条件检索记忆条目)、update_context(将检索到的记忆信息更新到智能体的上下文)等。这些方法使得开发者可以方便地操作记忆存储,实现对记忆数据的管理和利用。比如,通过add方法可以将新的用户输入或重要信息添加到记忆中,query方法则可以根据关键词或其他条件从记忆中查找相关的历史记录。
  3. 应用场景:主要应用于多轮对话场景,帮助智能体维护对话的上下文连贯性,提升对话质量;也适用于需要记住用户特定偏好、设置等信息的场景,以便为用户提供个性化的服务。例如在智能客服系统中,记忆功能可以记录用户之前反馈的问题和解决方案,当用户再次咨询类似问题时,客服智能体能够快速给出准确的答复。

Managing State

  1. 功能特性:Managing State机制更侧重于管理智能体在执行任务过程中的整体状态信息。这包括任务的当前阶段、已经执行的操作、任务的目标和约束条件等。它关注的是智能体在处理复杂任务时的状态流转和协调,确保智能体能够按照正确的流程和逻辑完成任务。例如,在一个涉及多个步骤的任务(如策划一次旅行,包括选择目的地、预订机票、酒店等步骤)中,管理状态机制会记录每个步骤的完成情况和相关的状态信息,以便智能体能够合理地推进后续操作。
  2. 实现方式:管理状态可能涉及到状态机、状态变量的维护和更新等技术手段。通过定义不同的状态和状态转换规则,智能体可以根据当前的任务状态决定下一步的行动。例如,当智能体处于 “预订机票” 的状态时,它会执行与机票预订相关的操作,如查询航班信息、选择合适的航班等,并在预订成功后更新状态为 “机票已预订”。
  3. 应用场景:主要应用于复杂任务的执行和管理,如工作流自动化、多步骤问题解决等场景。在这些场景中,智能体需要根据不同的状态来协调多个子任务的执行,确保任务能够顺利完成。例如在一个项目管理智能体中,管理状态机制可以跟踪项目的各个阶段(如规划、执行、监控等),并根据项目状态做出相应的决策和调整。

综上所述,Memory主要聚焦于存储和利用交互历史和上下文信息,而Managing State更关注智能体在任务执行过程中的状态管理和协调,两者在AutoGen中分别承担着不同但又相互关联的重要角色,共同支持智能体的高效运行和复杂任务处理。

通过本次分享,大家有所收获吗?请大家多去大胆的尝试和使用。博主还是那句话:成功总是在不断的失败中试验出来的,敢于尝试就已经成功了一半。这次分享就到这,如果大家对博主分享的内容感兴趣或有帮助,请点赞和关注。大家的点赞和关注是博主持续分享的动力🤭,博主也希望让更多的人学习到新的知识。


http://www.ppmy.cn/news/1572173.html

相关文章

fastadmin图片前台导出

参考 https://github.com/hhurz/tableExport.jquery.plugin#options define([jquery, bootstrap, backend, table, form], function ($, undefined, Backend, Table, Form) {$(document).ready(function(){$(#table).bootstrapTable(refreshOptions, {exportOptions: {onMsoNu…

DeepSeek 可视化部署手册:环境配置与运维指南

DeepSeek 可视化部署详细步骤 DeepSeek 可视化部署涉及前端、后端、数据库等多个组件的配置与集成。以下是详细的部署步骤&#xff0c;帮助您完成从环境准备到生产环境部署的全过程。 1. 环境准备 在开始部署之前&#xff0c;确保您的系统满足以下要求&#xff1a; 操作系统…

lobechat环境变量汇总(docker版)

LobeChat 环境变量配置指南 LobeChat Docs LobeHub 上述是官方环境变量的配置指南&#xff0c;我并不会总结所有的环境变量用法&#xff0c;只会根据自行使用时&#xff0c;遇到的问题总结 s3存储变量 S3_ENABLE_PATH_STYLE 类型&#xff1a;可选 描述&#xff1a;是否启…

web自动化笔记(二)

文章目录 一、参数化测试1.pytest命令2.实现参数化测试3.填写地址测试4.生成Allure测试报告5.关键字驱动 二、案例1.实现后台登录1.1登录1.2.处理验证码1.3.封装识别验证码函数 2.通过cookie保持登录2.1给页面添加cookie2.2获取页面的cookie2.3自动化获取cookie 三、excel进行数…

Python--多线程

一、多线程与多进程 1.1 基本概念 进程&#xff1a;操作系统资源分配的基本单位&#xff0c;独立的内存空间&#xff0c;包含一个或多个线程。线程&#xff1a;CPU调度的最小单位&#xff0c;共享进程资源&#xff0c;轻量级执行流。多线程&#xff1a;同一进程内多个线程并发…

DeepSeek R1打造本地化RAG知识库

本文将详细介绍如何使用Ollama、Deepseek R1大语音模型、Nomic-Embed-Text向量模型和AnythingLLM共同搭建一个本地的私有RAG知识库。 一. 准备工作 什么是RAG&#xff1f; RAG是一种结合了信息检索和大模型&#xff08;LLM&#xff09;的技术&#xff0c;在对抗大模型幻觉、…

A4988一款带转换器和过流保护的 DMOS 微步驱动器的使用方式

A4988是一款带转换器和过流保护的 DMOS 微步驱动器&#xff0c;用于驱动双极步进电动机。它支持全、半、1/4、1/8 及 1/16 步进模式&#xff0c;输出驱动性能可达 35 V 及 2 A。其特点包括简单的步进和方向控制接口、可调电位器调节最大电流输出、自动电流衰减模式检测/选择以及…

算法-哈希表03-快乐数

快乐数 力扣题目链接 题目描述 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为&#xff1a; 对于一个正整数&#xff0c;每一次将该数替换为它每个位置上的数字的平方和。 然后重复这个过程直到这个数变为 1&#xff0c;也可能是 无限循环 但始终变不到 1。…