介绍
大家好,博主又来给大家分享知识了。这次又要给大家分享什么呢?哈哈。这次要给大家分享的是微软AutoGen框架的高级且重要的功能:Memory。在微软AutoGen中,Memory(记忆)是一个重要概念,它主要用于存储和管理智能体之间交互的历史信息,有助于智能体在对话和协作过程中参考过往内容,以更智能地推进任务。那我们直接进入正题。
Memory
在几种用例中,维护一个有用事实的存储库是很有价值的,这些事实能在特定步骤即将开始前被智能地添加到智能体的上下文中。这里的典型用例是检索增强生成(RAG)模式,在这种模式下,一个查询被用于从数据库中检索相关信息,然后这些信息会被添加到智能体的上下文中。
AgentChat提供了一种记忆协议,该协议可以进行扩展以实现这一功能。其关键方法包括查询(query)、更新上下文(update_context)、添加(add)、清除(clear)和关闭(close)。
- 添加(add):向记忆存储中添加新的条目。
- 查询(query):从记忆存储中检索相关信息。
- 更新上下文(update_context):通过添加检索到的信息来改变智能体的内部模型上下文(在助理智能体类中使用)。
- 清除(clear):从记忆存储中清除所有条目。
- 关闭(close):清理记忆存储所使用的任何资源。
ListMemory示例
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],
)