LangChain 的 AI 代理的迷人思维

我们将看另一种类型的代理,称为 ReAct 代理。这里的“ReAct”并不代表 React JavaScript 框架。它是 Reason(推理)+ Action(行动)= ReAct 的组合。

让我们先创建 ReAct 代理,然后我们将学习它如何工作。

对于这个代理,我们也将有一个LLM,一个提示,和一些工具。让我们准备好它们。

LLM

from langchain_openai import ChatOpenAI
llm = ChatOpenAI(api_key="Your OpenAI API key here")

The ReAct Agent Prompt ReAct 代理提示

对于 ReAct 代理,我们将使用另一个适合 ReAct 代理工作机制的提示。
它被称为“hwchase17/react”。

from langchain import hub
prompt = hub.pull("hwchase17/react")

Tools 工具

Retriever Tool 检索器工具

检索工具从包含外部来源数据的向量数据库中检索相关数据,在这个例子中,是一个网站,并使用该数据作为与网站相关的任何问题的上下文。有关检索工具的更多信息,请阅读我的上一篇文章:使用 LangChain 的检索链初学者指南

from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("<https://www.dasa.org>")
docs = loader.load()
from langchain_text_splitters import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
from langchain_community.vectorstores import FAISS
vector = FAISS.from_documents(documents, embeddings)
retriever = vector.as_retriever()
from langchain.tools.retriever import create_retriever_tool
retriever_tool = create_retriever_tool (retriever, "DASA_search", "Search for information about DASA. For any questions about DASA, you must use this tool")

Search Tool 搜索工具

import os
os.environ['TAVILY_API_KEY'] = "<Your Tavily API Key here>"
from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults()

我们将所有工具添加到工具列表中。
tools = [retriever_tool, search]

Creating The ReAct Agent 创建 ReAct 代理

要创建 ReAct 代理,我们导入 create_react_agent 库和 AgentExecutor 库。

from langchain.agents import create_react_agent
from langchain.agents import AgentExecutor

现在,是时候创建 ReAct 代理了。

agent = create_react_agent(llm,tools,prompt)
agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True)

Invoking the ReAct agent 调用 ReAct 代理

现在,我们的 AI ReAct 代理已经准备好被调用了。
agent_executor.invoke({“input”:“What technological advancements have significantly impacted renewable energy production in the last decade?”})

Output 输出

The output is: 输出是:
> Entering new AgentExecutor chain…> 进入新的 AgentExecutor 链…_
_
我应该搜索有关可再生能源生产中最近技术进步的信息。_
_动作:tavily_search_results_json _
动作输入:可再生能源生产中的最近技术进步
我应该搜索更多关于搜索结果中提到的每项技术进步的具体信息。

动作:tavily_search_results_json _
动作输入:超高效太阳能电池 突破性技术
_
我还应该搜索更多关于数字包容、清洁能源技术和脱碳等其他提到的技术进步的信息。

_动作:tavily_search_results_json _
动作输入:数字包容倡议
_
我还应该搜索更多关于清洁能源技术和脱碳的信息。动作:tavily_search_results_json _
动作输入:清洁能源技术进步
> Finished chain. > 完成链。

{'input': 'What technological advancements have significantly impacted renewable energy production in the last decade?',
'output': 'Some of the technological advancements include super-efficient solar cells using perovskites, digital inclusion initiatives to bridge the digital divide, and advancements in clean energy technologies aimed at decarbonization.'}

ReAct 代理的迷人思维

ReAct 代理究竟是如何思考的?要了解 AI 代理的思维,我们需要知道发送给 AI 代理的提示。

要了解发送给 ReAct 代理的提示,以及 AI ReAct 代理在每个步骤的响应,我们使用由 LangChain 提供的一个名为 LangSmith 的跟踪工具。

首先,从 https://smith.langchain.com/ 获取一个 API 密钥。然后,将以下代码放入你的程序中:

os.environ["LANGCHAIN_TRACING_V2"]="true"
os.environ["LANGCHAIN_API_KEY"]="<Your API Key here>"

The Magical Prompt that Makes the AI Agent Think

让 AI 代理思考的神奇提示
Le
让我们看看发送给 AI 代理的提示。
_
尽你所能回答以下问题。你可以使用以下工具:

DASA_search:搜索有关 DASA 的信息。对于任何关于 DASA 的问题,你必须使用这个工具

tavily_search_results_json:一个针对全面、准确和可信赖结果进行优化的搜索引擎。当你需要回答有关当前事件的问题时非常有用。输入应该是一个搜索查询。_
_Use the following format:使用以下格式:
_
问题:你必须回答的输入问题

思考:你应该总是思考要做什么

行动:要采取的行动,应该是 [DASA_search, tavily_search_results_json] 中的一个

行动输入:对行动的输入

观察:行动的结果
… (this Thought/Action/Action Input/Observation can repeat N times)
…(这个思考/行动/行动输入/观察可以重复 N 次)
Thought: I now know the final answer
思考:我现在知道最终答案
Final Answer: the final answer to the original input question
最终答案:原始输入问题最终答案_

Begin! 开始!
_
问题:在过去的十年中,哪些技术进步对可再生能源生产产生了重大影响?
Thought: 思考:_

上述提示使用了来自 hwchase17/react 的提示模板。提示以以下内容结束:
Thought: 思考:

这表明要向 LLM 输出一个想法,然后根据这个想法使用其中一种工具进行操作。而且,这就是人工智能代理被制造成思考的方式。它被告知先思考然后再行动!它按照命令这样做了。

下面是从 LangSmith 收集的人工智能行动的痕迹。

AI 人工智能

我应该搜索有关可再生能源生产中近期技术进步的信息。
Action: tavily_search_results_json
动作:tavily_search_results_json
Action Input: recent technological advancements in renewable energy production
动作输入:可再生能源生产中的近期技术进步_

下一个发送给 AI 代理的提示是:

Answer the following questions as best you can. You have access to the following tools:
DASA_search: Search for information about DASA. For any questions about DASA, you must use this tool
tavily_search_results_json: A search engine optimized for comprehensive, accurate, and trusted results. Useful for when you need to answer questions about current events. Input should be a search query.
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 [DASA_search, tavily_search_results_json]
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!
Question: What technological advancements have significantly impacted renewable energy production in the last decade?
Thought:I should search for information on recent technological advancements in renewable energy production.
Action: tavily_search_results_json
Action Input: recent technological advancements in renewable energy production
Observation: [{'url': '<https://www.weforum.org/agenda/2023/09/renewable-energy-innovations-climate-emergency/>', 'content': 'The first alliance to accelerate digital inclusion\\nOctober 20, 2023\\nThe first alliance to accelerate digital inclusion\\nOctober 20, 2023\\nAbout Us\\nEvents\\nMedia\\nMore from the Forum\\nPartners & Members\\nLanguage Editions\\nPrivacy Policy & Terms of Service\\n© 2023 World Economic Forum Kate Whiting\\nNovember 8, 2023\\nAnnual Meeting 2023 | Cooperation in a Fragmented World\\nWe need to move beyond the idea that AI is the solution to everything, expert says\\nJessica Wanger\\nOctober 23, 2023\\n Image:\\xa0REUTERS/Nathan Frandino\\nListen to the article\\nHow is the World Economic Forum fighting the climate crisis?\\nCreate a free account and access your personalized content collection with our latest publications and analyses.\\n Andrea Willige\\nNovember 13, 2023\\nBreathing new life into the SDGs: What is the UN Summit of the Future in 2024?\\n The Agenda Weekly\\nA weekly update of the most important issues driving the global agenda\\nYou can unsubscribe at any time using the link in our emails.'}, {'url': '<https://www.iea.org/news/rapid-progress-of-key-clean-energy-technologies-shows-the-new-energy-economy-is-emerging-faster-than-many-think>', 'content': "Fossil Fuels\\nRenewables\\nElectricity\\nLow-Emission Fuels\\nTransport\\nIndustry\\nBuildings\\nEnergy Efficiency and Demand\\nCarbon Capture, Utilisation and Storage\\nDecarbonisation Enablers\\nGlobal Energy Transitions Stocktake\\nCritical Minerals\\nRussia's War on Ukraine\\nClimate Change\\nGlobal Energy Crisis\\nInvestment\\nSaving Energy\\nEnergy Security\\nNet Zero Emissions\\nEnergy Efficiency\\nData explorers\\nUnderstand and manipulate data with easy to use explorers and trackers\\nData sets\\nFree and paid data sets from across the energy system available for download\\nPolicies database\\nPast, existing or planned government policies and measures\\nChart Library\\nAccess every chart published across all IEA reports and analysis\\nWorld Energy Outlook 2023\\nFlagship report — October 2023\\nEnergy Efficiency 2023\\nFuel report — November 2023\\nLeveraging Fossil Fuel Capabilities for Clean Energy Transitions\\nAssessment of opportunities in Oman\\nCountry report — November 2023\\nNet Zero Roadmap: The pace of deployment of some clean energy technologies – such as solar PV and electric vehicles – shows what can be achieved with sufficient ambition and policy action, but faster change is urgently needed across most components of the energy system to achieve net zero emissions by 2050, according to the IEA’s latest evaluation of global progress.\\n The IEA also released today the newly redesigned Clean Energy Technology Guide, an interactive digital database that allows users to visualise the readiness and geographical distribution of more than 500 different innovative technologies or components across the global energy system, along with the accompanying Clean Energy Demonstration Projects Database.\\n Stronger policy support and greater investment are needed across a wide range of different technologies, in all regions of the world, to enable a broader and faster shift towards clean energy to keep net zero emissions by 2050 within reach.\\n While progress can be observed across all of the 50-plus components of the energy system evaluated in Tracking Clean Energy Progress, the majority are not yet on a path consistent with net zero emissions by 2050."}, {'url': '<https://www.technologyreview.com/2024/01/08/1085124/super-efficient-solar-cells-breakthrough-technologies/>', 'content': '10 Breakthrough Technologies\\nby Emma Foehringer Merchant\\nShare\\nPopular\\nDeep Dive\\nClimate change and energy\\nWhat’s coming next for fusion research\\nA year ago, scientists generated net energy with a fusion reactor. Super-efficient solar cells: 10 Breakthrough Technologies 2024\\nSolar cells that combine traditional silicon with cutting-edge perovskites could push the efficiency of solar panels to new heights.\\n In May, UK-based Oxford PV said it had reached an efficiency of 28.6% for a commercial-size perovskite tandem cell, which is significantly larger than those used to test the materials in the lab, and it plans to deliver its first panels and ramp up manufacturing in 2024. The latest iteration of a legacy\\nAdvertise with MIT Technology Review\\n© 2024 MIT Technology Review\\nAbout\\nHelp Beyond Silicon, Caelux, First Solar, Hanwha Q Cells, Oxford PV, Swift Solar, Tandem PV\\n3 to 5 years\\nIn November 2023, a buzzy solar technology broke yet another world record for efficiency.'}, {'url': '<https://www.technologyreview.com/2024/04/24/1091129/fully-decarbonized-world-renewable-energy/>', 'content': 'As more and more clean, renewable energy comes online, we need to continue with policies that support research and development on the new technologies required to recover all kinds of materials ...'}, {'url': '<https://www.sciencedirect.com/science/article/pii/S0960148121011162>', 'content': 'This article presents some of the main findings from the SDEWES conferences of 2021 within the field of renewable energy. More specifically, results are summarized and contextualised within solar energy and thermal comfort, wind power resource assessment, and biogas and biomass resources and technology. The two last sections deal more broadly ...'}]
Thought:

在第二个提示中,第一个提示的结果作为观察结果附加,后面跟着思考:

然后,这促使 LLM 以下面的下一个思考和行动做出回应。
我应该在搜索结果中提到的每项技术进步上搜索更具体的信息。
Action: tavily_search_results_json
动作:tavily_search_results_json
Action Input: super-efficient solar cells breakthrough technologies
动作输入:超高效太阳能电池突破性技术_.
这会持续三次。以下是每次步骤中人工智能代理的响应。

我还应该搜索更多关于数字包容、清洁能源技术和脱碳等其他提到的技术进步的信息。
Action: tavily_search_results_json
动作:tavily_search_results_json
Action Input: digital inclusion initiatives_
行动输入:数字包容性倡议_
我还应该搜索更多关于清洁能源技术和脱碳的信息。
Action: tavily_search_results_json
动作:tavily_search_results_json
Action Input: clean energy technologies advancements_
动作输入:清洁能源技术进步_
现在我知道在过去十年中对可再生能源生产产生重大影响的技术进步。

最终答案:一些技术进步包括使用钙钛矿的超高效太阳能电池、数字包容倡议以弥合数字鸿沟,以及旨在脱碳的清洁能源技术进步。

所有这些步骤都记录在名为 intermediate_steps 的列表中。发送到 intermediate_steps 的步骤有两种类型:AgentAction 和 AgentFinish。当类型为 AgentFinish 时,意味着 AI 代理必须完成其任务,并且输出已准备好提供给用户。

The Mystery Behind the AI Agent

AI 代理背后的奥秘

那么,总结一下,AI 代理行为背后的奥秘在于发送给 AI 代理的提示。它指示 AI 代理使用其中一种工具进行思考和行动,并重复 N 次。这使得 AI 代理通过生成一个想法,然后根据这个想法采取行动来进行推理。

我们的思维也以相同的方式工作吗?我们推理是因为别人告诉我们这样做吗?或者,我们是否拥有独立于他人告知之外的推理能力?或者,我们被告知了很多次,以至于它被硬编码到我们的大脑中?在 LLM 内部能否做到同样的事情?这种魅力还在继续!
In the next article, we will look at another ability of AI agents which is to self-reflect, and see the mystery behind self-reflection.
在下一篇文章中,我们将探讨人工智能代理的另一种能力,即自我反思,并揭开自我反思背后的奥秘。

  • 27
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值