跳到主要内容

使用Mem0的带记忆功能的Agent

Open In Colab Open on GitHub

这个笔记本展示了一个结合了智能客服聊天机器人的系统,它集成了以下功能:

  • 用于对话代理的AutoGen
  • Mem0用于内存管理

Mem0 为大型语言模型(LLMs)提供了一个智能、自我改进的记忆层,使开发者能够创建随着每次用户交互而进化的个性化AI体验。更多信息请参考 docs

Mem0采用了一种混合数据库方法,结合了向量、键值和图数据库,以高效地存储和检索不同类型的信息。它将记忆与唯一标识符关联,在存储时提取相关事实和偏好,并使用一种复杂的检索过程,该过程考虑了相关性、重要性和最近性。

Mem0的主要功能包括:1. 全面的内存管理:通过强大的API轻松管理个人用户、代理和会话的长期、短期、语义和情景记忆。2. 自我改进的记忆:一个自适应系统,持续从用户互动中学习,随着时间的推移不断完善其理解。3. 跨平台一致性:确保在各种AI平台和应用程序中的统一用户体验。4. 集中内存控制:简化存储、更新和删除记忆的过程。

这种方法允许在会话之间保持上下文、自适应个性化以及动态更新,使其在创建上下文感知的AI应用方面比传统的检索增强生成(RAG)方法更强大。

该实现展示了如何初始化代理,管理对话记忆,并促进多代理对话,以增强客户支持场景中的问题解决能力。

要求

Requirements

本笔记本需要一些额外的依赖项,可以通过pip安装:

pip install autogen-agentchat~=0.2 mem0ai

如需更多信息,请参考安装指南

获取API密钥

请从Mem0 Platform获取MEM0_API_KEY

import os

from mem0 import MemoryClient

from autogen import ConversableAgent

os.environ["OPENAI_API_KEY"] = "your_api_key"
os.environ["MEM0_API_KEY"] = "your_api_key"

初始化代理和内存

使用‘gpt-4o’模型和mem0客户端设置对话代理。我们将利用客户端的方法来存储和访问记忆。

agent = ConversableAgent(
"chatbot",
llm_config={"config_list": [{"model": "gpt-4o", "api_key": os.environ.get("OPENAI_API_KEY")}]},
code_execution_config=False,
function_map=None,
human_input_mode="NEVER",
)

memory = MemoryClient()

初始化Best Buy客服聊天机器人的对话历史。它包含用户和助手之间的消息交换列表,结构化为带有“role”和“content”键的字典。整个对话使用memory.add()方法存储在内存中,并与标识符“customer_service_bot”关联。

conversation = [
{
"role": "assistant",
"content": "Hi, I'm Best Buy's chatbot!\n\nThanks for being a My Best Buy TotalTM member.\n\nWhat can I help you with?",
},
{
"role": "user",
"content": 'Seeing horizontal lines on our tv. TV model: Sony - 77" Class BRAVIA XR A80K OLED 4K UHD Smart Google TV',
},
{
"role": "assistant",
"content": "Thanks for being a My Best Buy Total™ member. I can connect you to an expert immediately - just one perk of your membership!\n\nSelect the button below when you're ready to chat.",
},
{
"role": "assistant",
"content": "Good evening, thank you for choosing Best Buy, Fnu. My name is Lovely. I hope you are doing well. I'm sorry to hear that you're seeing horizontal lines on your TV.\n\nI'm absolutely committed to exploring all possible ways to assist you to fix this issue.\n\nTo ensure that we are on the right account, may I please have your email address registered with your Best Buy account?",
},
{"role": "user", "content": "dd@gmail.com"},
{
"role": "assistant",
"content": "Perfect! Thank you for providing all the details, surely you have made my job easier by doing this. I really appreciate it.\n\nI also want to take a moment to express our heartfelt appreciation for your trust and loyalty. Thank you for being an amazing customer of BestBuy Total.\n\nCould you please help me with the order number or product's details to check it quickly?\n\nSamsung - 49\" Odyssey OLED G9 (G95SC) DQHD 240Hz 0.03ms G-Sync Compatible Curved Smart Gaming Monitor - Silver - just to confirm this is the item, right?",
},
{"role": "user", "content": "Order number: 112217629"},
{
"role": "assistant",
"content": "Superb! Thank you for confirmation.\n\nThank you for your patience. After exploring all possible solutions, I can help you to arrange a home repair appointment for your device. Our Geek Squad experts will visit your home to inspect and fix your device.\n\nIt's great that you have a protection plan - rest assured, we've got your back! As a valued Total member, you can avail this service at a minimal service fee. This fee, applicable to all repairs, covers the cost of diagnosing the issue and any small parts needed for the repair. It's part of our 24-month free protection plan.\n\nPlease click here to review the service fee and plan coverage details -\n\nhttps://www.bestbuy.com/site/best-buy-membership/best-buy-protection/pcmcat1608643232014.c?id=pcmcat1608643232014#jl-servicefees\n\nFnu - just to confirm shall I proceed to schedule the appointment?",
},
{"role": "user", "content": "Yes please"},
{"role": "assistant", "content": "When should I schedule the appointment?"},
{"role": "user", "content": "Schedule it for tomorrow please"},
]

memory.add(messages=conversation, user_id="customer_service_bot")
{'message': 'ok'}

代理推理

我们向代理提出一个问题,利用mem0检索相关的记忆。然后,代理根据问题和检索到的上下文信息制定回答。

data = "I forgot the order numnber, can you quickly tell me?"

relevant_memories = memory.search(data, user_id="customer_service_bot")
flatten_relevant_memories = "\n".join([m["memory"] for m in relevant_memories])

prompt = f"""Answer the user question considering the memories. Keep answers clear and concise.
Memories:
{flatten_relevant_memories}
\n\n
Question: {data}
"""

reply = agent.generate_reply(messages=[{"content": prompt, "role": "user"}])
print(reply)
Sure, your order number is 112217629.

多代理会话

初始化两个AI代理:一个用于解决客户问题的“manager”,和一个用于收集客户问题信息的“customer_bot”,两者都使用GPT-4。然后,它为给定问题检索相关记忆,将这些记忆与问题结合成一个提示。这个提示可以由manager或customer_bot使用,以生成具有上下文信息的响应。

manager = ConversableAgent(
"manager",
system_message="You are a manager who helps in resolving customer issues.",
llm_config={"config_list": [{"model": "gpt-4", "temperature": 0, "api_key": os.environ.get("OPENAI_API_KEY")}]},
human_input_mode="NEVER",
)

customer_bot = ConversableAgent(
"customer_bot",
system_message="You are a customer service bot who gathers information on issues customers are facing. Keep answers clear and concise.",
llm_config={"config_list": [{"model": "gpt-4", "temperature": 0, "api_key": os.environ.get("OPENAI_API_KEY")}]},
human_input_mode="NEVER",
)
data = "When is the appointment?"

relevant_memories = memory.search(data, user_id="customer_service_bot")
flatten_relevant_memories = "\n".join([m["memory"] for m in relevant_memories])

prompt = f"""
Context:
{flatten_relevant_memories}
\n\n
Question: {data}
"""
result = manager.send(prompt, customer_bot, request_reply=True)
manager (to customer_bot):


Context:
Scheduled an appointment for a home repair for tomorrow
Order number is 112217629
TV model is Sony - 77" Class BRAVIA XR A80K OLED 4K UHD Smart Google TV
User's email address is dd@gmail.com



Question: When is the appointment?


--------------------------------------------------------------------------------
customer_bot (to manager):

The appointment is scheduled for tomorrow.

--------------------------------------------------------------------------------