大家好,博主又来给大家分享知识了。这次又要给大家分享什么呢?哈哈。这次要给大家分享的是微软AutoGen框架的高级且重要的功能:Memory。在微软AutoGen中,Memory(记忆)是一个重要概念,它主要用于存储和管理智能体之间交互的历史信息,有助于智能体在对话和协作过程中参考过往内容,以更智能地推进任务。那我们直接进入正题。
在几种用例中,维护一个有用事实的存储库是很有价值的,这些事实能在特定步骤即将开始前被智能地添加到智能体的上下文中。这里的典型用例是检索增强生成(RAG)模式,在这种模式下,一个查询被用于从数据库中检索相关信息,然后这些信息会被添加到智能体的上下文中。
AgentChat提供了一种记忆协议,该协议可以进行扩展以实现这一功能。其关键方法包括查询(query)、更新上下文(update_context)、添加(add)、清除(clear)和关闭(close)。
Python类autogen_core.memory.ListMemory作为Python类autogen_core.memory.Memory协议的一个示例实现被提供。它是一个基于简单列表的记忆实现方式,按时间顺序保存记忆内容,将最新的记忆添加到模型的上下文中。这种实现方式设计得简单直接且具有可预测性,便于理解和调试。我们通过一个示例来演示,我们将使用ListMemory来维护一个用户偏好的记忆库,并展示随着时间推移,它如何被用来为智能体的回复提供一致的上下文信息。
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())
---------- user ----------
What is the weather in Beijing?
---------- assistant_agent ----------
[MemoryContent(content='The weather should be in metric units', mime_type=, metadata=None), MemoryContent(content='Meal recipe must be vegan', mime_type=, 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方法被用于将检索到的记忆条目格式化为可供智能体使用的字符串。在这种情况下,我们只是简单地将每个记忆条目的内容连接成一个单一的字符串。
从上述内容我们可以看到,正如用户偏好中所要求的那样,天气信息是以摄氏度为单位返回的。
同样地,假设我们另外提出一个关于制定一份餐食计划的问题,智能体能够从记忆存储中检索到相关信息,并给出个性化的回复。
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())
---------- user ----------
Write brief meal recipe with broth
---------- assistant_agent ----------
[MemoryContent(content='The weather should be in metric units', mime_type=, metadata=None), MemoryContent(content='Meal recipe must be vegan', mime_type=, 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
我们可以基于记忆协议来实现更复杂的记忆存储方式。例如,我们可以实现一个自定义的记忆存储系统,利用向量数据库来存储和检索信息,或者创建一个使用机器学习模型的记忆存储系统,以便根据用户的偏好等生成个性化的回复。
具体来说,我们需要重载add、query和update_context方法,以实现所需的功能,并将记忆存储传递给你的智能体。
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]:
pass
async def update_context(self, agent: ChatCompletionContext) -> UpdateContextResult:
pass
async 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())
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稳定版。
安装或更新命令
pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"
另外大家要根据业务需求,设置使用的LLM,不一定要按照我给大家分享代码中的设置来,如果只是为了测试并看运行结果可直接复制粘贴代码(完整代码)。
好了,以上就是本次分享的全部内容,细心的小伙伴可能会发现该功能有点类似于之前博主给大家分享的Managing State(管理状态)机制。那么它们二者之间的区别是什么呢?博主在这里给大家整理如下:
在微软的AutoGen框架中,Memory和Managing State机制在功能和应用场景上存在一些区别。
Memory
Managing State
综上所述,Memory主要聚焦于存储和利用交互历史和上下文信息,而Managing State更关注智能体在任务执行过程中的状态管理和协调,两者在AutoGen中分别承担着不同但又相互关联的重要角色,共同支持智能体的高效运行和复杂任务处理。
通过本次分享,大家有所收获吗?请大家多去大胆的尝试和使用。博主还是那句话:成功总是在不断的失败中试验出来的,敢于尝试就已经成功了一半。这次分享就到这,如果大家对博主分享的内容感兴趣或有帮助,请点赞和关注。大家的点赞和关注是博主持续分享的动力,博主也希望让更多的人学习到新的知识。