<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>chatgpt - まったり勉強ノート</title>
	<atom:link href="https://www.mattari-benkyo-note.com/tag/chatgpt/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mattari-benkyo-note.com</link>
	<description>shuの日々の勉強まとめ</description>
	<lastBuildDate>Tue, 04 Apr 2023 23:56:22 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">189243286</site>	<item>
		<title>LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Tue, 04 Apr 2023 22:25:29 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[chatgpt]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2691</guid>

					<description><![CDATA[<p>ChatGPTのようなLLMを使ったライブラリやサービスがいくつも最近でてきています。その中でも以前、LangChainというPythonのライブラリを紹介しました。 今回はこの中で紹介した例で出てきた「zero-sho [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/">LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>ChatGPTのようなLLMを使ったライブラリやサービスがいくつも最近でてきています。その中でも以前、LangChainというPythonのライブラリを紹介しました。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="syFTXPTafz"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/embed/#?secret=Oq7PdhWcSH#?secret=syFTXPTafz" data-secret="syFTXPTafz" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>今回はこの中で紹介した例で出てきた「<a href="https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html#zero-shot-react-description" target="_blank" rel="noopener" title="zero-shot-react-description">zero-shot-react-description</a>」というAgentを使って以下の質問をしたときに内部でLLMとどういう連携をしているのか？を調べたのでそのまとめになります。</p>



<pre class="wp-block-preformatted">"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"</pre>



<p>今回動作検証に用いたコードは以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="lang_chain_agent" data-lang="Python"><code>import langchain
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.llms import OpenAI


langchain.verbose = True

llm = OpenAI(temperature=0, verbose=True)
tools = load_tools([&quot;serpapi&quot;, &quot;llm-math&quot;], llm=llm)
agent = initialize_agent(tools, llm, agent=&quot;zero-shot-react-description&quot;, verbose=True)
agent.run(&quot;Who is Leo DiCaprio&#39;s girlfriend? What is her current age raised to the 0.43 power?&quot;)</code></pre></div>



<h2 class="wp-block-heading">zero-shot-react-descriptionとは</h2>



<p>zero-shot-react-descriptionはReActベースのLangChainのAgentになります。ReActとは以下で提案されている手法です。</p>



<p>Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K., &amp; Cao, Y. (2022). ReAct: Synergizing Reasoning and Acting in Language Models.&nbsp;<em>ArXiv, abs/2210.03629</em>.</p>



<p>ReActがやっていることを簡単に説明すると以下の二つの行動を繰り返していき、最終的な結果を得るということをしています。</p>



<ol class="wp-block-list">
<li>次に何をすべきか？を考える</li>



<li>考えに基づいてアクションを実行し、アクションの結果を得る</li>
</ol>



<p>ここでアクションというのは<code>initialize_agent</code>で指定したtoolになります。先ほどのコードでは<code>serpapi</code>、 <code>llm-math</code>です。<code>serpapi</code>は<a href="https://serpapi.com/" target="_blank" rel="noreferrer noopener">SerpApi</a>というGoolgeの検索結果をパースして返してくれるサービスを実行するツール、<code>llm-math</code> はLLMを使ってPythonコードを生成して実行するツールになります。</p>



<p>zero-shot-react-descriptionではこのような動きをLLMにさせるために入力のテキストの前にいろいろ追加で文章を付け加えてLLMに投げています。</p>



<p>この追加でつけている文章がどんなものか気になったので、今回詳しくzero-shot-react-descriptionの動作を調べました。動作チェックには先ほども示した以下の質問を使いました。</p>



<pre class="wp-block-preformatted">"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"</pre>



<h2 class="wp-block-heading">動作チェックをするための下準備</h2>



<p>頑張ってPythonのデバッガーを使って1行ごとに何が起きているか？を見てもいいのですが、実はLangChainは以下のようにすると、それ以降の実行に関して細かい出力をするようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="langchain_verbose" data-lang="Python"><code>import langchain
langchain.verbose = True</code></pre></div>



<p>今回は上の設定によって出てきたログに基づいて動作を説明していきます。</p>



<h2 class="wp-block-heading">zero-shot-react-descriptionの動作例</h2>



<p>先ほど示した質問に対してzero-shot-react-descriptionはまとめると、この記事を書いている時点では以下の手順で問題に対する回答をしようとします。</p>



<ol class="wp-block-list">
<li>「Leo DiCaprio&#8217;s girlfriend」が誰なのか調べる</li>



<li>「Leo DiCaprio&#8217;s girlfriend」が「Camila Morrone」であることがわかったので、次は「Camila Morrone」の年齢を調べる。</li>



<li>25歳であることがわかったので、次は25^0.43を計算する</li>



<li>最終的な結果を出力する</li>
</ol>



<p>ちなみに実行したタイミングによっては1を調べたらついでに年齢もわかってしまって2がスキップされるという挙動をするタイミングもありました。このため、上の例とは違う動作をするケースもありますので注意してください。</p>



<p>それではLangChainで細かい出力をさせてそれぞれのステップでLLMをどのように動作させているか？を細かく見ていきます。</p>



<h3 class="wp-block-heading">最初の質問時点の入力に関して</h3>



<p>まず、そもそも最初の問のときにどのような入力になっているかを見てみます。入力では先ほど示したように以下のものを入れています。</p>



<pre class="wp-block-preformatted">"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"</pre>



<p>しかし、これだけだとReAct的な動作をしてくれないので、ReAct的な動作をしてくれるように質問の前にいろいろ追加します。実はLLMに投げている文章としては以下のものになっています。</p>



<pre class="wp-block-preformatted">Answer the following questions as best you can. You have access to the following tools:

Search: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Calculator: Useful for when you need to answer questions about math.

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search, Calculator]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?
Thought:
</pre>



<p>「Question: 」のところに入力した質問があって、その前後にいろいろついていることがわかります。</p>



<p>これに関して順番に見ていきます。まず以下の部分です。</p>



<pre class="wp-block-preformatted">Answer the following questions as best you can. You have access to the following tools:

Search: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Calculator: Useful for when you need to answer questions about math.</pre>



<p>最初に、質問にできるだけこたえるように頼み、使えるツールとしてどんなものがあるかを説明しています。</p>



<p>それぞれSearchが<code>serpapi</code>, Calculatorが<code>llm-math</code> のことを言っています。このツールの説明の部分は<code>initialize_agent</code> で指定されたツールの<code>name</code> と<code>description</code>をから自動生成されて加えられています。このため、もし使用するツールを増やすとこの部分に新しく追加されたツールの説明が付け加わることになります。</p>



<p>次にこの部分に関してです。</p>



<pre class="wp-block-preformatted">Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search, Calculator]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question</pre>



<p>この部分はこの後、LLMが生成するテキストのフォーマットの指定に関しての説明です。これを加えることで、この後、Agentの中でLLMがこのフォーマットに従って出力してくれるようになります。そのおかげでLLMの出力を簡単にパースすることができ、LLMの出力から次にどのようなアクションをすればよいかを自動で判断し、実行することができます。</p>



<p>そして最後のこの部分です。</p>



<pre class="wp-block-preformatted">Begin!

Question: Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?
Thought:</pre>



<p>この部分はLLMにここから開始することと、質問、そして最初にLLMに何をするべきか考えてもらうために「Thought:」までテキストで与えます。「Thought:」があることでLLMはちゃんと考えることから初めてくれます。</p>



<p>この入力に加えて「Observation:」という文字列を出力したら出力を止めるようにしてLLMを実行させます。</p>



<p>「Observation:」はアクションの結果を示すところです。このため、「Observation:」より先はLLMでは生成できないので、これを出力したらLLMを止めるようにしています。</p>



<h3 class="wp-block-heading">「Leo DiCaprio&#8217;s girlfriend」が誰なのか調べる</h3>



<p>先ほどの文章をLLMに入力するとLLMは次のように出力してきます。</p>



<pre class="wp-block-preformatted">I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"</pre>



<p>1行目の「Thought:」の続きなので、LLMが何をするべきか考えたところです。そしてその次は質問に答えるために何をするべきかを出力しています。ここでは「&#8221;Leo DiCaprio girlfriend&#8221;」という入力で「Search」を実行することを選択しています。</p>



<p>この出力から&#8221;Leo DiCaprio girlfriend&#8221;を入力としてSerpApiを使います。このSerpApiは以下のURLの説明にあるような形で検索結果を返してきます。</p>



<p><a href="https://serpapi.com/organic-results">https://serpapi.com/organic-results</a></p>



<p>このJSONの一部を取り出して「Observation:」のあとに追加します。どこの部分を取り出すかは<code>SerpAPIWrapper</code> というクラスの<code>_process_response</code> という関数で決めています。私が実行した際はtopヒットの<code>snippet</code> の部分を取り出していました。書かれている内容としては以下の通りです。</p>



<pre class="wp-block-preformatted">Leonardo DiCaprio seemed to prove a long-held theory about his love life right after splitting from girlfriend Camila Morrone just months …</pre>



<p>この文章を見ると「Camila Morrone」が「Leo DiCaprio&#8217;s girlfriend」だったようですが別れているようですね。ただ、LLMはこの後、「Leo DiCaprio&#8217;s girlfriend」が「Camila Morrone」として処理を進めていきます。質問が若干曖昧なので、過去の彼女でも質問の回答としては成り立ちそうなので、OKとしてこのあとも説明していきます。</p>



<h3 class="wp-block-heading">「Leo DiCaprio&#8217;s girlfriend」が「Camila Morrone」であることがわかったので、次は「Camila Morrone」の年齢を調べる。</h3>



<p>先ほどの検索結果を合わせてLLMに以下の文章を入力して次にどうするかを考えさせます。</p>



<pre class="wp-block-preformatted">Answer the following questions as best you can. You have access to the following tools:

...

Begin!

Question: Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?
Thought: I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Leonardo DiCaprio seemed to prove a long-held theory about his love life right after splitting from girlfriend Camila Morrone just months …
Thought:</pre>



<p>前半部分は全く同じで、最後に先ほどの検索結果と「Thought:」をつけています。こうすることで検索結果を受けて次にどうするべきかをLLMに出力させています。</p>



<p>この入力を受けてLLMは以下のような出力をしてきます。</p>



<pre class="wp-block-preformatted">I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"</pre>



<p>最初の行は「Thought:」の出力です。なので、「Camila Morrone」の年齢を調べる必要があると考えています。そして「&#8221;Camila Morrone age&#8221;」を入力として「Search」を実行することを選択しています。この先は先ほどと同じようにSerpApiを利用して検索して結果を得ます。この部分の結果では以下のような内容を検索結果から抽出してきました。</p>



<pre class="wp-block-preformatted">25 years</pre>



<p>これで年齢もわかりました。</p>



<h3 class="wp-block-heading">25歳であることがわかったので、次は25^0.43を計算する</h3>



<p>先ほど、「Camila Morrone」25歳であることがわかったのでLLMに次にどうするか出力させます。これを行うために以下のような入力をいれます。</p>



<pre class="wp-block-preformatted">Answer the following questions as best you can. You have access to the following tools:

...

Thought: I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought:</pre>



<p>こちらも先ほどと同様にそれまでの文章にさらに検索結果を追加して「Thought:」をつけて次に何をするかLLMに考えさせています。この入力に対してLLMは以下の出力をしてきます。</p>



<pre class="wp-block-preformatted">I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43</pre>



<p>LLMとしては25^0.43を計算するために「Calculator」に対して「25^0.43」という入力を渡して実行するということをします。</p>



<p>Calculatorは先ほど説明した通り、<code>llm-math</code> を指しています。これはPythonコードを生成させて、生成されたPythonコードを実行して答えを得るということをしています。</p>



<p>具体的には以下のような入力をLLMに渡しています。</p>



<pre class="wp-block-preformatted">Translate a math problem into Python code that can be executed in Python 3 REPL. Use the output of running this code to answer the question.

Question: ${Question with math problem.}
```python
${Code that solves the problem and prints the solution}
```
```output
${Output of running the code}
```
Answer: ${Answer}

Begin.

Question: What is 37593 * 67?

```python
print(37593 * 67)
```
```output
2518731
```
Answer: 2518731

Question: 25^0.43</pre>



<p>これは何をしているかというとPythonコードを生成するように説明し、その後フォーマットを示しています。そして、そのあとフォーマットに従った簡単なexampleを1つ示してそれにまねてPythonコードを生成させるように指示しています。これはLLMにおけるone-shot learningをしていることになります。この結果、LLMが賢ければちゃんと以下のように出力してきます。</p>



<pre class="wp-block-preformatted"> ```python
import math
print(math.pow(25, 0.43))
```

Answer: 3.991298452658078</pre>



<p>ここでAnswerで計算結果も出力していますが、これは使わずにPythonコードの部分を取り出してPythonで実行させ結果を得ています。これでほしかった計算結果を得ることができました。</p>



<h3 class="wp-block-heading">最終的な結果を出力する</h3>



<p>さきほどの計算結果を加えた文章をLLMに入力して文章を生成させます。</p>



<p>LLMへの入力は以下の通りです。</p>



<pre class="wp-block-preformatted">Answer the following questions as best you can. You have access to the following tools:
...
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078
Thought:</pre>



<p>これに対するLLMの出力は以下の通りです。</p>



<pre class="wp-block-preformatted">I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.
</pre>



<p>ここまでで最終的な結果がわかったので「Final Answer: 」のあとに最終的な結果を出力しています。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回zero-shot-react-descriptionのログを追ってみてだいぶ何をやっているか理解することができました。</p>



<p>感想としては検索結果のチェックが若干甘い感じがしています。この結果、先ほどみたような「Leo DiCaprio&#8217;s girlfriend」として別れていそうな「Camila Morrone」をあげてくるということをしています。このあたりより精度の高い結果を得るためには、そもそも最初の質問をより明確にするか事実確認の仕組みをもう少し工夫していれる必要がありそうだなと思っています。</p>



<p>また、<code>llm-math</code> のLLMの出力したPythonコードをそのまま実行するという仕組みは若干怖いなぁということを思いました。今回のようにどのようなコードを生成されるかわかっているケースはいいのですが、誤って変なコード、例えばhome以下のファイル削除みたいなコードがでてきて実行されたら大変なことになります。このあたりはもうちょっとセキュアにコードを実行する仕組みがほしいところです。</p>



<p>ただ、LLMに入力する文章を工夫することで想像よりもはるかにすごいことができると分かったので、いい勉強になりました。</p>



<p>個人的にはかなり興味がわいてきたので、いろいろLLMの入力を工夫するやり方などを勉強していければと思っています。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/">LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2691</post-id>	</item>
	</channel>
</rss>
