【2024最全最细LangChain教程-12】Agent智能体(一)-CSDN博客
B站视频:【2024最全最细】Langchain教学之Agent with memory_哔哩哔哩_bilibili
上节课我们介绍了Agent,当时我们构造的是一个没有memory的Agent,下面我们看看如何构造一个有memory的Agent:
google搜索工具需要自己去google的网站去申请账号,google每个月只有100次的免费调用额度,真抠:
from langchain_community.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
# 注意tools是一个列表,只不过这里只有一个元素,回想一下上一节课的内容
tools = [
Tool(
name="Google Search",
description="useful when you need to answer questions about current events",
func=search.run,
)
]
tools[0].run("what is the performance of NASDAQ today?")
这里注意在构造prompt的时候,用了一个ZeroShotAgent.create_prompt()方法,这种方法我们之前好像是没有见过的,input_variables注意除了input,chat_history还要有agent_scratchpad,这个是agent添加memory所需的:
import os
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI
from langchain.agents import AgentExecutor,Tool,ZeroShotAgent
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
prefix = """
Have a conversation with a human, answering the following questions as best you can.
If you can answer the question by yourself,dont' use the tools.
You have access to the following tools: """
suffix = """Begin!"
Previous Conversation:{chat_history}
Question: {input}
Thought: {agent_scratchpad}"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"],
)
memory = ConversationBufferMemory(memory_key="chat_history")
memory.clear()
memory.load_memory_variables({})
然后我们和之前一样构造agent和 agent_chain,注意在agent_chain里添加memory:
llm = OpenAI(
temperature=0,
openai_api_key = os.getenv("OPENAI_API_KEY"),
base_url = os.getenv("OPENAI_BASE_URL")
)
llm_chain = LLMChain(llm=llm, 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, max_iterations = 5
)
agent_chain.invoke({"input":"How many people live in China?"})
我们来调用看下结果:
继续提问,也可以得到答案:
但是我发现了一个问题就是,如果你再问他一个问题,who are you ,Agent就困惑了,他不知道需不需要去使用工具,结果进入了一个死循环,这是Agent的一个问题。后面我们看可否通过提示词去优化这个问题:
原理相同,构造细节步骤有不同,不再赘述了,直接看代码即可:
import os
from langchain_openai import OpenAI
from langchain import hub
from langchain_core.prompts import PromptTemplate
from langchain.agents import AgentExecutor, create_react_agent
template='''
Answer the following questions as best you can.
Try to answer the question by yourself.
If not necessary, don't use the tools.
You have access to the following tools:{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Previous Conversation:{chat_history}
Question: {input}
Thought:{agent_scratchpad}
'''
prompt = PromptTemplate.from_template(template)
print(prompt)
llm = OpenAI(
temperature=0,
openai_api_key = os.getenv("OPENAI_API_KEY"),
base_url = os.getenv("OPENAI_BASE_URL")
)
from langchain_community.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
tools = [
Tool(
name="Google Search",
description="A search engine you can use when you need to know latest news or data",
func=search.run,
),
]
memory = ConversationBufferMemory(memory_key="chat_history")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, memory = memory, max_iterations = 3,handle_parsing_errors=True,verbose= True)
agent_executor.invoke({"input":"hi,how are you?"})
这个agent在运行的时候,也会有不知道何时使用工具的问题。