Skip to main content

为Agent添加基于数据库的消息存储的消息记忆

本笔记本介绍了如何为Agent添加记忆,其中记忆使用外部消息存储。在阅读本笔记本之前,请先阅读以下笔记本,因为本笔记本将在它们的基础上构建:

为了将具有外部消息存储的记忆添加到Agent中,我们将执行以下步骤:

  1. 我们将创建一个RedisChatMessageHistory,以连接到外部数据库来存储消息。
  2. 我们将使用该聊天历史记录创建一个LLMChain作为记忆。
  3. 我们将使用该LLMChain创建一个自定义Agent。

为了完成这个练习,我们将创建一个简单的自定义Agent,该Agent可以访问搜索工具并利用ConversationBufferMemory类。

from langchain.agents import ZeroShotAgent, Tool, AgentExecutor  
from langchain.memory import ConversationBufferMemory
from langchain.memory.chat_memory import ChatMessageHistory
from langchain.memory.chat_message_histories import RedisChatMessageHistory
from langchain import OpenAI, LLMChain
from langchain.utilities import GoogleSearchAPIWrapper

search = GoogleSearchAPIWrapper()
tools = [
Tool(
name="Search",
func=search.run,
description="有助于回答有关当前事件的问题",
)
]

prefix = """与人类进行对话,尽力回答以下问题。您可以使用以下工具:"""
suffix = """开始!

{chat_history}
问题:{input}
{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"],
)

message_history = RedisChatMessageHistory(
url="redis://localhost:6379/0", ttl=600, session_id="my-session"
)

memory = ConversationBufferMemory(
memory_key="chat_history", chat_memory=message_history
)

llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_chain = AgentExecutor.from_agent_and_tools(
agent=agent, tools=tools, verbose=True, memory=memory
)

agent_chain.run(input="加拿大有多少人口?")
agent_chain.run(input="他们的国歌叫什么?")

我们可以看到,Agent记住了前一个问题是关于加拿大的,并正确地询问了Google搜索加拿大的国歌名称。

为了对比,让我们看看没有记忆的Agent的表现。

prefix = """与人类进行对话,尽力回答以下问题。您可以使用以下工具:"""  
suffix = """开始!

问题:{input}
{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(
tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"]
)
llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_without_memory = AgentExecutor.from_agent_and_tools(
agent=agent, tools=tools, verbose=True
)

agent_without_memory.run("加拿大有多少人口?")
agent_without_memory.run("他们的国歌叫什么?")

我们可以看到,没有记忆的Agent无法记住前一个问题,因此无法正确回答关于加拿大国歌的问题。