<?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>pandas - まったり勉強ノート</title>
	<atom:link href="https://www.mattari-benkyo-note.com/tag/pandas/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mattari-benkyo-note.com</link>
	<description>shuの日々の勉強まとめ</description>
	<lastBuildDate>Wed, 26 Apr 2023 22:34:46 +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>LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Wed, 26 Apr 2023 22:33:14 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[pandas]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2775</guid>

					<description><![CDATA[<p>最近、LLMを使ったOSSの中身を調べてLLMとどう連携して目的を達成しているのかをいろいろ調べています。今回はLangChainのPandas Dataframe Agentの中身がどうなっているのか気になったので調べ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/">LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>最近、LLMを使ったOSSの中身を調べてLLMとどう連携して目的を達成しているのかをいろいろ調べています。今回はLangChainのPandas Dataframe Agentの中身がどうなっているのか気になったので調べたまとめになります。</p>



<p>今回のコードは以下のところにあるので、全体としてどうなっているのか見たい方はこちらをご覧ください。</p>



<p><a href="https://github.com/shu65/langchain_examples/blob/main/LangChain_Pandas_Dataframe_Agent.ipynb">https://github.com/shu65/langchain_examples/blob/main/LangChain_Pandas_Dataframe_Agent.ipynb</a></p>



<h2 class="wp-block-heading">LangChainのPandas Dataframe Agentとは</h2>



<p>LLMを使いやすくwrapしてくれるLangChainにはいくつかAgentというLLMとToolと呼ばれるものを組み合わせて実行する仕組みが用意されています。この中でもPandas Dataframe Agentは名前の通りpandasのDataframeに対する操作をLLMにやらせるための仕組みです。</p>



<p>どういうことができるかはこちらのnotebookをご覧ください。</p>



<p><a href="https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html">https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html</a></p>



<p>この記事では、上のnotebookの実行例の一つを取り上げてどのようにLLMなどと連携しているのかを説明していきたいと思います。</p>



<h2 class="wp-block-heading">実行例</h2>



<p>今回は機械学習でお馴染みのタイタニックのデータを使います。データはここから持ってきました。</p>



<p><a href="https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/problem12.html">https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/problem12.html</a></p>



<p>どういうデータか詳しく知りたい方は上のページの説明をご覧ください。</p>



<p>また、今回は以下のことをLLMに聞いたときのLLMなどを含めた一連の流れがどうなっているのかを説明していきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>
from langchain.llms import OpenAI
from langchain.agents import create_pandas_dataframe_agent
import pandas as pd

df = pd.read_csv(&#39;titanic.csv&#39;)
agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True)
agent.run(&quot;whats the square root of the average age?&quot;)</code></pre></div>



<p>最後の行がLLMでpandasのDataFrameを操作する部分になっています。やらせたいことは読んで分かる通り、年齢の平均を取って、それのルートを取るという計算をした結果を得るということです。</p>



<p>それではこの後これがどのように実行されるかを見ていきます。</p>



<h2 class="wp-block-heading">実行の流れ</h2>



<p>Pandas Dataframe Agentの大まかな実行の流れは以下の通りです。</p>



<ol class="wp-block-list">
<li><code>zero-shot-react-description</code> と同じAgentクラスに対し、promptを少し変えたAgentを作成</li>



<li>できたAgentがどのようなコードを実行するかを考える</li>



<li>考えに従ってコードを生成</li>



<li>生成されたコードを実行</li>



<li>実行した結果に基づいて再度考える。以降はこの繰り返して最終結果を得る</li>
</ol>



<p>このような「考える」と「行動」（LangChain的にはTool）を交互に繰り返すやり方はReActと呼ばれる方法で、以下の論文で提案されています。</p>



<p><span style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">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;</span><em style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">ArXiv, abs/2210.03629</em><span style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">.</span></p>



<p><code>zero-shot-react-description</code> に関しては以前記事を書きましたので、動作について詳しく知りたい方はこちらも併せてご覧ください。</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="dYRayzlMPQ"><a href="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/">LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/embed/#?secret=1tgUKm6Vhz#?secret=dYRayzlMPQ" data-secret="dYRayzlMPQ" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>ここからはさきほどの例の場合、LLMと連携してどのような手順で処理をしていくかを見ていきます。</p>



<h3 class="wp-block-heading">一番最初のpromptに関して</h3>



<p>一番最初のpromptは以下のようになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You are working with a pandas dataframe in Python. The name of the dataframe is `df`.
You should use the tools below to answer the question posed of you:

python_repl_ast: A Python shell. Use this to execute python commands. Input should be a valid python command. When using this tool, sometimes output is abbreviated - make sure it does not look abbreviated before using it in your answer.

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 [python_repl_ast]
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


This is the result of `print(df.head())`:
   Survived  Pclass                                               Name  \
0         0       3                             Mr. Owen Harris Braund   
1         1       1  Mrs. John Bradley (Florence Briggs Thayer) Cum...   
2         1       3                              Miss. Laina Heikkinen   
3         1       1        Mrs. Jacques Heath (Lily May Peel) Futrelle   
4         0       3                            Mr. William Henry Allen   

      Sex   Age  Siblings/Spouses Aboard  Parents/Children Aboard     Fare  
0    male  22.0                        1                        0   7.2500  
1  female  38.0                        1                        0  71.2833  
2  female  26.0                        0                        0   7.9250  
3  female  35.0                        1                        0  53.1000  
4    male  35.0                        0                        0   8.0500  

Begin!
Question: whats the square root of the average age?</code></pre></div>



<p>一番最初のpromptが一番大事な部分なので、丁寧に説明していきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You are working with a pandas dataframe in Python. The name of the dataframe is `df`.</code></pre></div>



<p>この部分は<code>zero-shot-react-description</code> とは違う部分の一つです。最初にpandasの<code>DataFrame</code>を使うことと、その変数名が<code>df</code>であることをLLMに伝えます。</p>



<p>次にこの部分についてです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You should use the tools below to answer the question posed of you:

python_repl_ast: A Python shell. Use this to execute python commands. Input should be a valid python command. When using this tool, sometimes output is abbreviated - make sure it does not look abbreviated before using it in your answer.
</code></pre></div>



<p>この部分はToolの説明です。Pandas Dataframe Agentの場合は<code>python_repl_ast</code>を使うため、このToolがどういうものかをLLMに伝えています。</p>



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



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>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 [python_repl_ast]
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</code></pre></div>



<p>この部分は<code>zero-shot-react-description</code>と同じでLLMにReAct的な動きをしてもらうための説明のところです。</p>



<p>そして次はこの部分です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>This is the result of `print(df.head())`:
   Survived  Pclass                                               Name  \
0         0       3                             Mr. Owen Harris Braund   
1         1       1  Mrs. John Bradley (Florence Briggs Thayer) Cum...   
2         1       3                              Miss. Laina Heikkinen   
3         1       1        Mrs. Jacques Heath (Lily May Peel) Futrelle   
4         0       3                            Mr. William Henry Allen   

      Sex   Age  Siblings/Spouses Aboard  Parents/Children Aboard     Fare  
0    male  22.0                        1                        0   7.2500  
1  female  38.0                        1                        0  71.2833  
2  female  26.0                        0                        0   7.9250  
3  female  35.0                        1                        0  53.1000  
4    male  35.0                        0                        0   8.0500  </code></pre></div>



<p>ここではDataFrameの一部を出力させてどういうデータであるかをLLMに伝えている部分です。</p>



<p>最後にこの部分です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Begin!
Question: whats the square root of the average age?
Thought: </code></pre></div>



<p>動作の開始の合図と、「Question:」から先が実際にAgentを使ってやりたいことをLLMに伝えます。そして、「Thought:」までLLMに入力させて、LLMに何をするべきか考えさせます。</p>



<p>ここから先はLLMの出力と出力されたPythonコードを実行して得られた結果を受け取ってさらにLLMに考えさせるという動作を繰り返していきます。これを順番に説明していきます。</p>



<h3 class="wp-block-heading">LLMが考えて、Pythonのコードを生成する部分(1回目)</h3>



<p>先ほどのpromptをLLMに入力すると以下のような出力が返ってきます。これを順番に見ていきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>I need to calculate the average age first
Action: python_repl_ast
Action Input: df[&#39;Age&#39;].mean()</code></pre></div>



<p>1行目が先ほどの「Thought:」の続きで、LLMがどのようなことをするべきか考えた部分です。最初は年齢の平均を計算しようと考えて、それを行うためのコードを「Action Input:」から先に出力しています。</p>



<p>このコードを今度は実際に実行します。</p>



<h3 class="wp-block-heading">Pythonコードの実行</h3>



<p>先ほどのPythonのコードをどのように実行するかを説明していきます。実際に実行している部分は、この記事を書いている現在のバージョンではLangChainのここになります。</p>



<p><a href="https://github.com/hwchase17/langchain/blob/72b7d76d79b0e187426787616d96257b64292119/langchain/tools/python/tool.py#L67-L92">https://github.com/hwchase17/langchain/blob/72b7d76d79b0e187426787616d96257b64292119/langchain/tools/python/tool.py#L67-L92</a></p>



<p>これは以下のような手順でPythonコードを実行しています。</p>



<ol class="wp-block-list">
<li>LLMの生成したPythonコードを受け取りきれいに整える</li>



<li>Pythonコードの抽象構文木を生成</li>



<li>Pythonコードの最後から一つ手前までのコードを実行</li>



<li>Pythonコードの最後の部分を実行して出力結果、もしくはエラーを得る</li>
</ol>



<p>3と4でなぜ分けて実行しているかというとToolの説明にある通り、途中の出力は省略して最後だけ得るためであると考えています。</p>



<p>このような流れでPythonコードを実行すると以下の結果が得られえます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Observation: 29.471443066516347</code></pre></div>



<p>ここから次に何をするべきかさらに考えて実行していきます。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(2回目)</h3>



<p>次にLLMの出力とPythonコードの実行は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I now need to calculate the square root of the average age
Action: python_repl_ast
Action Input: math.sqrt(df[&#39;Age&#39;].mean())
Observation: name &#39;math&#39; is not defined</code></pre></div>



<p>1行目は先ほどと同じように次に何をするべきかLLMに考えさせた結果の部分です。ここでは年齢の平均のルートを計算するということを考えてコードを生成しています。</p>



<p>このコードを実行すると以下のようなエラーが出力されます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>name &#39;math&#39; is not defined</code></pre></div>



<p>まだ<code>math</code> がインポートされてないので、その部分でエラーがでています。たしかに現状のコードではどこも<code>math</code> をインポートしてないので、このエラーがでるのは当然です。</p>



<p>ここからさらにLLMに考えさせます。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(3回目)</h3>



<p>次にLLMの出力とPythonのコードを実行した結果は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I need to import the math library
Action: python_repl_ast
Action Input: import math
Observation: </code></pre></div>



<p>1行目は先ほどと同じように次に何をするべきかLLMに考えさせた結果の部分です。今度はちゃんと<code>math</code> をインポートするように考えて、その通りのコードを生成しています。</p>



<p>このコードはインポートだけなので出力はなしです。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(4回目)</h3>



<p>ここからさらにLLMに考えさせます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I now need to calculate the square root of the average age
Action: python_repl_ast
Action Input: math.sqrt(df[&#39;Age&#39;].mean())
Observation: 5.42876073026951</code></pre></div>



<p>LLMの考えていることは1行目にでていて、これは2回目のときと同じものになっています。コードも2回目と同じです。</p>



<p>一方、先ほど<code>math</code>をインポートしたので、今度はエラーが出ずに正しい計算ができています。</p>



<p>以上がPandas Dataframe Agentの中身になります。</p>



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



<p>今回はLangChainのPandas Dataframe Agentの中身がどうなっているのかを調べたのでまとめを書きました。DataFrameの中の情報をどうやって教えているのか疑問だったのですが、その辺もわかってよかったです。</p>



<p>また、Pythonの<code>ast</code>まわりを知らなかったのでそれについてもいい勉強になりました。</p>



<p>この記事が少しでも他の方の役にたったら幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/">LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</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/27/langchain_pandas/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2775</post-id>	</item>
	</channel>
</rss>
