LangChainの Plan and Execute を試してみる

FacebooktwitterredditpinterestlinkedinmailFacebooktwitterredditpinterestlinkedinmail

LangChain の Plan and Execute とは

参考:https://python.langchain.com/docs/modules/agents/agent_types/plan_and_execute

LangChain の Plan and Execute は、BabyAGIPlan-and-Solve の論文に強くインスパイアされた、何をすべきかを先に計画し、その後にサブタスクを実行するエージェントの実装です。

論文: Plan-and-Solve の概要

LLM では精度を上げるために、Step-by-Step のfew-shot の思考の連鎖(CoT)プロンプトが提案、使用されています。これにより、LLM は明示的に推論のステップを生成し、そのタスクの精度を向上させています。

手作業をなくすために、Zero-Shot CoT は、「一歩一歩考えましょう」「Step by Stepで考えましょう」といった入力プロンプトを利用します。これは、 ChatGPT 登場初期によく用いられたプロンプトのテクニックの一つです。しかし、こういった工夫を行っても、3つの落とし穴が存在します。それは、

  1. 計算ミス
  2. ステップが欠落するミス
  3. 誤解によるミス

この論文で提案されるのは、ステップの欠落への対処であり、 Plan-and-Solve (PS) プロンプトと呼ばれています。このプロンプトは2つのコンポーネントからなっており、

  1. 全体のタスクをより小さなサブタスクに分割する「計画」を実施する
  2. 計画に従ってサブタスクを実行する

また、計算エラーに対処し、生成されたステップの品質を高めるために、PSプロンプトをより詳細な指示で拡張、PS+プロンプトを導き出しています。

著者らは、提案された Zero-Shot プロンプトがすべてのデータセットで Zero-Shot CoT プロンプトのを大幅に上回っていると主張しています。さらに、 Zero-Shot Program-of-Thought プロンプトと比較しても同等から上回るとしています。また、数学的推論においては、 8-shot(few-shot) CoTと同等であるとされています。

ただし、GPT-3でのことなので、他のモデルやGPT-3.5-turbo以降のモデルでも同様の結果になるかは不明です。また、 LangChain に実装されたものは、強くインスパイアされたものであり同様のものでもないので、そこも注意が必要です。更に言えば、日本語をプロンプトに使う場合は、当然言語の違いも重要です。

コード:https://github.com/AGI-Edgerunners/Plan-and-Solve-Prompting

 

ということで、かなり新しめのエージェントの実装なので、どんな挙動をするか試してみたいと思います。

Plan-and-Execute を使って見る

計画を立てさせて(Plan)、サブタスクを実行(Execute)する実装なので、LangChain の Tool を複数使用します。例えば、そこそこ複雑な検索プロセスであれば検索ツール1種類でもなんとかそれっぽい動作をするかもしれませんが、現状、GPT-xの実装で知らないことを何度も検索させる方が大変なので、大人しく複数使います。

参考にした LangChain の Document では SerpAPI を使っていましたが、ここでは以前から扱っている Google Search API の方を使います。

まずは import

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.utilities import GoogleSearchAPIWrapper
from langchain.agents.tools import Tool
from langchain import LLMMathChain

重要なのはやはり、

from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner

ここで、PlanAndExecute と、 load_agent_executor, load_chat_planner を import しています。

後々コードでも出て来ますが、

  • LangChain の agent としての実体:PlanAndExecute
  • LLMを利用して計画を立てる(つまり LLM を直接実行する実体):load_chat_planner
  • LangChain の Tool を認識し、実行を行う( LLM に Tools を使わせる実体):load_agent_executor

となっています。

agent_executor に与える Tool は、 LLMMathChain (数学的な演算を行う)と Google Search が相当します。

Tool の作成

search = GoogleSearchAPIWrapper()
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"
    ),
]

検索と数学演算の Tool のインスタンスを作成、さらに Tool インスタンスのリストとしています。 LLMMathChain は ChatOpenAI ではなく OpenAI のインスタンスを渡しています(恐らく Chat 用に fine-tune されていない方が都合がいいのでしょう)。

agent にまとめる

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)

こちらは、 Chat 用に fine-tune されたモデルとの prompt から派生したエージェントだからだと思いますが、 model として ChatOpenAI を利用します。

計画を立てる planner は通常の対話モデルがあればいいので引数は model のみ、 executor はそれに加えて、Tool インスタンスを格納したリストが必要です。

実際に実行を行う agent はテキストを適切に評価すればいいので、 model は引数にとらず、planner, executor のみを受け取ります。

 

BabyAGI や AutoGPT のときには、Memory 自体も必須となっていたので、Zero-Shot で実行する分、こちらの方が大分気軽に実行できるように思います。一方で、Zero-Shot agent よりは複雑にタスクを実行させるといった感じでしょうか。

実行する

agent.run("宮崎駿の最新作の名前は? また、宮崎駿の現在の年齢を0.43乗してください。")

何故か()サンプルでは執拗に年齢を0.43乗したがっていたので、それにならうことにします。また事前学習では知るはずもない、ということで映画の最新作を聞いています。

結果(verbose の出力)

> Entering new PlanAndExecute chain...
steps=[Step(value='Research the latest work of Hayao Miyazaki.'), Step(value='Find out the current age of Hayao Miyazaki.'), Step(value='Calculate the age of Hayao Miyazaki raised to the power of 0.43.'), Step(value="Given the above steps taken, respond to the user's original question.\n\n")]

> Entering new AgentExecutor chain...
Thought: I can use the Search tool to find the latest work of Hayao Miyazaki.

Action:
```{"action": "Search", "action_input": "latest work of Hayao Miyazaki"}```
Observation: Other creditsEdit ; 2015, Avengers: Age of Ultron, Thanks ; 2016, Never-Ending Man: Hayao Miyazaki, Subject ; 2017, Mary and the Witch's Flower, Thanks ; 2019, 10 ... Nov 23, 2021 ... When his last film, “The Wind Rises,” came out in 2013, it did well at the box office but fell short of his previous four features, perhaps ... The Boy and the Heron is a 2023 Japanese animated fantasy film written and directed by Hayao Miyazaki and produced by Studio Ghibli. Unlike Studio Ghibli's latest film, Earwig and the Witch (2020) made by Gorō Miyazaki entirely in 3D animation, How Do You Live? will use 2D animation—and ... Jun 5, 2023 ... How Do You Live? is due to be released in Japan on 14 July, but prospective filmgoers are not entirely devoid of information. Studio Ghibli, the ... Jul 14, 2023 ... Japanese fans queuing for tickets to see Hayao Miyazaki's latest film. There are inside the. There was excitement among Japanese film fans ... Nov 1, 2022 ... Hayao Miyazaki's Beautiful, Broken Worlds ... “Shuna's Journey,” a newly translated manga by the celebrated children's animator, asks what it's ... The success of the film led to the establishment of a new animation studio, Studio Ghibli. Since then, he has since directed, written & produced many other ... Dec 13, 2022 ... Studio Ghibli Sets New Miyazaki Hayao Film, 'How Do You Live,' for Summer 2023. By K.J. Yossman. Oct 30, 2022 ... Miyazaki's last film, How Do You Live? releases sometime in 2023. In the meantime, catch other Studio Ghibli titles such as Spirited Away and My ...
Thought:The latest work of Hayao Miyazaki is a film called "How Do You Live?" It is a Japanese animated fantasy film written and directed by Hayao Miyazaki and produced by Studio Ghibli. The film is set to be released in Japan on July 14, 2023. It will be a 2D animated film, unlike Studio Ghibli's previous film "Earwig and the Witch" which was made entirely in 3D animation.

> Finished chain.
*****

Step: Research the latest work of Hayao Miyazaki.

Response: The latest work of Hayao Miyazaki is a film called "How Do You Live?" It is a Japanese animated fantasy film written and directed by Hayao Miyazaki and produced by Studio Ghibli. The film is set to be released in Japan on July 14, 2023. It will be a 2D animated film, unlike Studio Ghibli's previous film "Earwig and the Witch" which was made entirely in 3D animation.

> Entering new AgentExecutor chain...
Action:
```{"action": "Search", "action_input": "current age of Hayao Miyazaki"}```
Observation: Early lifeEdit. Hayao Miyazaki was born on January 5, 1941, in Tokyo City, Empire of Japan, the second of four sons. Miyazaki Hayao ; Born: January 5, 1941 (age 82) Tokyo Japan ; Founder: Studio Ghibli ; Awards And Honors: Academy Award (2015) He was born on January 5, 1941 in Tokyo. He started his career in 1963 as an animator at the studio Toei Douga studio, and was subsequently involved in many ... Hayao Miyazaki. Director. Birthday January 5, 1941. Birth Sign Capricorn. Birthplace Tokyo, Japan. Age 82 years old. #18380 Most Popular. Nov 1, 2022 ... The children's animator and manga artist Hayao Miyazaki returns over ... war-torn dystopia can be changed only by her idealistic teen-age ... Apr 17, 2016 ... Totoros, Boar Gods, and River SpiritsNature Spirits as Intermediaries in the Animation of Hayao Miyazaki. Chris G. Hall (bio). Jan 20, 2023 ... Hayao Miyazaki “retired” multiple times after his “final film. ... at his current age, the team can only handcraft one-minute of animation ... In this celebrated Hayao Miyazaki fantasy, ten-year-old Chihiro and her parents stumble upon an abandoned theme park that turns out to be a true magic kingdom. Hayao Miyazaki (Miyazaki Hayao, born January 5, 1941) is a Japanese manga artist and prominent film director and animator of many popular anime feature ... Tickets. All admission to the Ghibli Museum is by advance reservation only. No reservation or ticket purchase can be made at the Museum. Ages 19 and over ...     
Thought:Based on the search results, the current age of Hayao Miyazaki is 82 years old. 

Action:
```{"action": "Final Answer", "action_input": "Hayao Miyazaki is currently 82 years old."}```

> Finished chain.
*****

Step: Find out the current age of Hayao Miyazaki.

Response: Hayao Miyazaki is currently 82 years old.

> Entering new AgentExecutor chain...
Action:
```
{
  "action": "Calculator",
  "action_input": "82^0.43"
}
```

> Entering new LLMMathChain chain...
82^0.43```text
82**0.43
```
...numexpr.evaluate("82**0.43")...

Answer: 6.651811850794001
> Finished chain.

Observation: Answer: 6.651811850794001
Thought:The age of Hayao Miyazaki raised to the power of 0.43 is approximately 6.65.

Final Answer: 6.65

> Finished chain.
*****

Step: Calculate the age of Hayao Miyazaki raised to the power of 0.43.

Response: The age of Hayao Miyazaki raised to the power of 0.43 is approximately 6.65.

Final Answer: 6.65

> Entering new AgentExecutor chain...
Action:
{
  "action": "Final Answer",
  "action_input": "The latest work of Hayao Miyazaki is a film called 'How Do You Live?' It is a Japanese animated fantasy film written and directed by Hayao Miyazaki and produced by Studio Ghibli. The film is set to be released in Japan on July 14, 2023. It will be a 2D animated film, unlike Studio Ghibli's previous film 'Earwig and the Witch' which was made entirely in 3D animation. Hayao Miyazaki is currently 82 years old. The age of Hayao Miyazaki raised to the power of 0.43 is approximately 6.65."
}

> Finished chain.
*****

Step: Given the above steps taken, respond to the user's original question

無限ループに陥ることもなく、スムーズに回答にたどり着いています。

一方で、agent 内の prompt がかなりの分量の英語である影響だと思いますが、回答が英語になってしまっています。実用しようと思うと、この点はやはりSystem Role の Prompt をカスタマイズするなどして対応する必要があると思います。

終わりに

Plan-and-Execute はZero-Shot の prompt で実行することが前提なので、メモリを持たなくていい分、自分の記憶に引きずられない点に利点があるように思います。 ChatGPT の Code Interpreter のように積極的に対話を行い、実行許可を求めたり質問したりする姿勢は、実行時のエラーを防止する点では便利ですが、シンプルなタスクではやや面倒です。

その点、ZeroShotで動作するので、シンプルなツールをまとめるだけのタスクであれば(書き込みや削除などの取り返しの付かないエラーが発生しないタスクであれば)扱いやすいでしょう。

一方で、他の BabyAGI や AutoGPT などの Agent の実装と同様に、どうしても日本語で回答を得るのにコツや prompt の工夫が必要な点は注意が必要かと思います。この点は、カスタムプロンプトを食わせるなどして、対策が必要かなと思います。

FacebooktwitterredditpinterestlinkedinmailFacebooktwitterredditpinterestlinkedinmail

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

最新の記事