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 人工智能

_I should search for information on recent technological advancements in renewable energy production.我应该搜索有关可再生能源生产中近期技术进步的信息。
Action: tavily_search_results_json_动作:tavily_search_results_json
Action Input: recent technological advancements in renewable energy production_动作输入:可再生能源生产中的近期技术进步

The next prompt send to the AI agent is:
下一个发送给 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:

In the second prompt, the result of the first prompt is appended as Observation: followed by Thought:
在第二个提示中,第一个提示的结果作为观察结果附加,后面跟着思考:
And, this prompts the LLM to respond with the next thought and action as below.
然后,这促使 LLM 以下面的下一个思考和行动做出回应。
_I should search for more specific information on each of the technological advancements mentioned in the search results.我应该在搜索结果中提到的每项技术进步上搜索更具体的信息。
Action: tavily_search_results_json_动作:tavily_search_results_json
Action Input: super-efficient solar cells breakthrough technologies_动作输入:超高效太阳能电池突破性技术

This continues for three times. Below are the responses of the AI agent at each step.
这会持续三次。以下是每次步骤中人工智能代理的响应。
_I should also search for more information on other mentioned technological advancements like digital inclusion, clean energy technologies, and decarbonization.我还应该搜索更多关于数字包容、清洁能源技术和脱碳等其他提到的技术进步的信息。
Action: tavily_search_results_json_动作:tavily_search_results_json
Action Input: digital inclusion initiatives_行动输入:数字包容性倡议

_I should also search for more information on clean energy technologies and decarbonization.我还应该搜索更多关于清洁能源技术和脱碳的信息。
Action: tavily_search_results_json_动作:tavily_search_results_json
Action Input: clean energy technologies advancements_动作输入:清洁能源技术进步

_I now know the technological advancements that have significantly impacted renewable energy production in the last decade._现在我知道在过去十年中对可再生能源生产产生重大影响的技术进步。
Final Answer: 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.最终答案:一些技术进步包括使用钙钛矿的超高效太阳能电池、数字包容倡议以弥合数字鸿沟,以及旨在脱碳的清洁能源技术进步。
All these steps are recorded in a list named intermediate_steps. There are two types of steps send to intermediate_steps: AgentAction and AgentFinish. When the type is AgentFinish, then it means that AI agent has to come to the end of its task and the output is ready to be provided to the user.
所有这些步骤都记录在名为 intermediate_steps 的列表中。发送到 intermediate_steps 的步骤有两种类型:AgentAction 和 AgentFinish。当类型为 AgentFinish 时,意味着 AI 代理必须完成其任务,并且输出已准备好提供给用户。

The Mystery Behind the AI Agent

AI 代理背后的奥秘
So, to recap, the mystery behind the actions of an AI agent lies in the prompt send to the AI Agent. It instructs the AI agent to think and act by using one of the tools, and repeat it N number of times. This makes the AI Agent to reason by generating a thought and then acting based on the thought.
那么,总结一下,AI 代理行为背后的奥秘在于发送给 AI 代理的提示。它指示 AI 代理使用其中一种工具进行思考和行动,并重复 N 次。这使得 AI 代理通过生成一个想法,然后根据这个想法采取行动来进行推理。
Do our minds also work the same way? Do we also reason because we are told to? Or, is there a reasoning ability part from being told by others? Or, are we told so many times, that it gets hardwired into our brains. Can the same thing be done within an LLM? The fascination continues!
我们的思维也以相同的方式工作吗?我们推理是因为别人告诉我们这样做吗?或者,我们是否拥有独立于他人告知之外的推理能力?或者,我们被告知了很多次,以至于它被硬编码到我们的大脑中?在 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.
在下一篇文章中,我们将探讨人工智能代理的另一种能力,即自我反思,并揭开自我反思背后的奥秘。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/593059.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ubuntu20配置深度学习环境

目录 系统环境安装anaconda文件的安装anaconda环境配置anaconda换中科大源常用的anaconda命令 安装显卡驱动安装CUDA下载cudnn安装pytorch更换conda源选择对应的pytorch版本进行安装 系统环境 ubuntu20&#xff0c;安装了ros noetic。 参考博客主要有&#xff1a; https://g…

【Trick】conda安装python依赖时出现429 Client Error

起因 我在根据yml文件安装依赖和创建虚拟环境时&#xff0c;出现报错&#xff0c;主要报错信息为以下两点&#xff1a; 【1】Collecting package metadata (repodata.json): failed 【2】requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https…

Git在无法访问github的访问方法

Git无法下载github上的源代码 代理的情况 问题&#xff1a;Failed to connect to github.com port 443 after 21100 ms: Couldnt connect to server 提示我们需要为Git单独配置代理。 查看我们的代理端口  为git 设置全局代理 git config --global http.proxy 127.0.0.1:&l…

【LeetCode刷题记录】简单篇-104-二叉树的最大深度

【题目描述】 给定一个二叉树 root &#xff0c;返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 【测试用例】 示例1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;3 示例2&#xff1a; 输入&#…

颜值高的浏览器 ARC

可以使用 chrome 的插件&#xff0c;和书签&#xff0c;现在可以下载&#xff0c;别的不说这个ui 的颜值是可以的, 而且很丝滑

思考题 —— Windows 登录密码

1.windows登录的明文密码&#xff0c;存储过程是怎么样的&#xff1f;密文存放在哪个文件下&#xff1f;该文件是否可以打开&#xff0c;并且查看到密文&#xff1f; 系统通过保存密码的哈希值来确保安全性&#xff0c;进行加密存储的方法通常为NTLM或Kerberos身份认证协议。该…

SFOS1:开发环境搭建

一、简介 最近在学习sailfish os的应用开发&#xff0c;主要内容是QmlPython。所以&#xff0c;在开发之前需要对开发环境&#xff08;virtualBox官方SDKcmake编译器python&#xff09;进行搭建。值得注意的是&#xff0c;我的开发环境是ubuntu22.04。如果是windows可能大同小异…

Codeforces Round 943 (Div. 3 ABCDEFG1G2题) 视频讲解

A. Maximize? Problem Statement You are given an integer x x x. Your task is to find any integer y y y ( 1 ≤ y < x ) (1\le y<x) (1≤y<x) such that gcd ⁡ ( x , y ) y \gcd(x,y)y gcd(x,y)y is maximum possible. Note that if there is more tha…

Webshell绕过技巧分析之-base64/HEX/Reverse/Html/Inflate/Rot13

在网络安全运营&#xff0c;护网HVV&#xff0c;重保等活动的过程中&#xff0c;webshell是一个无法绕过的话题。通常出现的webshell都不是以明文的形式出现&#xff0c;而是针对webshell关键的内容进行混淆&#xff0c;编码来绕过网络安全产品&#xff08;IDS&#xff0c;WAF&…

Linux USB转串口设备路径的查找方法

1、USB转串口设备 USB转串口设备是在嵌入式软件开发过程中经常要使用的&#xff0c;常常用于对接各种各样的串口设备。如果一台linux主机上使用多个usb转串口设备时&#xff0c;应用程序中就需要知道自己操作的是哪个串口设备。串口设备在系统上电时&#xff0c;由于驱动加载的…

短剧在线搜索表格-送模板

短剧在线搜索表格-附模板 介绍电脑界面手机界面送附加功能&#xff1a;反馈缺失短剧送&#xff1a;资源更新源头获取 介绍 你好&#xff01; 这是你第一次使用 金山在线文档 所生成的短剧搜索表格&#xff0c;支持批量导入自己转存的短剧名字和链接&#xff0c;实现在线搜索&a…

Kotlin基础知识总结(三万字超详细)

1、条件语句 &#xff08;1&#xff09;if条件 if条件表达式&#xff0c;每一个分支最后一条语句就是该分支的返回值。适用于每个分支返回值类型一致这种情况。 fun getDegree(score: Int): String{val result: String if(score 100){"非常优秀"}else if(score …

Docker使用进阶篇

文章目录 1 前言2 使用Docker安装常用镜像示例2.1 Docker安装RabbitMQ2.2 Docker安装Nacos2.3 Docker安装xxl-job&#xff08;推荐该方式构建&#xff09;2.4 Docker安装redis2.5 Docker安装mysql 1 前言 上一篇介绍了Docker的基础概念&#xff0c;带你 入门Docker&#xff0c…

菜鸡学习netty源码(四)—— EventLoopGroup

1.概述 我们前面进行过分析,channel为netty网络操作的抽象类,EventLoop负责处理注册到其上的Channel处理的I/O事件;EventLoopGroup是一个EventLoop的分组,它可以获取到一个或者多个的EventLoop对象。 2.类关系图 NioEventLoopGroup的类继承图,蓝色部分为对应的java类,绿…

当管道运算符遇上无限可能:探索数据流的奇妙之旅

文章目录 序言目的进程间通信的理解进程间通信的发展历史管道创建验证管道的大小管道的4种情况管道的5种特征 序言 通过该命令计算了在当前路径下一共有多少个文件夹的任务 进程虽然有独立性,但是进程并不孤僻,他们之间也会相互进行协作共同完成一件事 这个前提是他们之间的信…

Java如何获取当前日期和时间?

Java如何获取当前日期和时间&#xff1f; 本文将为您介绍 Java 中关于日期和时间获取的方法&#xff0c;以及介绍 Java 8 中获取日期和时间的全新API。 1、 System.currentTimeMillis() 获取标准时间可以使用 System.currentTimeMillis() 方法来获取&#xff0c;此方法优势是…

Flutter笔记:Widgets Easier组件库(12)使用消息吐丝(Notify Toasts)

Flutter笔记 Widgets Easier组件库&#xff08;12&#xff09;使用消息吐丝&#xff08;Notify Toasts&#xff09; - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 29114848416…

Linux(openEuler、CentOS8)基于chrony企业内网NTP服务器搭建实验

一、知识点 chrony 是由 守护进程 chronyd 以及 命令行工具 chronyc 组成的 chronyd 在后台静默运行并通过 123 端口与时间服务器定时同步时间&#xff0c;默认的配置文件是 /etc/chrony.conf chronyc 通过 323 端口与 chronyd 交互&#xff0c;可监控 chronyd 的性能并在运…

单例、工厂、策略、装饰器设计模式

1. 单例模式&#xff08;Singleton Pattern&#xff09;&#xff1a; 单例模式是一种常用的设计模式&#xff0c;用于确保一个类只有一个实例&#xff0c;并提供一个全局访问点。这种模式的特点是类自己负责保存其唯一的实例&#xff0c;并控制其实例化过程。单例模式广泛应用…

微服务----nacos配置及简单使用

目录 什么是nacos 项目在nacos上进行注册 注入nacos依赖 配置application.yml文件 nacos写入配置文件 首先&#xff0c;还是需要导入依赖 然后在nacos中编写配置文件 prod是我自定义的一个命名空间&#xff0c;在这里面进行配置文件编写~ 启动类上加上注解 编写Patt…
最新文章