天天看點

LangChain手冊(Python版)27子產品:Agent代理執行器

作者:AI讓生活更美好

代理執行者采用代理和工具,并使用代理來決定調用哪些工具以及調用的順序。

在文檔的這一部分中,我們介紹了代理執行器的其他相關功能

  • 如何結合代理和向量存儲
  • 如何為代理使用異步 API
  • 如何建立 ChatGPT 克隆
  • 處了解析錯誤
  • 如何通路中間步驟
  • 如何限制最大疊代次數
  • 如何為代理使用逾時
  • 如何将 SharedMemory 添加到代理及其工具

如何結合代理和向量存儲

本筆記本介紹了如何組合代理和矢量存儲。此用例是您已将資料提取到矢量存儲中并希望以代理方式與其互動。

這樣做的推薦方法是建立 RetrievalQA,然後将其用作整體代理中的工具。讓我們看看下面的操作。您可以使用多個不同的 vectordbs 執行此操作,并使用代理作為在它們之間進行路由的方式。有兩種不同的方法可以做到這一點——您可以讓代理将矢量存儲用作普通工具,或者您可以設定return_direct=True為真正隻将代理用作路由器。

建立 Vectorstorefrom langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import RetrievalQA llm = OpenAI(temperature=0) from pathlib import Path relevant_parts = [] for p in Path(".").absolute().parts: relevant_parts.append(p) if relevant_parts[-3:] == ["langchain", "docs", "modules"]: break doc_path = str(Path(*relevant_parts) / "state_of_the_union.txt") from langchain.document_loaders import TextLoader loader = TextLoader(doc_path) documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. 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()) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.

建立代理# Import things that are needed generically 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="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question." ), Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question." ), ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address. Action: State of Union QA System Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address? Observation: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent.run("Why use ruff over flake8?") > Entering new AgentExecutor chain... I need to find out the advantages of using ruff over flake8 Action: Ruff QA System Action Input: What are the advantages of using ruff over flake8? Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. Thought: I now know the final answer Final Answer: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. > Finished chain. 'Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.'

将 Agent 單獨用作路由器

return_direct=True如果你打算将代理用作路由器并且隻想直接傳回 RetrievalQAChain 的結果,你也可以設定。

請注意,在上面的示例中,代理在查詢 RetrievalQAChain 之後做了一些額外的工作。您可以避免這種情況并直接傳回結果。

tools = [
    Tool(
        name = "State of Union QA System",
        func=state_of_union.run,
        description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.",
        return_direct=True
    ),
    Tool(
        name = "Ruff QA System",
        func=ruff.run,
        description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question.",
        return_direct=True
    ),
]
           
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
           
agent.run("What did biden say about ketanji brown jackson in the state of the union address?")
           
> Entering new AgentExecutor chain...
 I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address.
Action: State of Union QA System
Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address?
Observation:  Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.


> Finished chain.
           
" Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
           
agent.run("Why use ruff over flake8?")
           
> Entering new AgentExecutor chain...
 I need to find out the advantages of using ruff over flake8
Action: Ruff QA System
Action Input: What are the advantages of using ruff over flake8?
Observation:  Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.


> Finished chain.
           
' Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.'
           

多跳矢量存儲推理

因為 vectorstores 很容易用作代理中的工具,是以很容易使用現有的代理架構來回答依賴于 vectorstores 的多跳問題

tools = [
    Tool(
        name = "State of Union QA System",
        func=state_of_union.run,
        description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question, not referencing any obscure pronouns from the conversation before."
    ),
    Tool(
        name = "Ruff QA System",
        func=ruff.run,
        description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before."
    ),
]
           
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
           
agent.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?")
           
> Entering new AgentExecutor chain...
 I need to find out what tool ruff uses to run over Jupyter Notebooks, and if the president mentioned it in the state of the union.
Action: Ruff QA System
Action Input: What tool does ruff use to run over Jupyter Notebooks?
Observation:  Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb
Thought: I now need to find out if the president mentioned this tool in the state of the union.
Action: State of Union QA System
Action Input: Did the president mention nbQA in the state of the union?
Observation:  No, the president did not mention nbQA in the state of the union.
Thought: I now know the final answer.
Final Answer: No, the president did not mention nbQA in the state of the union.

> Finished chain.
           
'No, the president did not mention nbQA in the state of the union.'           

如何為代理使用異步 API

LangChain 通過利用asyncio庫為代理提供異步支援。

目前支援以下異步方法Tools:GoogleSerperAPIWrapper和SerpAPIWrapper。LLMMathChain對其他代理工具的異步支援在路線圖上。

對于Tool已經coroutine實作(上面提到的三個)的 s,AgentExecutor将await直接執行它們。否則,AgentExecutor将調用Tool的funcviaasyncio.get_event_loop().run_in_executor以避免阻塞主運作循環。

您可以使用異步arun調用AgentExecutor。

串行與并發執行

在此示例中,我們啟動代理以串行或同時回答一些問題。您可以看到并發執行顯着加快了速度。

import asyncio
import time

from langchain.agents import initialize_agent, load_tools
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain.callbacks.stdout import StdOutCallbackHandler
from langchain.callbacks.tracers import LangChainTracer
from aiohttp import ClientSession

questions = [
    "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() - s
print(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 Serper
Action 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: Calculator
Action Input: 33^0.334
Observation: Answer: 3.215019829667466
Thought: 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 Serper
Action 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 Serper
Action Input: "Harry Styles age"
Observation: 29 years
Thought: I need to calculate 29 raised to the 0.23 power.
Action: Calculator
Action Input: 29^0.23
Observation: Answer: 2.169459462491557
Thought: 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 Serper
Action 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, 2021
Thought: I need to find out Max Verstappen's age
Action: Google Serper
Action Input: "Max Verstappen age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.23 power
Action: Calculator
Action Input: 25^0.23
Observation: Answer: 2.096651272316035
Thought: I now know the final answer
Final 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 Serper
Action 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, 2019
Thought: I now need to calculate her age raised to the 0.34 power.
Action: Calculator
Action Input: 19^0.34
Observation: Answer: 2.7212987634680084
Thought: 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 Serper
Action Input: "Who is Beyonce's husband?"
Observation: Jay-Z
Thought: I need to find out Jay-Z's age
Action: Google Serper
Action Input: "How old is Jay-Z?"
Observation: 53 years
Thought: I need to calculate 53 raised to the 0.19 power
Action: Calculator
Action Input: 53^0.19
Observation: Answer: 2.12624064206896
Thought: I now know the final answer
Final 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_complete
tasks = [agent.arun(q) for q in questions]
await asyncio.gather(*tasks)
elapsed = time.perf_counter() - s
print(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 Serper
Action 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 Serper
Action 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 Serper
Action 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 Serper
Action 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 Serper
Action 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-Z
Thought:
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, 2019
Thought:
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 Serper
Action Input: "Harry Styles age" I need to find out Jay-Z's age
Action: Google Serper
Action 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: Calculator
Action Input: 33^0.334 I now need to calculate her age raised to the 0.34 power.
Action: Calculator
Action Input: 19^0.34
Observation: 29 years
Thought:
Observation: 53 years
Thought: Max Verstappen won the most recent Formula 1 grand prix.
Action: Calculator
Action Input: Max Verstappen's age (23) raised to the 0.23 power
Observation: Answer: 2.7212987634680084
Thought:
Observation: Answer: 3.215019829667466
Thought: I need to calculate 29 raised to the 0.23 power.
Action: Calculator
Action Input: 29^0.23 I need to calculate 53 raised to the 0.19 power
Action: Calculator
Action Input: 53^0.19
Observation: Answer: 2.0568252837687546
Thought:
Observation: Answer: 2.169459462491557
Thought:
> Finished chain.

> Finished chain.

Observation: Answer: 2.12624064206896
Thought:
> Finished chain.

> Finished chain.

> Finished chain.
Concurrent executed in 17.52 seconds.           

如何建立 ChatGPT 克隆

該鍊通過結合 (1) 特定提示和 (2) 記憶體概念來複制 ChatGPT。

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

from langchain import OpenAI, ConversationChain, LLMChain, PromptTemplate
from langchain.memory import ConversationBufferWindowMemory


template = """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.py
Assistant:

> Finished LLMChain chain.


```
$ echo -e "x=lambda y:y*5+3;print('Result:' + str(x(6)))" > run.py
$ python3 run.py
Result: 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.py
AI: 

```
$ echo -e "x=lambda y:y*5+3;print('Result:' + str(x(6)))" > run.py
$ python3 run.py
Result: 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.py
Assistant:

> 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.py
AI: 

```
$ echo -e "x=lambda y:y*5+3;print('Result:' + str(x(6)))" > run.py
$ python3 run.py
Result: 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.py
AI: 

```
$ 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.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_image
Assistant:

> Finished LLMChain chain.


```
$ echo -e "echo 'Hello from Docker" > entrypoint.sh
$ echo -e "FROM ubuntu:20.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile
$ docker build . -t my_docker_image
$ docker run -t my_docker_image
Hello 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.py
AI: 

```
$ 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.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_image
AI: 

```
$ echo -e "echo 'Hello from Docker" > entrypoint.sh
$ echo -e "FROM ubuntu:20.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile
$ docker build . -t my_docker_image
$ docker run -t my_docker_image
Hello from Docker
```
Human: nvidia-smi
Assistant:

> Finished LLMChain chain.


```
$ nvidia-smi
Sat 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.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile && docker build . -t my_docker_image && docker run -t my_docker_image
AI: 

```
$ echo -e "echo 'Hello from Docker" > entrypoint.sh
$ echo -e "FROM ubuntu:20.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile
$ docker build . -t my_docker_image
$ docker run -t my_docker_image
Hello from Docker
```
Human: nvidia-smi
AI: 

```
$ nvidia-smi
Sat 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.com
Assistant:

> Finished LLMChain chain.


```
$ ping bbc.com
PING bbc.com (151.101.65.81): 56 data bytes
64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms
64 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 loss
round-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-smi
AI: 

```
$ nvidia-smi
Sat 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.com
AI: 

```
$ ping bbc.com
PING bbc.com (151.101.65.81): 56 data bytes
64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms
64 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 loss
round-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.com
AI: 

```
$ ping bbc.com
PING bbc.com (151.101.65.81): 56 data bytes
64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms
64 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 loss
round-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/careers
Assistant:

> Finished LLMChain chain.


```
$ lynx https://www.deepmind.com/careers
DeepMind Careers

Welcome 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/careers
AI: 

```
$ lynx https://www.deepmind.com/careers
DeepMind Careers

Welcome 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/chat
Assistant:

> 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/careers
AI: 

```
$ lynx https://www.deepmind.com/careers
DeepMind Careers

Welcome 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/chat
AI:  

```
$ 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/chat
Assistant:

> 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/chat
AI:  

```
$ 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/chat
AI: 

```
$ 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/chat
Assistant:

> 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 range

During 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 response
Thought:
Observation: Invalid or incomplete response
Thought:Search for Leo DiCaprio's current girlfriend
Action:
```
{
  "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 girlfriend
Final 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 canno
Thought: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 canno
Thought: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_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from 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 dating
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I should look up how old Camila Morrone is
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I should calculate what 25 years raised to the 0.43 power is
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078

Thought: I now know the final answer
Final 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 observation
print(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 json
print(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, AgentExecutor
from langchain.memory import ConversationBufferMemory, ReadOnlySharedMemory
from langchain import OpenAI, LLMChain, PromptTemplate
from langchain.utilities import GoogleSearchAPIWrapper
           
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")
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,然後建立代理。

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: Search
Action 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 ChatGPT
Action: Search
Action Input: Who developed ChatGPT
Observation: 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 answer
Final 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: Summary
Action 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: Search
Action 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 ChatGPT
Action: Search
Action Input: Who developed ChatGPT
Observation: 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 answer
Final 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: Summary
Action 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 old
AI: 
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.

> Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19." } ``` > Finished chain. ***** Step: Given the above steps taken, respond to the user's original question. Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19.

> Finished chain. "Gigi Hadid's current age raised to the 0.43 power is approximately 4.19."