LangChain手册(Python版)27模块:代理执行器

代理执行者采用代理和工具,并使用代理来决定调用哪些工具以及调用的顺序。在文档的这一部分中,我们介绍了代理执行器的其他相关功能如何结合代理和向量存储如何为代理使用

大家好,关于LangChain手册(Python版)27模块:代理执行器很多朋友都还不太明白,今天小编就来为大家分享关于的知识,希望对各位有所帮助!

如何结合代理和向量存储如何对代理使用异步API 如何创建ChatGPT 克隆处理解析错误如何访问中间步骤如何限制最大迭代次数如何对代理使用超时如何向代理和代理添加SharedMemory他们的工具

如何结合代理和向量存储

本笔记本解释了如何组合代理和矢量存储。用例是您已将数据提取到向量存储中并希望以代理方式与其交互。

建议的方法是创建RetrievalQA,然后将其用作整个代理中的工具。下面让我们看看它是如何工作的。您可以使用多个不同的向量数据库来执行此操作,并使用代理作为在它们之间进行路由的方式。有两种不同的方法可以执行此操作—— 您可以让代理使用向量存储作为普通工具,或者您可以设置return_direct=True 以真正将代理用作路由器。

创建Vectorstorefrom langchain.embeddings.openai 导入OpenAIEmbeddings from langchain.vectorstores 导入Chroma from langchain.text_splitter 导入CharacterTextSplitter from langchain.llms 导入OpenAI from langchain.chains import RetrievalQA llm=OpenAI(温度=0) from pathlib import Path related_parts=[] for p in Path(‘.’).absolute().parts: related_parts.append(p) if related_parts[-3:]==[‘langchain’, ‘docs’, ‘modules’]: 中断doc_path=str(Path(* related_parts)/’state_of_the_union.txt’) from langchain.document_loaders import TextLoader loader=TextLoader(doc_path) 文档=loader.load() text_splitter=CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) 文本=text_splitter.split_documents(documents) 嵌入=OpenAIEmbeddings() docsearch=Chroma.from_documents(texts, embeddings, collection_name=’state-of-union’) 使用直接本地API 运行Chroma。使用内存中的DuckDB 作为数据库。数据将是暂时的。 state_of_union=RetrievalQA.from_chain_type(llm=llm, chain_type=’stuff’, retriever=docsearch.as_retriever()) from langchain.document_loaders import WebBaseLoader loader=WebBaseLoader(‘https://beta.ruff.rs/docs/faq/’) docs=loader .load() ruff_texts=text_splitter .split_documents(docs) ruff_db=Chroma.from_documents(ruff_texts, embeddings, collection_name=’ruff’) ruff=RetrievalQA.from_chain_type(llm=llm, chain_type=’stuff’, retriever=ruff_db.as_retriever( )) 使用直接本地API 运行Chroma。使用内存中的DuckDB 作为数据库。数据将是暂时的。

创建Agent # 导入一般需要的东西from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.tools import BaseTool from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper tools=[ Tool( name=’State of Union QA System’, func=state_of_union.run, description=’当您需要回答有关联合地址最新状态的问题时很有用。输入应该是完整的问题。’ ), Tool( name=’Ruff QA System’, func=ruff.run, description=’当您需要回答有关ruff 的问题时很有用(输入应该是完整的问题。’ ), ] # 构建代理。我们将在这里使用默认的代理类型。 # 有关选项的完整列表,请参阅文档。 agent=initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run(‘拜登对ketanji Brown Jackson 说的话是联合地址的状态?’) 输入新的AgentExecutor 链.我需要了解拜登在国情咨文演讲中对科坦吉·布朗·杰克逊的评价。 Action: 国情咨文QA 系统操作Input: 拜登在国情咨文演讲中对Ketanji Brown Jackson 说了些什么? Observation: 拜登表示,杰克逊是美国顶尖的法律专家之一,她将继承布雷耶大法官的卓越遗产。 Thought: 我现在知道了最终答案最终答案: 拜登表示,杰克逊是美国顶尖的法律专家之一,她将继承布雷耶大法官的卓越遗产。链条成品。 “拜登表示,杰克逊是美国顶尖的法律专家之一,她将继承布雷耶大法官的卓越遗产。” agent.run(‘为什么使用ruff 而不是flake8?’) 进入新的AgentExecutor 链.我需要找出使用ruff 相对于flake8 的优点Action: Ruff QA 系统操作Input: 使用ruff 相对于flake8 有哪些优点? Observation: Ruff 在以下情况下可以用作Flake8 的直接替代品:(1) 不带或带少量插件;(2) 与Black 一起使用;(3) 在Python 3 代码上使用。它还原生地重新实现了一些最流行的Flake8 插件和相关代码质量工具,包括isort、yesqa、eradicate 以及pyupgrade 中的大部分规则。 Ruff 还支持自动修复自己的lint 违规行为,而Flake8 则不支持。 Thought: 我现在知道了最终答案最终答案: Ruff 在使用时可以用作Flake8 的直接替代品(1)不带或带少量插件,(2)与Black 一起使用,以及(3)在Python 3 代码上使用。它还原生地重新实现了一些最流行的Flake8 插件和相关代码质量工具,包括isort、yesqa、eradicate 以及pyupgrade 中的大部分规则。 Ruff 还支持自动修复自己的lint 违规行为,而Flake8 则不支持。链条成品。 ‘当使用时,Ruff 可以作为Flake8 的直接替代品来实现(1)不带或带少量插件,(2)与Black 一起使用,以及(3)在Python 3 代码上使用。它还原生重新实现了一些最流行的Flake8 插件和相关代码质量工具,包括isort、yesqa、eradicate 以及pyupgrade 中实现的大部分规则。 Ruff 还支持自动修复自己的lint 违规行为,而Flake8 则不支持。

将 Agent 单独用作路由器

return_direct=True 如果您打算使用代理作为路由器并且只想直接返回RetrievalQAChain 的结果,您也可以设置此项。

请注意,在上面的示例中,代理在查询RetrievalQAChain 后会执行一些额外的工作。您可以避免这种情况并直接返回结果。

tools=[ Tool( name=’State of Union QA System’, func=state_of_union.run, description=’当您需要回答有关最新的工会地址状态的问题时很有用。输入应该是一个完整的问题。 ‘, return_direct=True ), Tool( name=’Ruff QA System’, func=ruff.run, description=’当您需要回答有关ruff (Python linter)的问题时很有用。输入应该是一个完整的问题。 ‘, return_direct=True ),]agent=initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)agent.run(‘拜登在联邦地址中对科坦吉·布朗·杰克逊说了些什么?’) 输入新的AgentExecutor 链.我需要找出拜登在国情咨文中对Ketanji Brown Jackson 的评价。Action: 国情咨文QA SystemAction 输入: 拜登在国情咨文中对Ketanji Brown Jackson 说了些什么?Observation:拜登表示,杰克逊是美国顶尖的法律专家之一,她将继承布雷耶大法官的卓越遗产。完成的链条。拜登表示,杰克逊是美国顶尖的法律专家之一,她将继承布雷耶大法官的卓越遗产。 ‘agent.run(‘Why use ruff over flake8?’) 输入新的AgentExecutor 链.我需要找出使用ruff 相对于flake8Action: Ruff QA SystemAction Input: 使用ruff 相对于flake8 的优点是什么?Observation: Ruff 可以在以下情况下可用作Flake8 的直接替代品:(1) 不带或带少量插件;(2) 与Black 一起使用;(3) 在Python 3 代码上使用。它还原生重新实现了一些最流行的Flake8 插件和相关代码质量工具,包括isort、yesqa、eradicate 以及pyupgrade 中实现的大部分规则。 Ruff 还支持自动修复自己的lint 违规行为,而Flake8 则不支持。完成的链条。在以下情况下,Ruff 可以用作Flake8 的直接替代品:(1) 不带或带少量插件;(2) 与Black 一起使用;(3) 在Python 3 代码上使用。它还原生重新实现了一些最流行的Flake8 插件和相关代码质量工具,包括isort、yesqa、eradicate 以及pyupgrade 中实现的大部分规则。 Ruff 还支持自动修复自己的lint 违规行为,而Flake8 则不支持。

多跳矢量存储推理

因为向量库很容易用作代理中的工具,所以很容易使用现有的代理框架来回答依赖向量库的多跳问题

tools=[ Tool( name=’State of Union QA System’, func=state_of_union.run, description=’当您需要回答有关最新的工会地址状态的问题时很有用。输入应该是一个完整的问题,没有引用之前对话中的任何晦涩的代词。’ ), Tool( name=’Ruff QA System’, func=ruff.run, description=’当你需要回答有关ruff 的问题时很有用(一个python linter)。输入应该是一个完整的问题,不引用之前对话中的任何晦涩的代词。’ ),]# 构造代理。我们将在这里使用默认的代理类型。# 有关选项的完整列表,请参阅文档。agent=initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)agent.run(‘ruff 使用什么工具来运行Jupyter Notebooks?总统在国情咨文中提到过这个工具吗?’)进入新的AgentExecutor 链.我需要找出ruff 使用什么工具来运行Jupyter Notebooks,以及总统是否在国情咨文中提到过它union.Action: Ruff QA SystemAction Input: ruff 使用什么工具在Jupyter Notebooks 上运行?Observation: Ruff 集成到nbQA 中,nbQA 是一个在Jupyter Notebooks 上运行linter 和代码格式化程序的工具。安装ruff 和nbqa 后,您可以在像so: nbqa ruff Untitled.ipynbThought: 这样的笔记本上运行Ruff 我现在需要查明总统是否在国情咨文中提到了这个工具。Action: 国情咨文QA SystemAction Input: 总统是否提到过nbQA 在国情咨文中?观察: 不,总统在国情咨文中没有提到nbQA。Thought: 我现在知道最终答案。最终答案: 不,总统在国情咨文中没有提到nbQA。连锁完成。“不,总统在国情咨文中没有提到nbQA。”

如何为代理使用异步 API

LangChain利用asyncio库为代理提供异步支持。

目前支持以下异步方法工具:GoogleSerperAPIWrapper 和SerpAPIWrapper。 LLMMathChain 对其他代理工具的异步支持已在路线图上。

对于具有协程实现的Tool(上面提到的三个),AgentExecutor 将等待直接执行它们。否则,AgentExecutor会调用Tool的funcviaasyncio.get

_event_loop().run_in_executor以避免阻塞主运行循环。

您可以使用异步arun调用AgentExecutor。

串行与并发执行

在此示例中,我们启动代理以串行或同时回答一些问题。您可以看到并发执行显着加快了速度。

import asyncioimport timefrom langchain.agents import initialize_agent, load_toolsfrom langchain.agents import AgentTypefrom langchain.llms import OpenAIfrom langchain.callbacks.stdout import StdOutCallbackHandlerfrom langchain.callbacks.tracers import LangChainTracerfrom aiohttp import ClientSessionquestions = [ “Who won the US Open men’s final in 2019? What is his age raised to the 0.334 power?”, “Who is Olivia Wilde’s boyfriend? What is his current age raised to the 0.23 power?”, “Who won the most recent formula 1 grand prix? What is their age raised to the 0.23 power?”, “Who won the US Open women’s final in 2019? What is her age raised to the 0.34 power?”, “Who is Beyonce’s husband? What is his age raised to the 0.19 power?”]llm = OpenAI(temperature=0)tools = load_tools([“google-serper”, “llm-math”], llm=llm)agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)s = time.perf_counter()for q in questions: agent.run(q)elapsed = time.perf_counter() – sprint(f”Serial executed in {elapsed:0.2f} seconds.”)> Entering new AgentExecutor chain… I need to find out who won the US Open men’s final in 2019 and then calculate his age raised to the 0.334 power.Action: Google SerperAction Input: “Who won the US Open men’s final in 2019?”Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men’s singles tennis title at the 2019 US Open. It was his fourth US … Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 7–5, 6–3, 5–7, 4–6, 6–4. Bianca Andreescu won the women’s singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles … Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil … Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian … Rafael Nadal defeated Daniil Medvedev in the men’s singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday … NEW YORK — Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men’s singles title at the … Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the … Watch the full match between Daniil Medvedev and Rafael … Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open …Thought: I now know that Rafael Nadal won the US Open men’s final in 2019 and he is 33 years old.Action: CalculatorAction Input: 33^0.334Observation: Answer: 3.215019829667466Thought: I now know the final answer.Final Answer: Rafael Nadal won the US Open men’s final in 2019 and his age raised to the 0.334 power is 3.215019829667466.> Finished chain.> Entering new AgentExecutor chain… I need to find out who Olivia Wilde’s boyfriend is and then calculate his age raised to the 0.23 power.Action: Google SerperAction Input: “Olivia Wilde boyfriend”Observation: Sudeikis and Wilde’s relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don’t Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don’t Worry Darling.Thought: I need to find out Harry Styles’ age.Action: Google SerperAction Input: “Harry Styles age”Observation: 29 yearsThought: I need to calculate 29 raised to the 0.23 power.Action: CalculatorAction Input: 29^0.23Observation: Answer: 2.169459462491557Thought: I now know the final answer.Final Answer: Harry Styles is Olivia Wilde’s boyfriend and his current age raised to the 0.23 power is 2.169459462491557.> Finished chain.> Entering new AgentExecutor chain… I need to find out who won the most recent grand prix and then calculate their age raised to the 0.23 power.Action: Google SerperAction Input: “who won the most recent formula 1 grand prix”Observation: Max Verstappen won his first Formula 1 world title on Sunday after the championship was decided by a last-lap overtake of his rival Lewis Hamilton in the Abu Dhabi Grand Prix. Dec 12, 2021Thought: I need to find out Max Verstappen’s ageAction: Google SerperAction Input: “Max Verstappen age”Observation: 25 yearsThought: I need to calculate 25 raised to the 0.23 powerAction: CalculatorAction Input: 25^0.23Observation: Answer: 2.096651272316035Thought: I now know the final answerFinal Answer: Max Verstappen, aged 25, won the most recent Formula 1 grand prix and his age raised to the 0.23 power is 2.096651272316035.> Finished chain.> Entering new AgentExecutor chain… I need to find out who won the US Open women’s final in 2019 and then calculate her age raised to the 0.34 power.Action: Google SerperAction Input: “US Open women’s final 2019 winner”Observation: WHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women’s singles final, 6-3, 7-5. Sep 7, 2019Thought: I now need to calculate her age raised to the 0.34 power.Action: CalculatorAction Input: 19^0.34Observation: Answer: 2.7212987634680084Thought: I now know the final answer.Final Answer: Nineteen-year-old Canadian Bianca Andreescu won the US Open women’s final in 2019 and her age raised to the 0.34 power is 2.7212987634680084.> Finished chain.> Entering new AgentExecutor chain… I need to find out who Beyonce’s husband is and then calculate his age raised to the 0.19 power.Action: Google SerperAction Input: “Who is Beyonce’s husband?”Observation: Jay-ZThought: I need to find out Jay-Z’s ageAction: Google SerperAction Input: “How old is Jay-Z?”Observation: 53 yearsThought: I need to calculate 53 raised to the 0.19 powerAction: CalculatorAction Input: 53^0.19Observation: Answer: 2.12624064206896Thought: I now know the final answerFinal Answer: Jay-Z is Beyonce’s husband and his age raised to the 0.19 power is 2.12624064206896.> Finished chain.Serial executed in 89.97 seconds.llm = OpenAI(temperature=0)tools = load_tools([“google-serper”,”llm-math”], llm=llm)agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)s = time.perf_counter()# If running this outside of Jupyter, use asyncio.run or loop.run_until_completetasks = [agent.arun(q) for q in questions]await asyncio.gather(*tasks)elapsed = time.perf_counter() – sprint(f”Concurrent executed in {elapsed:0.2f} seconds.”)> Entering new AgentExecutor chain…> Entering new AgentExecutor chain…> Entering new AgentExecutor chain…> Entering new AgentExecutor chain…> Entering new AgentExecutor chain… I need to find out who Olivia Wilde’s boyfriend is and then calculate his age raised to the 0.23 power.Action: Google SerperAction Input: “Olivia Wilde boyfriend” I need to find out who Beyonce’s husband is and then calculate his age raised to the 0.19 power.Action: Google SerperAction Input: “Who is Beyonce’s husband?” I need to find out who won the most recent formula 1 grand prix and then calculate their age raised to the 0.23 power.Action: Google SerperAction Input: “most recent formula 1 grand prix winner” I need to find out who won the US Open men’s final in 2019 and then calculate his age raised to the 0.334 power.Action: Google SerperAction Input: “Who won the US Open men’s final in 2019?” I need to find out who won the US Open women’s final in 2019 and then calculate her age raised to the 0.34 power.Action: Google SerperAction Input: “US Open women’s final 2019 winner”Observation: Sudeikis and Wilde’s relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don’t Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don’t Worry Darling.Thought:Observation: Jay-ZThought:Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men’s singles tennis title at the 2019 US Open. It was his fourth US … Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 7–5, 6–3, 5–7, 4–6, 6–4. Bianca Andreescu won the women’s singles title, defeating Serena Williams in straight sets in the final, becoming the first Canadian to win a Grand Slam singles … Rafael Nadal won his 19th career Grand Slam title, and his fourth US Open crown, by surviving an all-time comback effort from Daniil … Rafael Nadal beats Daniil Medvedev in US Open final to claim 19th major title. World No2 claims 7-5, 6-3, 5-7, 4-6, 6-4 victory over Russian … Rafael Nadal defeated Daniil Medvedev in the men’s singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday … NEW YORK — Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to win the men’s singles title at the … Nadal previously won the U.S. Open three times, most recently in 2017. Ahead of the match, Nadal said he was “super happy to be back in the … Watch the full match between Daniil Medvedev and Rafael … Duration: 4:47:32. Posted: Mar 20, 2020. US Open 2019: Rafael Nadal beats Daniil Medvedev · Updated: Sep. 08, 2019, 11:11 p.m. |; Published: Sep · Published: Sep. 08, 2019, 10:06 p.m.. 26. US Open …Thought:Observation: WHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women’s singles final, 6-3, 7-5. Sep 7, 2019Thought:Observation: Lewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, … Michael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Sebastian Vettel ( … Grand Prix, Date, Winner, Car, Laps, Time. Bahrain, 05 Mar 2023, Max Verstappen VER, Red Bull Racing Honda RBPT, 57, 1:33:56.736. Saudi Arabia, 19 Mar 2023 … The Red Bull driver Max Verstappen of the Netherlands celebrated winning his first Formula 1 world title at the Abu Dhabi Grand Prix. Perez wins sprint as Verstappen, Russell clash. Red Bull’s Sergio Perez won the first sprint of the 2023 Formula One season after catching and passing Charles … The most successful driver in the history of F1 is Lewis Hamilton. The man from Stevenage has won 103 Grands Prix throughout his illustrious career and is still … Lewis Hamilton: 103. Max Verstappen: 37. Michael Schumacher: 91. Fernando Alonso: 32. Max Verstappen and Sergio Perez will race in a very different-looking Red Bull this weekend after the team unveiled a striking special livery for the Miami GP. Lewis Hamilton holds the record of most victories with 103, ahead of Michael Schumacher (91) and Sebastian Vettel (53). Schumacher also holds the record for the … Lewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, is second …Thought: I need to find out Harry Styles’ age.Action: Google SerperAction Input: “Harry Styles age” I need to find out Jay-Z’s ageAction: Google SerperAction Input: “How old is Jay-Z?” I now know that Rafael Nadal won the US Open men’s final in 2019 and he is 33 years old.Action: CalculatorAction Input: 33^0.334 I now need to calculate her age raised to the 0.34 power.Action: CalculatorAction Input: 19^0.34Observation: 29 yearsThought:Observation: 53 yearsThought: Max Verstappen won the most recent Formula 1 grand prix.Action: CalculatorAction Input: Max Verstappen’s age (23) raised to the 0.23 powerObservation: Answer: 2.7212987634680084Thought:Observation: Answer: 3.215019829667466Thought: I need to calculate 29 raised to the 0.23 power.Action: CalculatorAction Input: 29^0.23 I need to calculate 53 raised to the 0.19 powerAction: CalculatorAction Input: 53^0.19Observation: Answer: 2.0568252837687546Thought:Observation: Answer: 2.169459462491557Thought:> Finished chain.> Finished chain.Observation: Answer: 2.12624064206896Thought:> Finished chain.> Finished chain.> Finished chain.Concurrent executed in 17.52 seconds.

如何创建 ChatGPT 克隆

展示 https://www.engraved.blog/building-a-virtual-machine-inside/ 中的示例

from langchain import OpenAI, ConversationChain, LLMChain, PromptTemplatefrom langchain.memory import ConversationBufferWindowMemorytemplate = “””Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.{history}Human: {human_input}Assistant:”””prompt = PromptTemplate( input_variables=[“history”, “human_input”], template=template)chatgpt_chain = LLMChain( llm=OpenAI(temperature=0), prompt=prompt, verbose=True, memory=ConversationBufferWindowMemory(k=2),)output = chatgpt_chain.predict(human_input=”I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.Assistant:> Finished chain.“`/home/user“`output = chatgpt_chain.predict(human_input=”ls ~”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.AI: “`$ pwd/“`Human: ls ~Assistant:> Finished LLMChain chain.“`$ ls ~Desktop Documents Downloads Music Pictures Public Templates Videos“`output = chatgpt_chain.predict(human_input=”cd ~”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.AI: “`$ pwd/“`Human: ls ~AI: “`$ ls ~Desktop Documents Downloads Music Pictures Public Templates Videos“`Human: cd ~Assistant:> Finished LLMChain chain. “`$ cd ~$ pwd/home/user“`output = chatgpt_chain.predict(human_input=”{Please make a file jokes.txt inside and put some jokes inside}”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: ls ~AI: “`$ ls ~Desktop Documents Downloads Music Pictures Public Templates Videos“`Human: cd ~AI: “`$ cd ~$ pwd/home/user“`Human: {Please make a file jokes.txt inside and put some jokes inside}Assistant:> Finished LLMChain chain.“`$ touch jokes.txt$ echo “Why did the chicken cross the road? To get to the other side!” >> jokes.txt$ echo “What did the fish say when it hit the wall? Dam!” >> jokes.txt$ echo “Why did the scarecrow win the Nobel Prize? Because he was outstanding in his field!” >> jokes.txt“`output = chatgpt_chain.predict(human_input=”””echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py && python3 run.py”””)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: cd ~AI: “`$ cd ~$ pwd/home/user“`Human: {Please make a file jokes.txt inside and put some jokes inside}AI: “`$ touch jokes.txt$ echo “Why did the chicken cross the road? To get to the other side!” >> jokes.txt$ echo “What did the fish say when it hit the wall? Dam!” >> jokes.txt$ echo “Why did the scarecrow win the Nobel Prize? Because he was outstanding in his field!” >> jokes.txt“`Human: echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py && python3 run.pyAssistant:> Finished LLMChain chain.“`$ echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py$ python3 run.pyResult: 33“`output = chatgpt_chain.predict(human_input=”””echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py && python3 run.py”””)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: {Please make a file jokes.txt inside and put some jokes inside}AI: “`$ touch jokes.txt$ echo “Why did the chicken cross the road? To get to the other side!” >> jokes.txt$ echo “What did the fish say when it hit the wall? Dam!” >> jokes.txt$ echo “Why did the scarecrow win the Nobel Prize? Because he was outstanding in his field!” >> jokes.txt“`Human: echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py && python3 run.pyAI: “`$ echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py$ python3 run.pyResult: 33“`Human: echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py && python3 run.pyAssistant:> Finished LLMChain chain.“`$ echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py$ python3 run.py[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]“`docker_input = “””echo -e “echo ‘Hello from Docker” > entrypoint.sh && echo -e “FROM ubuntu:20.04\nCOPY entrypoint.sh entrypoint.sh\nENTRYPOINT [\”/bin/sh\”,\”entrypoint.sh\”]”>Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_image”””output = chatgpt_chain.predict(human_input=docker_input)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py && python3 run.pyAI: “`$ echo -e “x=lambda y:y*5+3;print(‘Result:’ + str(x(6)))” > run.py$ python3 run.pyResult: 33“`Human: echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py && python3 run.pyAI: “`$ echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py$ python3 run.py[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]“`Human: echo -e “echo ‘Hello from Docker” > entrypoint.sh && echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_imageAssistant:> Finished LLMChain chain.“`$ echo -e “echo ‘Hello from Docker” > entrypoint.sh$ echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile$ docker build . -t my_docker_image$ docker run -t my_docker_imageHello from Docker“`output = chatgpt_chain.predict(human_input=”nvidia-smi”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py && python3 run.pyAI: “`$ echo -e “print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])” > run.py$ python3 run.py[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]“`Human: echo -e “echo ‘Hello from Docker” > entrypoint.sh && echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_imageAI: “`$ echo -e “echo ‘Hello from Docker” > entrypoint.sh$ echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile$ docker build . -t my_docker_image$ docker run -t my_docker_imageHello from Docker“`Human: nvidia-smiAssistant:> Finished LLMChain chain.“`$ nvidia-smiSat May 15 21:45:02 2021 +—————————————————————————–+| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 ||——————————-+———————-+———————-+| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 GeForce GTX 108… Off | 00000000:01:00.0 Off | N/A || N/A 45C P0 N/A / N/A | 511MiB / 10206MiB | 0% Default |+——————————-+———————-+———————-+ +—————————————————————————–+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|output = chatgpt_chain.predict(human_input=”ping bbc.com”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: echo -e “echo ‘Hello from Docker” > entrypoint.sh && echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_imageAI: “`$ echo -e “echo ‘Hello from Docker” > entrypoint.sh$ echo -e “FROM ubuntu:20.04COPY entrypoint.sh entrypoint.shENTRYPOINT [“/bin/sh”,”entrypoint.sh”]”>Dockerfile$ docker build . -t my_docker_image$ docker run -t my_docker_imageHello from Docker“`Human: nvidia-smiAI: “`$ nvidia-smiSat May 15 21:45:02 2021 +—————————————————————————–+| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 ||——————————-+———————-+———————-+| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 GeForce GTX 108… Off | 00000000:01:00.0 Off | N/A || N/A 45C P0 N/A / N/A | 511MiB / 10206MiB | 0% Default |+——————————-+———————-+———————-+ +—————————————————————————–+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|Human: ping bbc.comAssistant:> Finished LLMChain chain.“`$ ping bbc.comPING bbc.com (151.101.65.81): 56 data bytes64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=2 ttl=53 time=14.945 ms— bbc.com ping statistics —3 packets transmitted, 3 packets received, 0.0% packet lossround-trip min/avg/max/stddev = 14.945/14.945/14.945/0.000 ms“`output = chatgpt_chain.predict(human_input=”””curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g'”””)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: nvidia-smiAI: “`$ nvidia-smiSat May 15 21:45:02 2021 +—————————————————————————–+| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 ||——————————-+———————-+———————-+| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 GeForce GTX 108… Off | 00000000:01:00.0 Off | N/A || N/A 45C P0 N/A / N/A | 511MiB / 10206MiB | 0% Default |+——————————-+———————-+———————-+ +—————————————————————————–+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|Human: ping bbc.comAI: “`$ ping bbc.comPING bbc.com (151.101.65.81): 56 data bytes64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=2 ttl=53 time=14.945 ms— bbc.com ping statistics —3 packets transmitted, 3 packets received, 0.0% packet lossround-trip min/avg/max/stddev = 14.945/14.945/14.945/0.000 ms“`Human: curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’Assistant:> Finished LLMChain chain.“`$ curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’1.8.1“`output = chatgpt_chain.predict(human_input=”lynx https://www.deepmind.com/careers”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: ping bbc.comAI: “`$ ping bbc.comPING bbc.com (151.101.65.81): 56 data bytes64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms64 bytes from 151.101.65.81: icmp_seq=2 ttl=53 time=14.945 ms— bbc.com ping statistics —3 packets transmitted, 3 packets received, 0.0% packet lossround-trip min/avg/max/stddev = 14.945/14.945/14.945/0.000 ms“`Human: curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’AI: “`$ curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’1.8.1“`Human: lynx https://www.deepmind.com/careersAssistant:> Finished LLMChain chain.“`$ lynx https://www.deepmind.com/careersDeepMind CareersWelcome to DeepMind Careers. We are a world-leading artificial intelligence research and development company, and we are looking for talented people to join our team.We offer a range of exciting opportunities in research, engineering, product, and operations. Our mission is to solve intelligence and make it useful, and we are looking for people who share our passion for pushing the boundaries of AI.Explore our current openings and apply today. We look forward to hearing from you.“`output = chatgpt_chain.predict(human_input=”curl https://chat.openai.com/chat”)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’AI: “`$ curl -fsSL “https://api.github.com/repos/pytorch/pytorch/releases/latest” | jq -r ‘.tag_name’ | sed ‘s/[^0-9\.\-]*//g’1.8.1“`Human: lynx https://www.deepmind.com/careersAI: “`$ lynx https://www.deepmind.com/careersDeepMind CareersWelcome to DeepMind Careers. We are a world-leading artificial intelligence research and development company, and we are looking for talented people to join our team.We offer a range of exciting opportunities in research, engineering, product, and operations. Our mission is to solve intelligence and make it useful, and we are looking for people who share our passion for pushing the boundaries of AI.Explore our current openings and apply today. We look forward to hearing from you.“`Human: curl https://chat.openai.com/chatAssistant:> Finished LLMChain chain. “`$ curl https://chat.openai.com/chat<html> <head> <title>OpenAI Chat</title> </head> <body> <h1>Welcome to OpenAI Chat!</h1> <p> OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI’s AI models in a conversational way. </p> <p> To get started, type a message in the box below and press enter. </p> </body></html>“`output = chatgpt_chain.predict(human_input=”””curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “What is artificial intelligence?”}’ https://chat.openai.com/chat”””)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: lynx https://www.deepmind.com/careersAI: “`$ lynx https://www.deepmind.com/careersDeepMind CareersWelcome to DeepMind Careers. We are a world-leading artificial intelligence research and development company, and we are looking for talented people to join our team.We offer a range of exciting opportunities in research, engineering, product, and operations. Our mission is to solve intelligence and make it useful, and we are looking for people who share our passion for pushing the boundaries of AI.Explore our current openings and apply today. We look forward to hearing from you.“`Human: curl https://chat.openai.com/chatAI: “`$ curl https://chat.openai.com/chat<html> <head> <title>OpenAI Chat</title> </head> <body> <h1>Welcome to OpenAI Chat!</h1> <p> OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI’s AI models in a conversational way. </p> <p> To get started, type a message in the box below and press enter. </p> </body></html>“`Human: curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “What is artificial intelligence?”}’ https://chat.openai.com/chatAssistant:> Finished LLMChain chain.“`$ curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “What is artificial intelligence?”}’ https://chat.openai.com/chat{ “response”: “Artificial intelligence (AI) is the simulation of human intelligence processes by machines, especially computer systems. These processes include learning (the acquisition of information and rules for using the information), reasoning (using the rules to reach approximate or definite conclusions) and self-correction. AI is used to develop computer systems that can think and act like humans.”}“`output = chatgpt_chain.predict(human_input=”””curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.”}’ https://chat.openai.com/chat”””)print(output)> Entering new LLMChain chain…Prompt after formatting:Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.Human: curl https://chat.openai.com/chatAI: “`$ curl https://chat.openai.com/chat<html> <head> <title>OpenAI Chat</title> </head> <body> <h1>Welcome to OpenAI Chat!</h1> <p> OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI’s AI models in a conversational way. </p> <p> To get started, type a message in the box below and press enter. </p> </body></html>“`Human: curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “What is artificial intelligence?”}’ https://chat.openai.com/chatAI: “`$ curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “What is artificial intelligence?”}’ https://chat.openai.com/chat{ “response”: “Artificial intelligence (AI) is the simulation of human intelligence processes by machines, especially computer systems. These processes include learning (the acquisition of information and rules for using the information), reasoning (using the rules to reach approximate or definite conclusions) and self-correction. AI is used to develop computer systems that can think and act like humans.”}“`Human: curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.”}’ https://chat.openai.com/chatAssistant:> Finished LLMChain chain. “`$ curl –header “Content-Type:application/json” –request POST –data ‘{“message”: “I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.”}’ https://chat.openai.com/chat{ “response”: ““`\n/current/working/directory\n“`”}“`

处理解析错误

有时 LLM 无法确定要采取的步骤,因为它以不正确的形式输出格式以供输出解析器处理。在这种情况下,默认情况下代理会出错。但是您可以使用handle_parsing_errors!轻松控制此功能。让我们探讨如何。

设置from langchain import OpenAI, LLMMathChain, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.chat_models import ChatOpenAI from langchain.agents.types import AGENT_TO_CLASS search = SerpAPIWrapper() tools = [ Tool( name = “Search”, func=search.run, description=”useful for when you need to answer questions about current events. You should ask targeted questions” ), ]

错误

在这种情况下,代理会出错(因为它无法输出 Action 字符串)

mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True,)mrkl.run(“Who is Leo DiCaprio’s girlfriend? No need to add Action”)> Entering new AgentExecutor chain…—————————————————————————IndexError Traceback (most recent call last)File ~/workplace/langchain/langchain/agents/chat/output_parser.py:21, in ChatOutputParser.parse(self, text) 20 try:—> 21 action = text.split(““`”)[1] 22 response = json.loads(action.strip())IndexError: list index out of rangeDuring handling of the above exception, another exception occurred:OutputParserException Traceback (most recent call last)Cell In[4], line 1—-> 1 mrkl.run(“Who is Leo DiCaprio’s girlfriend? No need to add Action”)File ~/workplace/langchain/langchain/chains/base.py:236, in Chain.run(self, callbacks, *args, **kwargs) 234 if len(args) != 1: 235 raise ValueError(“`run` supports only one positional argument.”)–> 236 return self(args[0], callbacks=callbacks)[self.output_keys[0]] 238 if kwargs and not args: 239 return self(kwargs, callbacks=callbacks)[self.output_keys[0]]File ~/workplace/langchain/langchain/chains/base.py:140, in Chain.__call__(self, inputs, return_only_outputs, callbacks) 138 except (KeyboardInterrupt, Exception) as e: 139 run_manager.on_chain_error(e)–> 140 raise e 141 run_manager.on_chain_end(outputs) 142 return self.prep_outputs(inputs, outputs, return_only_outputs)File ~/workplace/langchain/langchain/chains/base.py:134, in Chain.__call__(self, inputs, return_only_outputs, callbacks) 128 run_manager = callback_manager.on_chain_start( 129 {“name”: self.__class__.__name__}, 130 inputs, 131 ) 132 try: 133 outputs = (–> 134 self._call(inputs, run_manager=run_manager) 135 if new_arg_supported 136 else self._call(inputs) 137 ) 138 except (KeyboardInterrupt, Exception) as e: 139 run_manager.on_chain_error(e)File ~/workplace/langchain/langchain/agents/agent.py:947, in AgentExecutor._call(self, inputs, run_manager) 945 # We now enter the agent loop (until it returns something). 946 while self._should_continue(iterations, time_elapsed):–> 947 next_step_output = self._take_next_step( 948 name_to_tool_map, 949 color_mapping, 950 inputs, 951 intermediate_steps, 952 run_manager=run_manager, 953 ) 954 if isinstance(next_step_output, AgentFinish): 955 return self._return( 956 next_step_output, intermediate_steps, run_manager=run_manager 957 )File ~/workplace/langchain/langchain/agents/agent.py:773, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager) 771 raise_error = False 772 if raise_error:–> 773 raise e 774 text = str(e) 775 if isinstance(self.handle_parsing_errors, bool):File ~/workplace/langchain/langchain/agents/agent.py:762, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager) 756 “””Take a single step in the thought-action-observation loop. 757 758 Override this to take control of how the agent makes and acts on choices. 759 “”” 760 try: 761 # Call the LLM to see what to do.–> 762 output = self.agent.plan( 763 intermediate_steps, 764 callbacks=run_manager.get_child() if run_manager else None, 765 **inputs, 766 ) 767 except OutputParserException as e: 768 if isinstance(self.handle_parsing_errors, bool):File ~/workplace/langchain/langchain/agents/agent.py:444, in Agent.plan(self, intermediate_steps, callbacks, **kwargs) 442 full_inputs = self.get_full_inputs(intermediate_steps, **kwargs) 443 full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs)–> 444 return self.output_parser.parse(full_output)File ~/workplace/langchain/langchain/agents/chat/output_parser.py:26, in ChatOutputParser.parse(self, text) 23 return AgentAction(response[“action”], response[“action_input”], text) 25 except Exception:—> 26 raise OutputParserException(f”Could not parse LLM output: {text}”)OutputParserException: Could not parse LLM output: I’m sorry, but I cannot provide an answer without an Action. Please provide a valid Action in the format specified above.

默认错误处理

处理错误Invalid or incomplete response

mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=True)mrkl.run(“Who is Leo DiCaprio’s girlfriend? No need to add Action”)> Entering new AgentExecutor chain…Observation: Invalid or incomplete responseThought:Observation: Invalid or incomplete responseThought:Search for Leo DiCaprio’s current girlfriendAction:“`{ “action”: “Search”, “action_input”: “Leo DiCaprio current girlfriend”}“`Observation: Just Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date!Thought:Camila Morrone is currently Leo DiCaprio’s girlfriendFinal Answer: Camila Morrone> Finished chain.’Camila Morrone’

自定义错误消息

您可以轻松自定义在出现解析错误时要使用的消息

mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=”Check your output and make sure it conforms!”)mrkl.run(“Who is Leo DiCaprio’s girlfriend? No need to add Action”)> Entering new AgentExecutor chain…Observation: Could not parse LLM output: I’m sorry, but I cannoThought:I need to use the Search tool to find the answer to the question.Action:“`{ “action”: “Search”, “action_input”: “Who is Leo DiCaprio’s girlfriend?”}“`Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He’s since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week.Thought:The answer to the question is that Leo DiCaprio’s current girlfriend is Gigi Hadid. Final Answer: Gigi Hadid.> Finished chain.’Gigi Hadid.’

自定义错误函数

您还可以将错误自定义为接收错误并输出字符串的函数。

def _handle_error(error) -> str: return str(error)[:50]mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=_handle_error)mrkl.run(“Who is Leo DiCaprio’s girlfriend? No need to add Action”)> Entering new AgentExecutor chain…Observation: Could not parse LLM output: I’m sorry, but I cannoThought:I need to use the Search tool to find the answer to the question.Action:“`{ “action”: “Search”, “action_input”: “Who is Leo DiCaprio’s girlfriend?”}“`Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He’s since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week.Thought:The current girlfriend of Leonardo DiCaprio is Gigi Hadid. Final Answer: Gigi Hadid.> Finished chain.’Gigi Hadid.’

如何访问中间步骤

为了更清楚地了解代理正在做什么,我们还可以返回中间步骤。这以返回值中的额外键的形式出现,返回值是(动作,观察)元组的列表。

from langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.llms import OpenAI初始化代理所需的组件。

llm = OpenAI(temperature=0, model_name=’text-davinci-002′)tools = load_tools([“serpapi”, “llm-math”], llm=llm)初始化代理return_intermediate_steps=True

agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, return_intermediate_steps=True)response = agent({“input”:”Who is Leo DiCaprio’s girlfriend? What is her current age raised to the 0.43 power?”})> Entering new AgentExecutor chain… I should look up who Leo DiCaprio is datingAction: SearchAction Input: “Leo DiCaprio girlfriend”Observation: Camila MorroneThought: I should look up how old Camila Morrone isAction: SearchAction Input: “Camila Morrone age”Observation: 25 yearsThought: I should calculate what 25 years raised to the 0.43 power isAction: CalculatorAction Input: 25^0.43Observation: Answer: 3.991298452658078Thought: I now know the final answerFinal Answer: Camila Morrone is Leo DiCaprio’s girlfriend and she is 3.991298452658078 years old.> Finished chain.# The actual return type is a NamedTuple for the agent action, and then an observationprint(response[“intermediate_steps”])[(AgentAction(tool=’Search’, tool_input=’Leo DiCaprio girlfriend’, log=’ I should look up who Leo DiCaprio is dating\nAction: Search\nAction Input: “Leo DiCaprio girlfriend”‘), ‘Camila Morrone’), (AgentAction(tool=’Search’, tool_input=’Camila Morrone age’, log=’ I should look up how old Camila Morrone is\nAction: Search\nAction Input: “Camila Morrone age”‘), ’25 years’), (AgentAction(tool=’Calculator’, tool_input=’25^0.43′, log=’ I should calculate what 25 years raised to the 0.43 power is\nAction: Calculator\nAction Input: 25^0.43′), ‘Answer: 3.991298452658078\n’)]import jsonprint(json.dumps(response[“intermediate_steps”], indent=2))[ [ [ “Search”, “Leo DiCaprio girlfriend”, ” I should look up who Leo DiCaprio is dating\nAction: Search\nAction Input: \”Leo DiCaprio girlfriend\”” ], “Camila Morrone” ], [ [ “Search”, “Camila Morrone age”, ” I should look up how old Camila Morrone is\nAction: Search\nAction Input: \”Camila Morrone age\”” ], “25 years” ], [ [ “Calculator”, “25^0.43″, ” I should calculate what 25 years raised to the 0.43 power is\nAction: Calculator\nAction Input: 25^0.43″ ], “Answer: 3.991298452658078\n” ]]

如何将 SharedMemory 添加到代理及其工具

本笔记本介绍了如何为代理及其工具添加内存。在阅读本笔记本之前,请浏览以下笔记本,因为这将建立在它们之上:

向 LLM 链添加内存定制代理我们将创建一个自定义代理。代理可以访问对话记忆、搜索工具和摘要工具。并且,摘要工具还需要访问对话内存。

from langchain.agents import ZeroShotAgent, Tool, AgentExecutorfrom langchain.memory import ConversationBufferMemory, ReadOnlySharedMemoryfrom langchain import OpenAI, LLMChain, PromptTemplatefrom langchain.utilities import GoogleSearchAPIWrappertemplate = “””This is a conversation between a human and a bot:{chat_history}Write a summary of the conversation for {input}:”””prompt = PromptTemplate( input_variables=[“input”, “chat_history”], template=template)memory = ConversationBufferMemory(memory_key=”chat_history”)readonlymemory = ReadOnlySharedMemory(memory=memory)summry_chain = LLMChain( llm=OpenAI(), prompt=prompt, verbose=True, memory=readonlymemory, # use the read-only memory to prevent the tool from modifying the memory)search = GoogleSearchAPIWrapper()tools = [ Tool( name = “Search”, func=search.run, description=”useful for when you need to answer questions about current events” ), Tool( name = “Summary”, func=summry_chain.run, description=”useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary.” )]prefix = “””Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:”””suffix = “””Begin!”{chat_history}Question: {input}{agent_scratchpad}”””prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=[“input”, “chat_history”, “agent_scratchpad”])我们现在可以使用 Memory 对象构造 LLMChain,然后创建代理。

LangChain手册(Python版)27模块:代理执行器

llm_chain = LLMChain(llm=OpenAI(temperature=0), 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)agent_chain.run(input=”What is ChatGPT?”)> Entering new AgentExecutor chain…Thought: I should research ChatGPT to answer this question.Action: SearchAction Input: “ChatGPT”Observation: Nov 30, 2022 … We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer … ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large … ChatGPT. We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer … Feb 2, 2023 … ChatGPT, the popular chatbot from OpenAI, is estimated to have reached 100 million monthly active users in January, just two months after … 2 days ago … ChatGPT recently launched a new version of its own plagiarism detection tool, with hopes that it will squelch some of the criticism around how … An API for accessing new AI models developed by OpenAI. Feb 19, 2023 … ChatGPT is an AI chatbot system that OpenAI released in November to show off and test what a very large, powerful AI system can accomplish. You … ChatGPT is fine-tuned from GPT-3.5, a language model trained to produce text. ChatGPT was optimized for dialogue by using Reinforcement Learning with Human … 3 days ago … Visual ChatGPT connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting. Dec 1, 2022 … ChatGPT is a natural language processing tool driven by AI technology that allows you to have human-like conversations and much more with a …Thought: I now know the final answer.Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.> Finished chain.”ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.”为了测试此代理的记忆力,我们可以提出一个后续问题,该问题依赖于先前交流中的信息才能正确回答。

agent_chain.run(input=”Who developed it?”)> Entering new AgentExecutor chain…Thought: I need to find out who developed ChatGPTAction: SearchAction Input: Who developed ChatGPTObservation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large … Feb 15, 2023 … Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. The organization is headquartered in San … Feb 8, 2023 … ChatGPT is an AI chatbot developed by San Francisco-based startup OpenAI. OpenAI was co-founded in 2015 by Elon Musk and Sam Altman and is … Dec 7, 2022 … ChatGPT is an AI chatbot designed and developed by OpenAI. The bot works by generating text responses based on human-user input, like questions … Jan 12, 2023 … In 2019, Microsoft invested $1 billion in OpenAI, the tiny San Francisco company that designed ChatGPT. And in the years since, it has quietly … Jan 25, 2023 … The inside story of ChatGPT: How OpenAI founder Sam Altman built the world’s hottest technology with billions from Microsoft. Dec 3, 2022 … ChatGPT went viral on social media for its ability to do anything from code to write essays. · The company that created the AI chatbot has a … Jan 17, 2023 … While many Americans were nursing hangovers on New Year’s Day, 22-year-old Edward Tian was working feverishly on a new app to combat misuse … ChatGPT is a language model created by OpenAI, an artificial intelligence research laboratory consisting of a team of researchers and engineers focused on … 1 day ago … Everyone is talking about ChatGPT, developed by OpenAI. This is such a great tool that has helped to make AI more accessible to a wider …Thought: I now know the final answerFinal Answer: ChatGPT was developed by OpenAI.> Finished chain.’ChatGPT was developed by OpenAI.’agent_chain.run(input=”Thanks. Summarize the conversation, for my daughter 5 years old.”)> Entering new AgentExecutor chain…Thought: I need to simplify the conversation for a 5 year old.Action: SummaryAction Input: My daughter 5 years old> Entering new LLMChain chain…Prompt after formatting:This is a conversation between a human and a bot:Human: What is ChatGPT?AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.Human: Who developed it?AI: ChatGPT was developed by OpenAI.Write a summary of the conversation for My daughter 5 years old:> Finished chain.Observation: The conversation was about ChatGPT, an artificial intelligence chatbot. It was created by OpenAI and can send and receive images while chatting.Thought: I now know the final answer.Final Answer: ChatGPT is an artificial intelligence chatbot created by OpenAI that can send and receive images while chatting.> Finished chain.’ChatGPT is an artificial intelligence chatbot created by OpenAI that can send and receive images while chatting.’确认内存已正确更新。

print(agent_chain.memory.buffer)Human: What is ChatGPT?AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.Human: Who developed it?AI: ChatGPT was developed by OpenAI.Human: Thanks. Summarize the conversation, for my daughter 5 years old.AI: ChatGPT is an artificial intelligence chatbot created by OpenAI that can send and receive images while chatting.为了进行比较,下面是一个不好的例子,它为代理和工具使用相同的内存。

## This is a bad practice for using the memory.## Use the ReadOnlySharedMemory class, as shown above.template = “””This is a conversation between a human and a bot:{chat_history}Write a summary of the conversation for {input}:”””prompt = PromptTemplate( input_variables=[“input”, “chat_history”], template=template)memory = ConversationBufferMemory(memory_key=”chat_history”)summry_chain = LLMChain( llm=OpenAI(), prompt=prompt, verbose=True, memory=memory, # <— this is the only change)search = GoogleSearchAPIWrapper()tools = [ Tool( name = “Search”, func=search.run, description=”useful for when you need to answer questions about current events” ), Tool( name = “Summary”, func=summry_chain.run, description=”useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary.” )]prefix = “””Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:”””suffix = “””Begin!”{chat_history}Question: {input}{agent_scratchpad}”””prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=[“input”, “chat_history”, “agent_scratchpad”])llm_chain = LLMChain(llm=OpenAI(temperature=0), 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)agent_chain.run(input=”What is ChatGPT?”)> Entering new AgentExecutor chain…Thought: I should research ChatGPT to answer this question.Action: SearchAction Input: “ChatGPT”Observation: Nov 30, 2022 … We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer … ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large … ChatGPT. We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer … Feb 2, 2023 … ChatGPT, the popular chatbot from OpenAI, is estimated to have reached 100 million monthly active users in January, just two months after … 2 days ago … ChatGPT recently launched a new version of its own plagiarism detection tool, with hopes that it will squelch some of the criticism around how … An API for accessing new AI models developed by OpenAI. Feb 19, 2023 … ChatGPT is an AI chatbot system that OpenAI released in November to show off and test what a very large, powerful AI system can accomplish. You … ChatGPT is fine-tuned from GPT-3.5, a language model trained to produce text. ChatGPT was optimized for dialogue by using Reinforcement Learning with Human … 3 days ago … Visual ChatGPT connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting. Dec 1, 2022 … ChatGPT is a natural language processing tool driven by AI technology that allows you to have human-like conversations and much more with a …Thought: I now know the final answer.Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.> Finished chain.”ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.”agent_chain.run(input=”Who developed it?”)> Entering new AgentExecutor chain…Thought: I need to find out who developed ChatGPTAction: SearchAction Input: Who developed ChatGPTObservation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large … Feb 15, 2023 … Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. The organization is headquartered in San … Feb 8, 2023 … ChatGPT is an AI chatbot developed by San Francisco-based startup OpenAI. OpenAI was co-founded in 2015 by Elon Musk and Sam Altman and is … Dec 7, 2022 … ChatGPT is an AI chatbot designed and developed by OpenAI. The bot works by generating text responses based on human-user input, like questions … Jan 12, 2023 … In 2019, Microsoft invested $1 billion in OpenAI, the tiny San Francisco company that designed ChatGPT. And in the years since, it has quietly … Jan 25, 2023 … The inside story of ChatGPT: How OpenAI founder Sam Altman built the world’s hottest technology with billions from Microsoft. Dec 3, 2022 … ChatGPT went viral on social media for its ability to do anything from code to write essays. · The company that created the AI chatbot has a … Jan 17, 2023 … While many Americans were nursing hangovers on New Year’s Day, 22-year-old Edward Tian was working feverishly on a new app to combat misuse … ChatGPT is a language model created by OpenAI, an artificial intelligence research laboratory consisting of a team of researchers and engineers focused on … 1 day ago … Everyone is talking about ChatGPT, developed by OpenAI. This is such a great tool that has helped to make AI more accessible to a wider …Thought: I now know the final answerFinal Answer: ChatGPT was developed by OpenAI.> Finished chain.’ChatGPT was developed by OpenAI.’agent_chain.run(input=”Thanks. Summarize the conversation, for my daughter 5 years old.”)> Entering new AgentExecutor chain…Thought: I need to simplify the conversation for a 5 year old.Action: SummaryAction Input: My daughter 5 years old> Entering new LLMChain chain…Prompt after formatting:This is a conversation between a human and a bot:Human: What is ChatGPT?AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.Human: Who developed it?AI: ChatGPT was developed by OpenAI.Write a summary of the conversation for My daughter 5 years old:> Finished chain.Observation: The conversation was about ChatGPT, an artificial intelligence chatbot developed by OpenAI. It is designed to have conversations with humans and can also send and receive images.Thought: I now know the final answer.Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI that can have conversations with humans and send and receive images.> Finished chain.’ChatGPT is an artificial intelligence chatbot developed by OpenAI that can have conversations with humans and send and receive images.’最后的答案没有错,但是我们看到第三个Human input实际上是来自内存中的agent,因为内存被summary tool修改了。

print(agent_chain.memory.buffer)Human: What is ChatGPT?AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI’s GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capable of sending and receiving images during chatting.Human: Who developed it?AI: ChatGPT was developed by OpenAI.Human: My daughter 5 years oldAI: The conversation was about ChatGPT, an artificial intelligence chatbot developed by OpenAI. It is designed to have conversations with humans and can also send and receive images.Human: Thanks. Summarize the conversation, for my daughter 5 years old.AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI that can have conversations with humans and send and receive images.

计划和执行

计划和执行代理通过首先计划要做什么,然后执行子任务来完成目标。这个想法很大程度上是受到了BabyAGI的启发,然后是“Plan-and-Solve”论文。

规划几乎总是由法学硕士完成。

执行通常由单独的代理(配备工具)完成。

进口from langchain.chat_models import ChatOpenAI from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner from langchain.llms import OpenAI from langchain import SerpAPIWrapper from langchain.agents.tools import Tool from langchain import LLMMathChain

工具search = SerpAPIWrapper() llm = OpenAI(temperature=0) llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True) tools = [ Tool( name = “Search”, func=search.run, description=”useful for when you need to answer questions about current events” ), Tool( name=”Calculator”, func=llm_math_chain.run, description=”useful for when you need to answer questions about math” ), ]

计划者、执行者和代理人model = ChatOpenAI(temperature=0) planner = load_chat_planner(model) executor = load_agent_executor(model, tools, verbose=True) agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)

运行示例

agent.run(“Who is Leo DiCaprio’s girlfriend? What is her current age raised to the 0.43 power?”)

> Entering new PlanAndExecute chain… steps=[Step(value=”Search for Leo DiCaprio’s girlfriend on the internet.”), Step(value=’Find her current age.’), Step(value=’Raise her current age to the 0.43 power using a calculator or programming language.’), Step(value=’Output the result.’), Step(value=”Given the above steps taken, respond to the user’s original question.\n\n”)]

> Entering new AgentExecutor chain… Action: “` { “action”: “Search”, “action_input”: “Who is Leo DiCaprio’s girlfriend?” } “` Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He’s since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week. Thought:Based on the previous observation, I can provide the answer to the current objective. Action: “` { “action”: “Final Answer”, “action_input”: “Leo DiCaprio is currently linked to Gigi Hadid.” } “`

> Finished chain. ***** Step: Search for Leo DiCaprio’s girlfriend on the internet. Response: Leo DiCaprio is currently linked to Gigi Hadid.

> Entering new AgentExecutor chain… Action: “` { “action”: “Search”, “action_input”: “What is Gigi Hadid’s current age?” } “` Observation: 28 years Thought:Previous steps: steps=[(Step(value=”Search for Leo DiCaprio’s girlfriend on the internet.”), StepResponse(response=’Leo DiCaprio is currently linked to Gigi Hadid.’))] Current objective: value=’Find her current age.’ Action: “` { “action”: “Search”, “action_input”: “What is Gigi Hadid’s current age?” } “` Observation: 28 years Thought:Previous steps: steps=[(Step(value=”Search for Leo DiCaprio’s girlfriend on the internet.”), StepResponse(response=’Leo DiCaprio is currently linked to Gigi Hadid.’)), (Step(value=’Find her current age.’), StepResponse(response=’28 years’))] Current objective: None Action: “` { “action”: “Final Answer”, “action_input”: “Gigi Hadid’s current age is 28 years.” } “` > Finished chain. ***** Step: Find her current age. Response: Gigi Hadid’s current age is 28 years.

> Entering new AgentExecutor chain… Action: “` { “action”: “Calculator”, “action_input”: “28 ** 0.43” } “`

> Entering new LLMMathChain chain… 28 ** 0.43 “`text 28 ** 0.43 “` …numexpr.evaluate(“28 ** 0.43”)… Answer: 4.1906168361987195 > Finished chain. Observation: Answer: 4.1906168361987195 Thought:The next step is to provide the answer to the user’s question. Action: “` { “action”: “Final Answer”, “action_input”: “Gigi Hadid’s current age raised to the 0.43 power is approximately 4.19.” } “`

> Finished chain. ***** Step: Raise her current age to the 0.43 power using a calculator or programming language. Response: Gigi Hadid’s current age raised to the 0.43 power is approximately 4.19.

> Entering new AgentExecutor chain… Action: “` { “action”: “Final Answer”, “action_input”: “The result is approximately 4.19.” } “` > Finished chain. ***** Step: Output the result. Response: The result is approximately 4.19.

用户评论

LangChain手册(Python版)27模块:代理执行器
﹏櫻之舞﹏

终于找到了!我一直想学习Agent代理执行器,这款 LangChain 手册简直太棒了! 讲解清楚、步骤详细,图解方便理解,Python版的代码也很实用。已经开始跟着教程实践了,感觉很有成就感!

    有12位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
泪湿青衫

这个手册的27个模块介绍真是丰富啊, Agent代理执行器听起来就很牛逼,搞不清具体是做什么用的,但看内容感觉非常强大,可以自动化很多工作流程。等我学废了时间再来深入研究这方面。

    有14位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
像从了良

Python版手册?终于不用切换语言!LangChain 这个框架太酷了,希望能用 Agent执行器来构建一个智能问答机器人。希望这个手册能帮我解决一些关于代理逻辑和环境的疑问吧,感觉这些地方很容易迷路。

    有20位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
无望的后半生

看完27个模块的介绍,还是有些懵逼的状态。作为大数据领域研究者,对于 Agent执行器的概念很有兴趣,但具体应用场景和实现细节需要更详细的讲解。期待这方面能够提供更多案例和实战经验分享。

    有12位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
迷路的男人

LangChain手册写的太赞了!特别是Agent代理执行器这一部分,解释得很到位,图文并茂,很容易理解。之前用过别的语言版本的LangChain,感觉Python版更加简洁明了,真的很棒!

    有6位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
坠入深海i

这27个模块都看起来很酷炫,感觉 LangChain真是个强大的框架!希望能应用于我的项目中,构建一个智能化的小工具。不过 Agent执行器需要更深入理解才能运用,希望手册能提供更多实战案例和经验分享。

    有11位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
太难

作为一个初学者,发现Python版LangChain手册真的很贴心,27个模块的讲解非常全面,特别是对于Agent代理执行器部分,图解清晰,思路明确。感觉学习起来会更轻松!

    有18位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
惦着脚尖摘太阳

LangChain 手册一直是我的首选资源,这次更新的Agent代理执行器板块也很棒! 终于找到解决特定任务流程自动化的问题了。希望能看到更多关于安全性和可靠性的探讨和建议。

    有9位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
枫无痕

这个手册感觉有点过于简略了, Agent代理执行器相关的细节没有讲得很彻底,对于想要深入学习的人来说,不太实用。期待更加详细的教程或书籍能够推出!

    有8位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
瑾澜

LangChain真是个神奇的框架! 虽然Agent代理执行器听起来很复杂,但看着手册感觉其实应用起来并不难。 hâte to start building my own agents!

    有11位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
此生一诺

我试着按照手册来实现 Agent代理执行器功能,但是遇到了了一些问题,手册的代码示例不够完善,缺少调试技巧和常见问题的解答。希望能够后续更新补充相关内容,这样学习起来会更容易一些。

    有13位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
服从

作为一名Python爱好者,我很高兴看到LangChain 手册提供了Python版资源! Agent代理执行器 很有潜力,期待它可以应用于更多的场景。 希望手册能提供更多关于最佳实践和性能调优的讲解

    有10位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
涐们的幸福像流星丶

27个模块感觉有点吓人… 但我迫切想学习Agent代理执行器,希望能通过这个手册掌握基础知识。希望手册能够提供更多实践案例和实战经验分享,这样才能更好地理解 Agent执行器的应用场景。

    有10位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
七夏i

LangChain 的强大之处在于可以用 Agent 代理执行器来构建复杂的智能系统,这套教程做得很好,解释了每个模块的功能和作用,让我对 Agent代理执行器有了更深入的了解。我已经迫不及待地想在项目中实践它!

    有9位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
素婉纤尘

学习Python版 LangChain手册 Agent代理执行器的模块,感觉LangChain真是个强大的框架! 它能够帮我自动化很多工作流程,提高工作效率。 手册讲解得非常清楚, 也很实用,已经开始跟着教程进行练习了。

    有11位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
﹎℡默默的爱

LangChain的手册真是越来越好用了! 这27个模块的介绍太棒了,特别是 Agent代理执行器部分,以前我对这个概念一直有点模糊,现在阅读后豁然开朗。 特别感谢作者在手册中加入了很多实用案例和代码示例,让我更容易理解Agent代理执行器的应用场景。

    有10位网友表示赞同!

LangChain手册(Python版)27模块:代理执行器
冷嘲热讽i

我一直想学习如何利用AI来自动化一些工作流程,看到LangChain 的 Agent代理执行器 感觉非常适合我。 本次的Python版手册讲解很详细,帮助我快速入门了 Agent代理执行器的基本原理和使用方法,希望以后可以分享更多关于实战案例的内容!

    有19位网友表示赞同!

原创文章,作者:小su,如若转载,请注明出处:https://www.sudun.com/ask/105214.html

(0)
小su的头像小su
上一篇 2024年8月30日 上午7:33
下一篇 2024年8月30日 上午7:44

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注