当前位置:   article > 正文

【2024最全最细LangChain教程-13】Agent智能体(二)_zeroshotagent

zeroshotagent

【2024最全最细LangChain教程-12】Agent智能体(一)-CSDN博客

     B站视频:【2024最全最细】Langchain教学之Agent with memory_哔哩哔哩_bilibili

        上节课我们介绍了Agent,当时我们构造的是一个没有memory的Agent,下面我们看看如何构造一个有memory的Agent:

1. 构造一个google搜索工具

        google搜索工具需要自己去google的网站去申请账号,google每个月只有100次的免费调用额度,真抠:

  1. from langchain_community.utilities import GoogleSearchAPIWrapper
  2. search = GoogleSearchAPIWrapper()
  3. # 注意tools是一个列表,只不过这里只有一个元素,回想一下上一节课的内容
  4. tools = [
  5. Tool(
  6. name="Google Search",
  7. description="useful when you need to answer questions about current events",
  8. func=search.run,
  9. )
  10. ]
  11. tools[0].run("what is the performance of NASDAQ today?")

2. 构造一个ZeroShotAgent with memory

        这里注意在构造prompt的时候,用了一个ZeroShotAgent.create_prompt()方法,这种方法我们之前好像是没有见过的,input_variables注意除了input,chat_history还要有agent_scratchpad,这个是agent添加memory所需的:

  1. import os
  2. from langchain_core.prompts import PromptTemplate
  3. from langchain_openai import OpenAI
  4. from langchain.agents import AgentExecutor,Tool,ZeroShotAgent
  5. from langchain.chains import LLMChain
  6. from langchain.memory import ConversationBufferMemory
  7. prefix = """
  8. Have a conversation with a human, answering the following questions as best you can.
  9. If you can answer the question by yourself,dont' use the tools.
  10. You have access to the following tools: """
  11. suffix = """Begin!"
  12. Previous Conversation:{chat_history}
  13. Question: {input}
  14. Thought: {agent_scratchpad}"""
  15. prompt = ZeroShotAgent.create_prompt(
  16. tools,
  17. prefix=prefix,
  18. suffix=suffix,
  19. input_variables=["input", "chat_history", "agent_scratchpad"],
  20. )
  21. memory = ConversationBufferMemory(memory_key="chat_history")
  22. memory.clear()
  23. memory.load_memory_variables({})

                然后我们和之前一样构造agent和 agent_chain,注意在agent_chain里添加memory:

  1. llm = OpenAI(
  2. temperature=0,
  3. openai_api_key = os.getenv("OPENAI_API_KEY"),
  4. base_url = os.getenv("OPENAI_BASE_URL")
  5. )
  6. llm_chain = LLMChain(llm=llm, prompt=prompt)
  7. agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
  8. agent_chain = AgentExecutor.from_agent_and_tools(
  9. agent=agent, tools=tools, verbose=True, memory=memory, max_iterations = 5
  10. )
  11. agent_chain.invoke({"input":"How many people live in China?"})

        我们来调用看下结果:

        继续提问,也可以得到答案:

        但是我发现了一个问题就是,如果你再问他一个问题,who are you ,Agent就困惑了,他不知道需不需要去使用工具,结果进入了一个死循环,这是Agent的一个问题。后面我们看可否通过提示词去优化这个问题:

3. 构造一个create_react_agent with memory

        原理相同,构造细节步骤有不同,不再赘述了,直接看代码即可:

  1. import os
  2. from langchain_openai import OpenAI
  3. from langchain import hub
  4. from langchain_core.prompts import PromptTemplate
  5. from langchain.agents import AgentExecutor, create_react_agent
  6. template='''
  7. Answer the following questions as best you can.
  8. Try to answer the question by yourself.
  9. If not necessary, don't use the tools.
  10. You have access to the following tools:{tools}
  11. Use the following format:
  12. Question: the input question you must answer
  13. Thought: you should always think about what to do
  14. Action: the action to take, should be one of [{tool_names}]
  15. Action Input: the input to the action
  16. Observation: the result of the action
  17. ... (this Thought/Action/Action Input/Observation can repeat N times)
  18. Thought: I now know the final answer
  19. Final Answer: the final answer to the original input question
  20. Begin!
  21. Previous Conversation:{chat_history}
  22. Question: {input}
  23. Thought:{agent_scratchpad}
  24. '''
  25. prompt = PromptTemplate.from_template(template)
  26. print(prompt)
  27. llm = OpenAI(
  28. temperature=0,
  29. openai_api_key = os.getenv("OPENAI_API_KEY"),
  30. base_url = os.getenv("OPENAI_BASE_URL")
  31. )
  32. from langchain_community.utilities import GoogleSearchAPIWrapper
  33. search = GoogleSearchAPIWrapper()
  34. tools = [
  35. Tool(
  36. name="Google Search",
  37. description="A search engine you can use when you need to know latest news or data",
  38. func=search.run,
  39. ),
  40. ]
  41. memory = ConversationBufferMemory(memory_key="chat_history")
  42. agent = create_react_agent(llm, tools, prompt)
  43. agent_executor = AgentExecutor(agent=agent, tools=tools, memory = memory, max_iterations = 3,handle_parsing_errors=True,verbose= True)
  44. agent_executor.invoke({"input":"hi,how are you?"})

        这个agent在运行的时候,也会有不知道何时使用工具的问题。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/929263
推荐阅读
相关标签
  

闽ICP备14008679号