LangChain 如何为 Agent 添加记忆

本文介绍了如何在LangChain0.2.0版本中为Agent添加记忆功能,包括创建llm、prompt、tools、memory变量,以及测试和确认agent_executor对内存的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 的记忆里面存储了会话的历史。

完结!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值