LangChain 如何为 Agent 添加记忆
0. 背景
将来 LangChain 要发布 0.2.0 版本,有一些方法将要弃用(deprecated),如何为 Agent 添加记忆这样的需求比较普通,网上的代码大部分使用的是将要弃用的方法,所以今天尝试使用一些新的方法。
1. 创建 llm 变量
from dotenv import load_dotenv, find_dotenv
from langchain_openai import ChatOpenAI
_ = load_dotenv(find_dotenv())
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.3)
2. 创建 prompt 变量
from langchain import hub
prompt = hub.pull("stepbystep/conversational-agent")
3. 创建 tools 变量
from langchain_core.tools import Tool
from langchain_community.utilities import SerpAPIWrapper
search = SerpAPIWrapper()
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events"
)
]
4. 创建 memory 变量
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history")
5. 创建 agent 和 agent_executor 变量
from langchain.agents import create_react_agent, AgentExecutor
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, memory=memory, verbose=True)
6. 测试 agent_executor 是否正常使用 memory
先问一个问题,
agent_executor.invoke({"input": "How many people live in canada?"})
输出结果,
{'input': 'How many people live in canada?',
'chat_history': '',
'output': 'The current population of Canada is 38.25 million.'}
要测试此代理的记忆力,我们可以提出一个后续问题,该问题依赖于先前交换中的信息才能正确回答。
agent_executor.invoke({"input": "what is their national anthem called?"})
输出结果,
{'input': 'what is their national anthem called?',
'my_chat_history': 'Human: How many people live in canada?\nAI: The current population of Canada is 38.25 million.',
'output': 'The national anthem of Canada is called "O Canada".'}
从测试结果上可以看出,在回答后续问题时,大语言模型有参考会话的记忆。
7. 确认 agent_executor 的记忆缓存
agent_executor.memory.buffer
输出结果,
'Human: How many people live in canada?\nAI: The current population of Canada is 38.25 million.\nHuman: what is their national anthem called?\nAI: The national anthem of Canada is called "O Canada".'
从输出结果可以看出,agent_executor 的记忆里面存储了会话的历史。
完结!