<?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>langchain - まったり勉強ノート</title>
	<atom:link href="https://www.mattari-benkyo-note.com/tag/langchain/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mattari-benkyo-note.com</link>
	<description>shuの日々の勉強まとめ</description>
	<lastBuildDate>Sun, 05 Jan 2025 12:02:50 +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>AIを使ったソフトウェア開発の書籍まとめ(2025/1版)</title>
		<link>https://www.mattari-benkyo-note.com/2025/01/06/ai_software_dev_book_review/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/01/06/ai_software_dev_book_review/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Sun, 05 Jan 2025 23:30:00 +0000</pubDate>
				<category><![CDATA[書評]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[vscode]]></category>
		<category><![CDATA[書籍]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3121</guid>

					<description><![CDATA[<p>あけましておめでとうございます。今年も読んだ本や勉強したことのまとめを記事にして、少しでも皆さんのお役にたてればと思っていますので、よろしくお願いいたします。 さて、新年一発目の記事はAIを使ったソフトウェア開発の本を3 [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/01/06/ai_software_dev_book_review/">AIを使ったソフトウェア開発の書籍まとめ(2025/1版)</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>あけましておめでとうございます。今年も読んだ本や勉強したことのまとめを記事にして、少しでも皆さんのお役にたてればと思っていますので、よろしくお願いいたします。</p>



<p>さて、新年一発目の記事はAIを使ったソフトウェア開発の本を3冊読んだのでまとめて紹介しようと思います。</p>



<p>2024年はAIの実応用が様々な分野で出始めてきた印象を持っています。その中でもソフトウェア開発は、使い方のノウハウや各種ツールがいろいろリリースされて、これからどんどんAIを使ってソフトウェア開発がされていくんだろうなと誰もが思っているかと思います。</p>



<p>ただ、みなさん、実際にAIを使ってソフトウェア開発をどれくらいしているでしょうか？私も昨年末までは簡単にはGitHub Copilotを仕事や趣味で簡単に使っている程度でAIを使いこなしてソフトウェア開発をしている！と自信を持っていえる状態ではありませんでした。</p>



<p>このため、年末年始の休みはいい機会ということで、AIを活用したソフトウェア開発について学べる本をいくつか読みました。今回は読んだ本のうち３冊をまとめて紹介しようと思います。</p>



<h2 class="wp-block-heading">生成AI時代の新プログラミング実践ガイド Pythonで学ぶGPTとCopilotの活用ベストプラクティス</h2>


		<div class="pochipp-box"
			data-id="3118"
			data-img="l"
			data-lyt-pc="dflt"
			data-lyt-mb="vrtcl"
			data-btn-style="dflt"
			data-btn-radius="on"
			data-sale-effect="none"
			 data-cvkey="7299040b"		>
							<div class="pochipp-box__image">
					<a href="https://www.amazon.co.jp/dp/B0CTT8QKHR?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						<img decoding="async" src="https://m.media-amazon.com/images/I/51+2RXGDUBL._SL500_.jpg" alt="" width="120" height="120" />					</a>
				</div>
						<div class="pochipp-box__body">
				<div class="pochipp-box__title">
					<a href="https://www.amazon.co.jp/dp/B0CTT8QKHR?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						生成AI時代の新プログラミング実践ガイド Pythonで学ぶGPTとCopilotの活用ベストプラクティス					</a>
				</div>

									<div class="pochipp-box__info">著:松本直樹</div>
				
				
							</div>
				<div class="pochipp-box__btns"
		data-maxclmn-pc="fit"
		data-maxclmn-mb="1"
	>
					<div class="pochipp-box__btnwrap -amazon">
								<a href="https://www.amazon.co.jp/dp/B0CTT8QKHR?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						Amazon					</span>
									</a>
			</div>
							<div class="pochipp-box__btnwrap -rakuten">
								<a href="https://hb.afl.rakuten.co.jp/hgc/39c5c75e.b3799909.39c5c75f.e5fd5e7d/?pc=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17725382%2F%3Frafcid%3Dwsc_i_is_1074984852215714305&#038;m=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17725382%2F%3Frafcid%3Dwsc_i_is_1074984852215714305" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						楽天市場					</span>
									</a>
			</div>
											</div>
								<div class="pochipp-box__logo">
					<img decoding="async" src="https://www.mattari-benkyo-note.com/wp-content/plugins/pochipp/assets/img/pochipp-logo-t1.png" alt="" width="32" height="32">
					<span>ポチップ</span>
				</div>
					</div>
	


<p>GitHub Copilot以外にもChatGPTやOpenAI API、LangChainなど、幅広いAI活用法について紹介している本で、GitHub Copilot部分に関しては実際にwebアプリケーション開発の例なんかも載っていてわりと活用イメージをすぐに持てる本です。</p>



<p>この本の特徴を簡単にまとめると以下の通りです。</p>



<ul class="wp-block-list">
<li><strong>GitHub Copilot以外の内容も充実</strong><br>ChatGPTやOpenAI API、LangChainなどの使い方も説明されていて、AI全般に関する知識を獲得できます。ただ、GitHub Copilotだけを詳しく知りたいと思っている場合は思っていたものと違うという印象をもつかもしれません。</li>



<li><strong>GitHub CopilotとChatGPTを使った開発例がいい</strong><br>例としてGitHub Copilotの簡単な機能紹介だけではなく、ChatGPTを使った要件定義から、実際にCopilotでコードを書き上げる流れまで一連のプロセスが１章分かけて分かりやすく紹介されていました。この部分は読めばすぐにでもChatGPTとGitHub Copilotを使った開発の手順がイメージできたので、個人的に非常に良かったです。</li>
</ul>



<h2 class="wp-block-heading">コード×AI ー ソフトウェア開発者のための生成AI実践入門</h2>


		<div class="pochipp-box"
			data-id="3119"
			data-img="l"
			data-lyt-pc="dflt"
			data-lyt-mb="vrtcl"
			data-btn-style="dflt"
			data-btn-radius="on"
			data-sale-effect="none"
			 data-cvkey="718a271a"		>
							<div class="pochipp-box__image">
					<a href="https://www.amazon.co.jp/dp/B0DFW57CGY?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						<img decoding="async" src="https://m.media-amazon.com/images/I/41WkhXQZRJL._SL500_.jpg" alt="" width="120" height="120" />					</a>
				</div>
						<div class="pochipp-box__body">
				<div class="pochipp-box__title">
					<a href="https://www.amazon.co.jp/dp/B0DFW57CGY?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						コード×AIーソフトウェア開発者のための生成AI実践入門					</a>
				</div>

									<div class="pochipp-box__info">著:服部 佑樹</div>
				
				
							</div>
				<div class="pochipp-box__btns"
		data-maxclmn-pc="fit"
		data-maxclmn-mb="1"
	>
					<div class="pochipp-box__btnwrap -amazon">
								<a href="https://www.amazon.co.jp/dp/B0DFW57CGY?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						Amazon					</span>
									</a>
			</div>
							<div class="pochipp-box__btnwrap -rakuten">
								<a href="https://hb.afl.rakuten.co.jp/hgc/39c5c75e.b3799909.39c5c75f.e5fd5e7d/?pc=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17974210%2F%3Frafcid%3Dwsc_i_is_1074984852215714305&#038;m=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17974210%2F%3Frafcid%3Dwsc_i_is_1074984852215714305" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						楽天市場					</span>
									</a>
			</div>
											</div>
								<div class="pochipp-box__logo">
					<img decoding="async" src="https://www.mattari-benkyo-note.com/wp-content/plugins/pochipp/assets/img/pochipp-logo-t1.png" alt="" width="32" height="32">
					<span>ポチップ</span>
				</div>
					</div>
	


<p>先ほどの本（「生成AI時代の新プログラミング実践ガイド」）が「ChatGPTとGitHub Copilotを使ってすぐに開発する手順」が分かりやすくまとまっていたのに対して、こちらの本は「AIとは何か」「ソフトウェア開発にどう活かすか」という <strong>概念的な解説</strong> が多い印象でした。</p>



<p>この本の特徴を簡単にまとめると以下の通りです。</p>



<ul class="wp-block-list">
<li><strong>特定のツールに依存しない汎用的な説明</strong><br>Promptの改善の仕方など、概念ベースの解説が多いため、すぐに知識が陳腐化してしまうリスクは少なそうです。一方で、具体的なツールの使い方に重点を置いていないため、「これを読んですぐにAI開発ができる！」という即効性はあまり感じませんでした。</li>



<li><strong>実践するには練習が必要</strong><br>提示されているPrompt例はあくまでベースであり、こういう時どうすればいいのかについての深い言及は少なめな印象でした。このため、ただ読むだけでは活かせない知識が多く、この本で得た知識を使いこなすにはしばらくいろいろ手を動かしてみる必要があると思いました。</li>
</ul>



<h2 class="wp-block-heading">AIエディタCursor完全ガイド　やりたいことを伝えるだけでできる新世代プログラミング</h2>


		<div class="pochipp-box"
			data-id="3120"
			data-img="l"
			data-lyt-pc="dflt"
			data-lyt-mb="vrtcl"
			data-btn-style="dflt"
			data-btn-radius="on"
			data-sale-effect="none"
			 data-cvkey="2ef32272"		>
							<div class="pochipp-box__image">
					<a href="https://www.amazon.co.jp/dp/B0DDSQZ58S?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						<img loading="lazy" decoding="async" src="https://m.media-amazon.com/images/I/51Chd-sJSbL._SL500_.jpg" alt="" width="120" height="120" />					</a>
				</div>
						<div class="pochipp-box__body">
				<div class="pochipp-box__title">
					<a href="https://www.amazon.co.jp/dp/B0DDSQZ58S?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						AIエディタCursor完全ガイド ―やりたいことを伝えるだけでできる新世代プログラミング―					</a>
				</div>

									<div class="pochipp-box__info">著:木下雄一朗</div>
				
				
							</div>
				<div class="pochipp-box__btns"
		data-maxclmn-pc="fit"
		data-maxclmn-mb="1"
	>
					<div class="pochipp-box__btnwrap -amazon">
								<a href="https://www.amazon.co.jp/dp/B0DDSQZ58S?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						Amazon					</span>
									</a>
			</div>
							<div class="pochipp-box__btnwrap -rakuten">
								<a href="https://hb.afl.rakuten.co.jp/hgc/39c5c75e.b3799909.39c5c75f.e5fd5e7d/?pc=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17953394%2F%3Frafcid%3Dwsc_i_is_1074984852215714305&#038;m=https%3A%2F%2Fitem.rakuten.co.jp%2Fbook%2F17953394%2F%3Frafcid%3Dwsc_i_is_1074984852215714305" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						楽天市場					</span>
									</a>
			</div>
											</div>
								<div class="pochipp-box__logo">
					<img decoding="async" src="https://www.mattari-benkyo-note.com/wp-content/plugins/pochipp/assets/img/pochipp-logo-t1.png" alt="" width="32" height="32">
					<span>ポチップ</span>
				</div>
					</div>
	


<p>普段VSCodeを使っている身として、「最近よくきくCursorって、使い心地はどうなんだろう？」と気になり手に取った一冊です。この本は初心者でも分かりやすく、実践的な使い方が豊富に紹介されているので、「こんなことまでできるのか！」を体感しながら読める内容でした。</p>



<p>この本の特徴を簡単にまとめると以下の通りです。</p>



<ul class="wp-block-list">
<li><strong>エディタとしてのCursor活用例が充実</strong><br>単純な画像変換やPDF結合など、ちょっとしたスクリプトでできそうな作業から、iOSアプリ開発にまで踏み込んだ事例が取り上げられており、やりたいことに合わせてCursorを使いこなすイメージがつかみやすかったです。</li>



<li><strong>すぐに試してみたくなる</strong><br>手順が丁寧かつ実用的なため、読みながら「すぐにでもこれを試してみたい！」と思えるものが多く、Cursorでいろいろ試しながら読み進めていました。</li>
</ul>



<h2 class="wp-block-heading">こういう人にお勧め</h2>



<p>今回読んだ3冊は、意図せず全然違う３冊でした。それぞれどういう人にお勧めかを簡単にまとめると</p>



<ol class="wp-block-list">
<li><strong>すぐに開発に導入してみたいなら</strong><br>「<a href="https://amzn.to/3PlsXFI" target="_blank" rel="noopener" title="生成AI時代の新プログラミング実践ガイド">生成AI時代の新プログラミング実践ガイド</a>」が、ChatGPTとGitHub Copilotを連携させてコード生成まで行う流れを具体的に解説してくれるので、実践的な入門書として最適に感じました。</li>



<li><strong>概念から学びたいなら</strong><br>「<a href="https://amzn.to/40vW7sl" target="_blank" rel="noopener" title="コード×AI ー ソフトウェア開発者のための生成AI実践入門">コード×AI ー ソフトウェア開発者のための生成AI実践入門</a>」は、AI全般の仕組みやPromptの考え方など基礎がしっかり学べます。ただし、即戦力というよりは理解を深めるための本といった印象です。</li>



<li><strong>新しいAIエディタを試してみたいなら</strong><br>「<a href="https://amzn.to/41WHCic" target="_blank" rel="noopener" title="AIエディタCursor完全ガイド">AIエディタCursor完全ガイド</a>」は、Cursorというエディタの便利機能を豊富な事例とともに紹介してくれるので、今までVSCodeなどを使っていた方にも新鮮な発見がありそうです。</li>
</ol>



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



<p>それぞれの本を読んだことで、AIを開発に取り入れる際のイメージが具体的になりました。ツールやフレームワークの選択肢は多く、一長一短がありますが、まずは自分が取り組んでいるプロジェクトや学習スタイルに合ったものを試してみるのが大切だと思いました。これからもAIを活用したソフトウェア開発の動向や事例を追いかけつつ、積極的に活用していきたいと考えています。</p>



<p>またこれまでもいろいろ本の紹介記事を書いていますので、他にも興味がある本がありましたら是非読んで見てください。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/01/06/ai_software_dev_book_review/">AIを使ったソフトウェア開発の書籍まとめ(2025/1版)</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/01/06/ai_software_dev_book_review/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3121</post-id>	</item>
		<item>
		<title>Hugging FaceのモデルをLangChainで使う方法を調べた</title>
		<link>https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 18 May 2023 23:21:03 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2813</guid>

					<description><![CDATA[<p>今回はLangChainの小ネタの記事でHugging FaceのモデルをLangChainで扱う方法について調べたので、その記事になります。 LangChainについてご存じないという方のために一言で説明するとLang [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/">Hugging FaceのモデルをLangChainで使う方法を調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>今回はLangChainの小ネタの記事で<a href="https://huggingface.co/" target="_blank" rel="noreferrer noopener">Hugging Face</a>のモデルをLangChainで扱う方法について調べたので、その記事になります。</p>



<p>LangChainについてご存じないという方のために一言で説明するとLangChainはChatGPTの内部で使われているLLMを扱いやすい形でwarpしたライブラリになります。紹介記事を以前書きましたので、詳しく知りたい方はこちらをご覧ください。</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="c4u4q0hVUK"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" 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=LBSjXcLMLo#?secret=c4u4q0hVUK" data-secret="c4u4q0hVUK" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>LangChainのexampleを見ると多くの場合OpenAIのAPIを使うことが多いように感じます。ただ、OpenAIのモデルは精度が良いのですが、一方で長文の生成をしようとするとかなりの額のお金が必要になります。このため、遊びで使うには勇気がいるケースがあります。</p>



<p>このため、懐に優しい形でLangChainを扱えないか？ということで、有名どころのモデルが大体おいてあるHugging Faceを利用してLangChainで使う方法を調べました。</p>



<p>調べるにあたって作ったコードはここに置いてあります。コード全体が見たいかたはこちらをご覧ください。</p>



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



<h2 class="wp-block-heading">Hugging Faceとは？</h2>



<p>ここ最近、<a href="https://huggingface.co/" target="_blank" rel="noreferrer noopener">Hugging Face</a>は良く目にしますが、念のため説明しておきます。Hugging Faceは様々な機械学習のライブラリを開発している企業で、モデルやデータセットなどを共有するプラットフォームも提供しています。</p>



<p>たとえば、こちらの紹介記事を書いたTransformersはHugging Faceが作っているものになります。</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="wV1K3KSKCs"><a href="https://www.mattari-benkyo-note.com/2023/05/08/transformers_book_review/">[書評] 機械学習エンジニアのためのTransformers ー 自然言語のTransformerについてより知りたい人向けな一冊</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;[書評] 機械学習エンジニアのためのTransformers ー 自然言語のTransformerについてより知りたい人向けな一冊&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/05/08/transformers_book_review/embed/#?secret=QtlvaACq8c#?secret=wV1K3KSKCs" data-secret="wV1K3KSKCs" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>ここ最近の公開されている有名どころのモデルは大体Hugging Faceからダウンロードできるようになっているので、既存のモデルを試したいというときは非常に便利です。</p>



<p>今回はHugging Faceが運営しているプラットフォームにおいてあるモデルをLangChainで使う方法について説明します。</p>



<h2 class="wp-block-heading">Hugging FaceにおいてあるモデルをLangChainで使う</h2>



<p>Hugging FaceのモデルをLangChainで使う方法としていくつか用意されています。今回はこの中の以下の二つについて紹介します。</p>



<ol class="wp-block-list">
<li>Hugging Face APIを利用する方法</li>



<li>Hugging Faceからモデルをダウンロードしてきて手元の計算機でLLMを動かす方法</li>
</ol>



<p>それぞれ順番に説明していきます。</p>



<h3 class="wp-block-heading">Hugging Face APIを利用する方法</h3>



<p>Hugging Face上においてあるモデルは制約はありますが、API経由で利用することができます。</p>



<p>APIのトークンの取得に関しては公式のチュートリアルを参考にしてください。</p>



<p><a href="https://huggingface.co/docs/api-inference/quicktour">https://huggingface.co/docs/api-inference/quicktour</a></p>



<p>LangChainで利用する場合は<code>HUGGINGFACEHUB_API_TOKEN</code>という環境変数に上で取得したトークンを入れておく必要があります。</p>



<p>今回のコードではnotebookを公開する都合上、トークンの中身がコードにでてこないように<code>dotenv</code> を利用して環境変数の設定をしています。手元で動かす際は以下のようにすれば十分です</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-file="set_hugging_face_api.sh" data-lang="Bash"><code>export HUGGINGFACEHUB_API_TOKEN=XXXX</code></pre></div>



<p>あとは以下のようにHugging Face APIを利用したLLMのインスタンスを用意します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="hugging_face_hub.py" data-lang="Python"><code>from langchain import HuggingFaceHub

repo_id = &quot;google/flan-t5-xl&quot; 

llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={&quot;temperature&quot;:0, &quot;max_length&quot;:64})</code></pre></div>



<p>ここではモデルとして<a href="https://huggingface.co/google/flan-t5-xl" target="_blank" rel="noopener" title="GoogleのFlan-T5のXL">GoogleのFlan-T5のXL</a>というサイズのモデルを利用しています。<code>model_kwargs</code> はモデルごとに指定できるものが違うので注意してください。ここでは<code>temperature</code> と <code>max_length</code> を指定しています。</p>



<p>LLMが用意できればあとはOpenAIのモデルのときと同じ感覚で利用することができます。ここでは簡単にLangChainを使って以下のように質問して答えてもらいます</p>



<pre class="wp-block-preformatted"><code>Who won the FIFA World Cup in the year 1994? </code></pre>



<p>コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="run_hugging_face_api_llm" data-lang="Python"><code>template = &quot;&quot;&quot;Question: {question}

Answer: Let&#39;s think step by step.&quot;&quot;&quot;
prompt = PromptTemplate(template=template, input_variables=[&quot;question&quot;])
llm_chain = LLMChain(prompt=prompt, llm=llm)

question = &quot;Who won the FIFA World Cup in the year 1994? &quot;

llm_chain.run(question)</code></pre></div>



<p>このコードは以下のように出力されました。</p>



<pre class="wp-block-preformatted">The FIFA World Cup is a football tournament that is played every 4 years. The year 1994 was the 44th FIFA World Cup. The final answer: Brazil.</pre>



<p>調べてみると1994年は確かにブラジルが優勝しているので正しい回答が得られているようです。</p>



<h3 class="wp-block-heading">Hugging Faceからモデルをダウンロードしてきて手元の計算機でLLMを動かす方法</h3>



<p>次にHugging Faceのモデルを手元にダウンロードしてきてLangChainで利用する方法を説明していきます。</p>



<p>まず、LLMの準備ですが以下のようにします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="hugging_face_local" data-lang="Python"><code>from langchain.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_id = &quot;gpt2&quot;
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline(
    &quot;text-generation&quot;, model=model, tokenizer=tokenizer, max_new_tokens=64
)
llm = HuggingFacePipeline(pipeline=pipe)</code></pre></div>



<p>Google Colabで動かす都合上、小さめのモデルということでここでは<a href="https://huggingface.co/gpt2" target="_blank" rel="noopener" title="GPT-2">GPT-2</a>を利用しています。</p>



<p>基本的な使い方としては良くあるHugging Faceの使い方である <code>AutoTokenizer</code> と <code>AutoModelForCausalLM</code> を利用してtokenizerとmodelを用意します。その後LangChainが用意している <code>HuggingFacePipeline</code> を使ってLangChainで使えるLLMのインスタンスを作ります。</p>



<p>あとは先ほどと同様にすればLangChainでHugging Faceのモデルを利用することができます。コードはAPIのときと同じため省略します。またGPT-2ということもあり、結果はめちゃくちゃなので、出力結果も省略します。</p>



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



<p>今回はLangChainでHugging Faceのモデルを利用する方法について調べたのでそのまとめを書きました。</p>



<p>LangChainのほうで思った以上に簡単に使えるように整備されている印象で、どの関数を使えばわかっていればすぐに使うことはできました。今回は紹介しませんでしたが他にもHugging Faceのモデルを動かす方法は用意されているようなので興味のある方は調べてみてください。</p>



<p>この記事が他の方の参考になれば幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/">Hugging FaceのモデルをLangChainで使う方法を調べた</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/05/19/langchain_hugging_face/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2813</post-id>	</item>
		<item>
		<title>LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</title>
		<link>https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 11 May 2023 22:32:51 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2797</guid>

					<description><![CDATA[<p>最近、LangChainの以下の公式blog記事で「Contextual Compression」という機能が紹介されていました。 https://blog.langchain.dev/improving-documen [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/">LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>最近、LangChainの以下の公式blog記事で「Contextual Compression」という機能が紹介されていました。</p>



<p><a href="https://blog.langchain.dev/improving-document-retrieval-with-contextual-compression/">https://blog.langchain.dev/improving-document-retrieval-with-contextual-compression/</a></p>



<p>ちょうどこういう機能があったらいいなぁと思っていたところだったので、この機能について調べてみました。今回はそのまとめ記事になります。</p>



<p>今回の記事を書くにあたり、動作チェックをした際のnotebookはここにあげておきました。コードを見たい方はこちらをご覧ください。</p>



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



<p>また、LangChainがどういうものかご存じない方は以前LangChainの紹介記事を書きましたので、こちらをご覧ください。</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="T0i4X7Rnjk"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" 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=W0uyXVOi3m#?secret=T0i4X7Rnjk" data-secret="T0i4X7Rnjk" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h2 class="wp-block-heading">Contextual Compressionとは？</h2>



<p>LLMを使ったQAシステムでは関連するドキュメントを見つけてきて、質問と関連ドキュメントをLLMに入れて質問に答えるという形のものがあります。この際、以下のような問題点があります。</p>



<ol class="wp-block-list">
<li>質問と関連してないドキュメントが含まれるケースがある</li>



<li>関連ドキュメントの文字数が多いとLLMに入力できる文字数を圧迫する</li>
</ol>



<p>この問題を解決する方法の手段の一つとしてこの「Contextual Compression」があります。</p>



<p>このContextual Compressionでは関連ドキュメントを見つけたあと、質問により関連している情報だけを抽出します。この抽出された情報と質問をLLMに入れてより的確な質問に答えられるようにするというものです。</p>



<p>LangChainではContextual Compressionの機能としていくつか用意されています。その中でもぱっと見て動作が分かりずらいLLMを使ったものに関して今回はどういうpromptになっているのかを調べたので順番に紹介していきます。</p>



<h3 class="wp-block-heading">LLMChainExtractor</h3>



<p>まず一つ目が「LLMChainExtractor」です。これは関連するドキュメントを見つけたあとLLMによって質問に関連する部分だけを抽出するものになっています。</p>



<p>LLMChainExtractorを使う前の以下のコードは以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="baseline.py" data-lang="Python"><code>from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS

documents = TextLoader(&#39;./state_of_the_union.txt&#39;).load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever()

docs = retriever.get_relevant_documents(&quot;What did the president say about Ketanji Brown Jackson&quot;)</code></pre></div>



<p>このコードの出力は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. 

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
----------------------------------------------------------------------------------------------------
Document 2:

A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. 

And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. 

We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.  

We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.  

We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. 

We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.
----------------------------------------------------------------------------------------------------
Document 3:

And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. 

As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. 

While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. 

And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. 

So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together.  

First, beat the opioid epidemic.
----------------------------------------------------------------------------------------------------
Document 4:

Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. 

And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up.  

That ends on my watch. 

Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. 

We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. 

Let’s pass the Paycheck Fairness Act and paid leave.  

Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. 

Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.</code></pre></div>



<p>それでは次にLLMChainExtractorを使った場合の結果を見てみます。コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainExtractor" data-lang="Python"><code>from langchain.llms import OpenAI
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor

llm = OpenAI(temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents(&quot;What did the president say about Ketanji Jackson Brown&quot;)</code></pre></div>



<p>compressed_docsの中身を見てみると以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

&quot;One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.&quot;
----------------------------------------------------------------------------------------------------
Document 2:

&quot;A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.&quot;</code></pre></div>



<p>先ほど変わってドキュメント数が減っているのと、Document 1のほうを見ると出力されている内容もたしかに関連したところだけ残っている感じがしています。この時、どのようなpromtpでLLMを実行されていたかというと、以下のようなテンプレートを使ってpromptを作ってLLMに入力していました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainExtractor_template" data-lang="Python"><code>&quot;&quot;&quot;Given the following question and context, extract any part of the context *AS IS* that is relevant to answer the question. If none of the context is relevant return {no_output_str}. 

Remember, *DO NOT* edit the extracted parts of the context.

&gt; Question: {{question}}
&gt; Context:
&gt;&gt;&gt;
{{context}}
&gt;&gt;&gt;
Extracted relevant parts:&quot;&quot;&quot;</code></pre></div>



<p>{{question}}と{{context}}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。</p>



<p>templateを見ると、関連ドキュメントの中から質問に回答と関連すると思われるところを抜き出してくるというものになっています。また、関連していなければ{no_output_str}、実際にはNO_OUTPUTという文字列を返すようになっています。</p>



<p>これにより、見つけてきたドキュメントが関係ないものであればはじくということができるようになっています。</p>



<h3 class="wp-block-heading">LLMChainFilter</h3>



<p>次に「LLMChainFilter」です。これは先ほどの「LLMChainExtractor」と同じようにLLMを使うものになっていますが、見つけたドキュメントが質問に関連するものかどうかだけを判断し、関連しないものであればはじくということだけをするものになっています。つまり、「LLMChainExtractor」であった質問に関連する部分を抽出するという処理がなくなったバージョンという感じかと思います。</p>



<p>LLMChainFilterを利用するコードは以下のようになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainFilter" data-lang="Python"><code>from langchain.retrievers.document_compressors import LLMChainFilter

_filter = LLMChainFilter.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents(&quot;What did the president say about Ketanji Jackson Brown&quot;)</code></pre></div>



<p>このコードの出力結果は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. 

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.</code></pre></div>



<p>オリジナルのコードでは4つ関連ドキュメントがでていましたが、今回は一つだけになっています。</p>



<p>これを実現するためにLLMChainFilterはLLMには以下のようなテンプレートのpromptをLLMに入力しています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>&quot;&quot;&quot;Given the following question and context, return YES if the context is relevant to the question and NO if it isn&#39;t.

&gt; Question: {question}
&gt; Context:
&gt;&gt;&gt;
{context}
&gt;&gt;&gt;
&gt; Relevant (YES / NO):&quot;&quot;&quot;</code></pre></div>



<p>{question}と{context}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。</p>



<p>テンプレートを見ればわかる通り、質問と関連するドキュメントかどうかを聞き、YESかNOを返すようにLLMにお願いするpromptになっていることがわかります。</p>



<h3 class="wp-block-heading">それ以外のContextual Compressionの機能</h3>



<p>今回はLLMを利用しているContextual Compressionのみに注目して紹介しましたが、これ以外にも以下のようなものがあります。</p>



<ol class="wp-block-list">
<li>EmbeddingsFilter: Embeddingによって質問と関連するドキュメントかどうかを判断してフィルタリングするもの。LLMを利用しないので、高速に動作する</li>



<li>DocumentCompressorPipeline: 複数の前処理との組み合わせることができるContextual Compressionの仕組み</li>
</ol>



<p>実際にこれらを使った例は公式のこちらのnotebookにありますので気になる方はご覧ください。</p>



<p><a href="https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html">https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html</a></p>



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



<p>今回はContextual Compressionについて調べたのでまとめを書きました。LangChainを使った例としてQAシステムはよく見るのですが、自分でやってみると関連ドキュメントを見つけてくるドキュメントが微妙ということがよくあるので、このような仕組みがあったらいいな、と思っていました。このため、今回は個人的には非常に勉強になりました。</p>



<p>今後もまたLLMをどう扱えばいいのか？の勉強でいろいろ調べたらまとめようと思います。</p>



<p>この記事が皆様のお役に立てれば幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/">LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</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/05/12/langchain_contextual_compression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2797</post-id>	</item>
		<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 loading="lazy" 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>
		<item>
		<title>LangChainのSummarizationについて調べたまとめ</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 20 Apr 2023 23:24:00 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2726</guid>

					<description><![CDATA[<p>LangChainの中身がどうなっているのか気になっている今日このごろ。 今回はLangChainのテキストをまとめるSummarizationまわりについて調べたのでそのまとめになります。 LangChainって何？っ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/">LangChainのSummarizationについて調べたまとめ</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>LangChainの中身がどうなっているのか気になっている今日このごろ。</p>



<p>今回はLangChainのテキストをまとめるSummarizationまわりについて調べたのでそのまとめになります。</p>



<p>LangChainって何？ってなった方はこちらに紹介の記事がありますので、ご覧ください。</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="LNqbkauJIX"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" 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=nS1shevUZc#?secret=LNqbkauJIX" data-secret="LNqbkauJIX" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h2 class="wp-block-heading">LangChainのSummarizationとは？</h2>



<p>LangChainのSummarizationとは与えられたテキストデータから要約されたテキストを作る機能になります。</p>



<p>LangChainにはChatGPTのようなサンプル以外にも様々な例が紹介されています。その中の一つがSummarizationです。</p>



<p>Summarizationは他の機能よりも説明が少なく、また、少し長い論文の要約をさせようとすると動かないことがあるので、どのような処理をさせているのか？を理解したくて調査しました。</p>



<p>ちなみに参考にしたのはこのnotebookです。</p>



<p><a href="https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html">https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html</a></p>



<p>ここから基本的には要約したい<code>Document</code>のリストを引数にとる<code>load_summarize_chain()</code>を使って実行した場合の例について説明していきます。</p>



<h2 class="wp-block-heading">load_summarize_chainによるSummarizationの３つの方法</h2>



<p>load_summarize_chain()Summarizationとして以下の３つがあります。</p>



<ol class="wp-block-list">
<li><code>stuff</code> </li>



<li><code>map_reduce</code></li>



<li><code>refine</code>&nbsp;</li>
</ol>



<p>それぞれについて説明していきます。</p>



<h3 class="wp-block-heading">stuff</h3>



<p>おそらくSummarizationという機能から一番最初に想像するのがこれです。与えられた<code>Document</code>のリストを受け取って、すべてつなげた一つのテキストにします。それをLLMに投げて要約させます。defaultのPromptのテンプレートとしては以下のようなものになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="stuff_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>ここで、{text}のところに１つにつなげたテキストに置き換えてLLMに入力します。LLMはCONCISE SUMMARY:の続きを生成するので、{text}の部分に基づいて要約した文章を生成することになります。</p>



<p><code>CONCISE SUMMARY:</code> から先はLLMに生成させるようにすることで要約をえることができるようになっています。</p>



<p>ただ、これの問題点としては与えrる<code>Document</code>のリストの合計のテキストの長さが長すぎるとLLMのコンテキストサイズを超えて実行できないケースが発生するので注意してください。</p>



<h3 class="wp-block-heading">map_reduce</h3>



<p>次に<code>map_reduce</code> に関してです。名前の通りで、リストで与えられた<code>Document</code>を一度要約し、その要約されたものを組み合わせてさらに要約するというのを繰り返し行い、最終的な要約を得るものになります。</p>



<p>最初の要約の部分とその後の要約されたものからさらに要約をする部分の２種類のステップがありますが、どちらもデフォルトでは以下のpromptのテンプレートを使います。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="map_reduce_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>いろいろ試しましたが、特に論文のような長い文章の場合はこれが一番まともな要約をしてくれる印象でした。</p>



<h3 class="wp-block-heading">refine</h3>



<p>最後に<code>refine</code> です。これも名前の通りですが、与えられた<code>Document</code>のリストの最初の要約を作り、そのごその要約と次の<code>Document</code>の要約を作ります。これを繰り返して最終的な要約を得ます。</p>



<p>これは二種類のプロンプトを使い分けて実行されます。まず最初の要約を作る部分は今までと同じように以下のプロンプトが使われます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="refine_init_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>そして、それまでの要約と新しい<code>Document</code>を組み合わせて新しい要約を作る部分のプロンプトは以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="refine_prompt_template" data-lang="Python"><code>    &quot;Your job is to produce a final summary\n&quot;
    &quot;We have provided an existing summary up to a certain point: {existing_answer}\n&quot;
    &quot;We have the opportunity to refine the existing summary&quot;
    &quot;(only if needed) with some more context below.\n&quot;
    &quot;------------\n&quot;
    &quot;{text}\n&quot;
    &quot;------------\n&quot;
    &quot;Given the new context, refine the original summary&quot;
    &quot;If the context isn&#39;t useful, return the original summary.&quot;</code></pre></div>



<p><code>refine</code> を使ってみた感想としては最後のほうの<code>Document</code>に影響されて、それほど情報量のないにも関わらず、最後のほうの<code>Document</code>の内容が要約に含まれていました。このため、要約の品質としては<code>map_reduce</code> のほうがよいかもしれないと思っています。</p>



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



<p>今回はLangChainのSummarizationについて調べたのでまとめを書きました。</p>



<p>長い文章の要約に使えないか？と思って調べたのですが、実際にやってみると期待したほどすごい要約がでてくるという感じではない印象です。</p>



<p>このため、個人的には使いどころが悩ましいなぁというと思っています。</p>



<p>ただ、いろいろ工夫すればいいものができそうな気もするので、少し文章の要約というかまとめは工夫できないかチャレンジしようと思います。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/">LangChainのSummarizationについて調べたまとめ</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/21/langchain_summarization/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2726</post-id>	</item>
		<item>
		<title>LLMを使って論文のMindmapを作りたい ver.1</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/19/llm_mindmap/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/19/llm_mindmap/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Tue, 18 Apr 2023 21:38:41 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[mindmap]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2733</guid>

					<description><![CDATA[<p>今回は最近やっているLLMを使って論文からMindmapを作る取り組みについて紹介したいと思います。まだ試作段階で一部うまくいって、一部うまくいってないという感じですが、参考になる人もいるかもしれないと思ったので記事にま [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/19/llm_mindmap/">LLMを使って論文のMindmapを作りたい ver.1</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>今回は最近やっているLLMを使って論文からMindmapを作る取り組みについて紹介したいと思います。まだ試作段階で一部うまくいって、一部うまくいってないという感じですが、参考になる人もいるかもしれないと思ったので記事にまとめました。</p>



<p>今回のコードは以下のところに置いてあります。コードが気になる方はこちらをご覧ください</p>



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



<h2 class="wp-block-heading">Mindmapとは？</h2>



<p>Mindmapとしてはmain topicからアイディアや思考を分岐させて可視化する手法になります。様々な場所で利用されている方法で、私もちゃんと理解した本の場合は、読んだまとめをMindmapにするということをよくやります。</p>



<p>そんなMindmapですが、文章の内容を理解するのに結構役立つと思っていて、もしかしたら論文のMindmapをLLMに作ってもらってそれを読めば、論文の理解スピードがあがるのではということを思っています。今回はこの仮説を確かめてみる一環で、LLMでMindmapを作らせてみよう！ということでやってみました。</p>



<h2 class="wp-block-heading">LLMからMindmapを作る取り組み</h2>



<p>LLMでMindmapを作る例はいくつかあります。今回はその中でもこれを参考にしました。</p>



<p><a href="https://xmind.app/blog/chatgpt-and-xmind-how-to-create-a-mind-map-with-chatgpt/">https://xmind.app/blog/chatgpt-and-xmind-how-to-create-a-mind-map-with-chatgpt/</a></p>



<p>これはXmindというMindmapツールのblog記事で、ChatGPTを使ってトピックに沿ったMindmapをChatGPTに作らせてそれをXmindに取り込んで修正するまでの流れが示されています。</p>



<p>使ったpromptの例もちゃんと書いてあって参考にしやすそうだったので、この記事の例を利用して今回は試作しました。</p>



<p>今回作ったものを次に説明していきます。</p>



<h2 class="wp-block-heading">どうやって論文のMindmapを作るか？</h2>



<p>いろいろ工夫できる部分はあると思いますが、今回はひとまず一番手っ取り早くやるならどうやるか？というのを考えて実装したものを紹介します。</p>



<p>手順としては以下の手順で作ることにします。</p>



<ol class="wp-block-list">
<li>PDFからページごとにテキストを抽出</li>



<li>ページの量が大きすぎる場合LLMの入力できるトークン数の上限を超える可能性があるので、分割する</li>



<li>分割されたテキスト毎にMindmapを生成</li>



<li>できたMindmapをLLMにマージさせて最終的なMindmapを作る</li>
</ol>



<p>今回は例としてちょうど最近読んだ以下の論文で試してみた例を示します。</p>



<p>Dao, T., Fu, D.Y., Ermon, S., Rudra, A., &amp; R&#8217;e, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. ArXiv, abs/2205.14135.</p>



<p>また実装に関してはLangChainを使ってやりました。LangChainについてご存じない方は以前書いた紹介記事もありますので興味があれば見てください。</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="jFMBDQRWHV"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" 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=tuH2yhF0Iu#?secret=jFMBDQRWHV" data-secret="jFMBDQRWHV" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>次に各ステップに関して簡単に説明していきます。</p>



<h3 class="wp-block-heading">PDFからページごとにテキストを抽出とページの分割</h3>



<p>LangChainにはPDFを読み込む機能とページを分割する機能があるので、今回はこれをそのまま使います。コード的には以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="load_and_split_pages" data-lang="Python"><code>from langchain.document_loaders.pdf import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

file_path = &quot;./reserch_paper.pdf&quot;
loader = PyPDFLoader(file_path)
pages = loader.load()
pages = pages[:11]
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
    encoding_name=&quot;p50k_base&quot;,
    chunk_size=1000,
    chunk_overlap=100,
)
sub_pages = text_splitter.split_documents(pages)</code></pre></div>



<p>まず、<code>PyPDFLoader</code>で指定されたPDFを読み込みます。その後、Referenceよりも手前のページまでを取り出します。今回は11ページ目からReferenceが始まっているので、その手前のページまで取り出します。</p>



<p>その後、<code>RecursiveCharacterTextSplitter</code>でテキストを分割します。</p>



<h3 class="wp-block-heading">分割されたテキスト毎にMindmapを生成</h3>



<p>分割されたテキストごとにMindmapを作らせます。ここではXmindのblogを参考にして以下のようなpromptのテンプレートを利用しました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="make_mindmap_prompt" data-lang="Python"><code>MAKE_MIND_MAP_PROMPT_TEMPLATE_STR = &quot;&quot;&quot;I would like to create a mind map using the Xmind tool about following text.
Can you provide me with some text in Markdown format that is compatible with Xmind? 
Please include a Central Topic with Main Topics and any additional information goes to Subtopics that will help create an effective mind map.&quot;

The mindmap format is follow:

# Central Tpoic Title

## Main Topic Title 1

### Subtopic Title 1

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2

### Subtopic Title 2

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2

## Main Topic Title 2

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2


Text:


{text}


Mind map in Markdown format:&quot;&quot;&quot;</code></pre></div>



<p>これをLangChainのLLMChainを使ってLLMに渡します。</p>



<p>これでうまくいくの？と疑問に思う方もいると思うので、最初の分割（AbstractとIntroductionの最初の部分）の結果を以下に示します。</p>



<pre class="wp-block-code"><code># FlashAttention : Fast and Memory-Efficient Exact Attention with IO-Awareness

## Introduction

### FLOP Reduction

- Sparse-Approximation
- Low-Rank Approximation
- Combinations

### IO-Awareness

- Reads and Writes
- Fast and Slow Memory
- GPU On-Chip SRAM and HBM

## Proposed Method

### FlashAttention

- Tiling
- Reduce Memory Reads/Writes
- Analyze IO Complexity

### Block-Sparse FlashAttention

- Faster than Existing Approximate Attention
- End-to-End Wall-Clock Speedup
- Longer Context in Transformers
- Higher Quality Models
- New Capabilities</code></pre>



<p>可もなく不可もなくという感じのMindmapができているかなと思います。ちなみにXmindでimportできるフォーマットで出力されているので、画像にすることも可能です。</p>



<h3 class="wp-block-heading">MindmapをLLMにマージさせて最終的なMindmapを作る</h3>



<p>ここまでで各ページのMindmapができました。ここから1つのMindmapにまとめていく作業をさせます。</p>



<p>MindmapをLLMにマージしてもらうために、今回はLLMに入力できるトークン数までMindmapを連結して、以下のpromptのテンプレートに流し込んでLLMに入力しました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="merge_maindmap_prompt" data-lang="Python"><code>&quot;&quot;&quot;Compact the following mind map into one mind maps. 
The format should be Xmind compatible Markdwon format.
The mind map format is follow:

# Central Tpoic Title

## Main Topic Title 1

### Subtopic Title 1

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2

### Subtopic Title 2

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2

## Main Topic Title 2

- Subtopic Title 1

  - Subtopic Title 1
  - Subtopic Title 2


{text}


Output mind map in Markdown format:&quot;&quot;&quot;</code></pre></div>



<p>今回の例では全部同時に1つにマージしようとするとトークン数の限界を超えるので、Mindmapをマージしたあと、できたもの同士をまたマージするという多段階のマージを繰り返し、最終的な結果をえるようにしました。ただ、これは現状ではあまりうまくいってません。結果としては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code># FlashAttention : Fast and Memory-Efficient Exact Attention with IO-Awareness

## Introduction

### FLOP Reduction

- Sparse-Approximation
- Low-Rank Approximation
- Combinations
- IO-Awareness
  - Reads and Writes
  - Fast and Slow Memory
  - GPU On-Chip SRAM and HBM

## Proposed Method

### FlashAttention

- Tiling
- Reduce Memory Reads/Writes
- Analyze IO Complexity
- Bandwidth & Memory Size
- Attention on GPT-2
  - FlashAttention PyTorch
    - Time (ms)
    - Matmul
    - Mask
    - Softmax
    - Dropout
    - Matmul
    - Fused Kernel
    - Q: N x d
    - V: N X d
    - KT: d x N
    - QKT: N x N
    - sm(Q KT)V: N x d
- Outer Loop
  - Copy Block to SRAM
  - Copy
    - Outer Loop
    - Inner Loop
  - Compute Block on SRAM
  - Output to HBM
- Inner Loop
  - Outer Loop
  - GPU
    - SRAM
    - GPU
    - HBM
    - Main Memory (CPU DRAM)
  - SRAM : 19 TB/s (20 MB)
  - HBM: 1.5 TB/s (40 GB)
  - DRAM : 12.8 GB/s (&gt;1 TB)
- Fewer HBM Accesses
  - Fig. 2
  - Lower Bound
- Memory Access Overhead
  - Block-Sparse FlashAttention
    - 2-4x Faster
    - Sequence Length of 64k
    - IO Complexity Better than FlashAttention
- Softmax Decomposition
  - Vectors 𝑥¹1º–𝑥¹2º2R𝐵
    - Softmax of Concatenated 𝑥
      - Decomposition
        - 𝑚¹𝑥º
        - 𝑓¹𝑥º
        - ℓ¹𝑥º
- Text</code></pre></div>



<p>ぱっと見ただけで後半が変なことになっていることが分かります。これに関しては次で考察します。</p>



<h2 class="wp-block-heading">現状の方法の何がまずいのか？</h2>



<p>うまくいっていない原因としては以下のものがあります。</p>



<ol class="wp-block-list">
<li>PDFからテキスト抽出する時点で、数式や図、テーブルが含まれる部分はそもそもテキストが変</li>



<li>Mindmapが大きいと出力できるトークン数の制限にひっかかるため変なところで止まる</li>
</ol>



<p>１に関してはPDFを使っている限り常について回る問題だと思いますが、PDFのパースはちゃんとやろうとするとかなり大変です。この結果、どうしても一部変なテキストになります。LLMならもしかしたらそれでもちゃんとMindmapにできるんじゃないか？と思ってためしましたが、やはり、変なテキストの部分で作ったMindmapはクオリティがかなり低い印象です。これが最後まで響いて最終的なMindmapが変なことになっていると考えられます。</p>



<p>ただ、この部分に関してはpromptを工夫すればもう少しましになるかもしれないので、また今度改良しようと思っています。</p>



<p>また、もう一つ変なところで止まっている原因として出力できるトークン数の限界の問題があります。お金の関係もあり現在は512トークンまでで制限しています。この結果、変なところで出力がとまってしまうという問題がでています。解決方法としてはもっとたくさんトークンを出力できるようにすればいいだけではありまがすが、その場合お金がすごいことになります。そうなってくると気軽にMindmapが作れなくなってしまって微妙だなぁという感じがするので、この方法以外にいい方法がないか現在模索中です。</p>



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



<p>今回はLLMを使ってMindmapを作る取り組みをはじめしたのでそのまとめを書きました。まだまだ微妙なところは多いですが、ちょっとずつ改良できればと思っています。</p>



<p>進展がありましたらまた記事にまとめようと思います。</p>



<p>この記事が少しでもみなさんのお役に立てば幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/19/llm_mindmap/">LLMを使って論文のMindmapを作りたい ver.1</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/19/llm_mindmap/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2733</post-id>	</item>
		<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 loading="lazy" 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>
		<item>
		<title>ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</title>
		<link>https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Mon, 27 Mar 2023 22:36:44 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2428</guid>

					<description><![CDATA[<p>最近話題のChatGPT界隈ですが、そんなChatGPTみたいなアプリを簡単に作れるとしたら？そんな夢のようなライブラリである「LangChain」をこの前同僚に教えてもらったので、実際に使ってみました。 実際に使ってみ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>最近話題のChatGPT界隈ですが、そんなChatGPTみたいなアプリを簡単に作れるとしたら？そんな夢のようなライブラリである「<a href="https://langchain.readthedocs.io/en/latest/#" target="_blank" rel="noopener" title="LangCHain">LangChain</a>」をこの前同僚に教えてもらったので、実際に使ってみました。</p>



<p>実際に使ってみたら想像よりもはるかに「どうなってるの！？」と思うことが多々あるすごいライブラリだったので、紹介したくて使い方をまとめてみました。</p>



<p>今回はLangChainのドキュメントの中で一番衝撃だった以下の質問に対する答えを出すコードをGoogle Colabで実行する手順を示します。</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>コード全体としては以下のURLにあります。</p>



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



<h2 class="wp-block-heading">LangChainとは？</h2>



<p>ChatGPTをはじめとした最近話題のbotのサービスの裏側にはLarge Language Model(LLM)と呼ばれる深層学習のモデルがいます。このLLMの性能がすごくなりすぎて今までできなかったとされるようなタスクが現在できるようになってきました。そして、実際何ができるのか？をいろいろな人が試して毎日いろいろなすごい使い方が編み出されている印象です。</p>



<p>このLLM、こんなにすごいなら自分の困っているタスクをやらせたいと思うのが普通かと思いますが、いざやってみようと思うとどうやればいいのかわからない時があります。</p>



<p>例えばこれから紹介するLangChainのexampleで使われていた例では以下のタスクをやらせる例がでてきます。</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>ちなみにこれをそのまChatGPTで聞くと以下のような返答になりました。</p>



<pre class="wp-block-preformatted">I'm sorry, but as an AI language model, I don't have access to up-to-date personal information about celebrities or their romantic partners. Moreover, it's not appropriate to speculate about someone's age or personal life without their consent. It's important to respect everyone's privacy and focus on topics that are respectful and informative. Is there anything else I can assist you with?</pre>



<p>プライバシーにちゃんと配慮していて偉いですね。ですが、人がやるなら以下の手順でできると思います。</p>



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



<li>出てきた人の年齢を調べる</li>



<li>年齢の0.43乗を計算する</li>
</ol>



<p>実際、この記事を書くにあたって私が人手でできるかをGoogle検索を使って確認したところ、ちゃんとできました。さて、これをLLMにやらせるとしたらどうやればいいのでしょうか？</p>



<p>このような「LLMを使ってやるのどうやればいいんだ？」に答えてくれるのがLangChainです。</p>



<p>ちなみにこのタスクをするためのコードはGoogle Colab周りの環境構築を除けば10行以下で実行できます。</p>



<p>すごすぎないですか？</p>



<p>これをGoogle Colabでやる手順をこれから紹介していきます。</p>



<h2 class="wp-block-heading">コードをGoogle Colab上で動かす準備</h2>



<p>ここではGoogle Colabでコードを動かすために必要な準備方法について紹介していきます。</p>



<p>今回はGoogle Colabで動かして他の人にも共有したりすることを想定しています。このため、セキュリティーの観点からnotebookの中にAPI Keyが含まれないような形にするために、pythonのdotenvを利用します。</p>



<p>基本的な流れとしては、最初に今回のサンプルで必要なサービスのAPI Keyを取得し、それを書いたファイルをGoogle Driveに置き、Google Driveのファイルをdotenvでロードするということをします。</p>



<p>それでは順番に説明していきます。</p>



<h3 class="wp-block-heading">OpenAI API Keyの取得</h3>



<p>まずはOpenAIのAPI Keyの取得方法です。まだOpenAIのアカウントをお持ちでない方はまずは「Sign up」をクリックしてアカウントを作ってください。</p>



<p><a href="https://platform.openai.com/">https://platform.openai.com/</a></p>



<p>料金に関してはこちらを参照してください。</p>



<p><a href="https://openai.com/pricing">https://openai.com/pricing</a></p>



<p>このブログを執筆時は最初の3か月は5ドル分無料で使えるようです。ちなみに私がLangChainのexampleを一通り動かしても1，2ドルでした。</p>



<p>アカウントを作ったらAPI Keyを取得します。こちらのAPI Keyの取得に関してはこちらのブログが分かりやすかったので参照してください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-autoworker〜google-apps-script-gas-とsikuliで始める業務改善入門 wp-block-embed-autoworker〜google-apps-script-gas-とsikuliで始める業務改善入門"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="x9UbQMQMRk"><a href="https://auto-worker.com/blog/?p=6988">【2023年版】OpenAIのAPIキー発行手順！ChatGPTや文章生成AI、画像生成AIを利用可能</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;【2023年版】OpenAIのAPIキー発行手順！ChatGPTや文章生成AI、画像生成AIを利用可能&#8221; &#8212; AutoWorker〜Google Apps Script(GAS)とSikuliで始める業務改善入門" src="https://auto-worker.com/blog/?p=6988&#038;embed=true#?secret=x9UbQMQMRk" data-secret="x9UbQMQMRk" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>取得したAPI Keyはメモ帳などにメモしておくのを忘れないようにしてください。</p>



<h3 class="wp-block-heading">SerpApiのAPI Keyの取得</h3>



<p>次にSerpApiのAPI Keyの取得に関してです。SerpApiはGoogle Search などの検索エンジンの結果をリアルタイムで取得してパースしてくれるサービスです。LangChainを使うために必須というわけではないのですが、今回動かすコードには必要なので、API Keyを取得します。</p>



<p>まずは以下のサイトにアクセスします。</p>



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



<p>まだ、アカウントを持ってない方は「Register」をクリックしてアカウントを作ります。</p>



<p>料金に関しては以下をご覧ください。</p>



<p><a href="https://serpapi.com/pricing">https://serpapi.com/pricing</a></p>



<p>今回のコードでは数回APIを叩く程度なので無料の範囲で十分できます。</p>



<p>次にアカウントを作ったらdashboardで左のメニューから「API Key」を選択するとSerpAPI のAPI Keyを見ることができます。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="512" height="329" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/serpapi_api_key-e1679795100125.png" alt="" class="wp-image-2445" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/serpapi_api_key-e1679795100125.png 512w, https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/serpapi_api_key-e1679795100125-300x193.png 300w" sizes="auto, (max-width: 512px) 100vw, 512px" /><figcaption class="wp-element-caption">SerpApiのAPI Keyの取得</figcaption></figure></div>


<p>こちらもOpenAIのAPI Keyと同様にメモ超などにメモしておいてください。</p>



<h3 class="wp-block-heading">Google DriveにAPI Keyの情報を書いたファイルを用意</h3>



<p>最後にGoogle DriveにAPI Keyの情報を書いたファイルを置きます。まずは以下のようなフォーマットのファイルを作ります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain" data-file="lang_chain_env"><code>OPENAI_API_KEY=&quot;{OpenAI API Key}&quot;
SERPAPI_API_KEY=&quot;{SerpApi API Key}&quot;</code></pre></div>



<p><code>{OpenAI API Key}</code>と<code>{SerpApi API Key}</code>の部分はメモしておいたご自身のAPI Keyに置き換えてください。</p>



<p>この作ったファイルをGoogle DriveにUploadします。保存場所はGoogle Driveなら適切にパスを指定すればGoogle Colabから読めるので、どこでもよいのです。ただし、このあとの説明は[マイドライブ] → [colab_env] の下の<code>lang_chain_env</code>というファイル名で保存したとして説明していきます。</p>



<h2 class="wp-block-heading">Google Colab上でのLangChainの使い方</h2>



<h3 class="wp-block-heading">Google Colab上での環境構築</h3>



<p>さて、準備が整ったらGoogle Colab上でコードを実行していきます。まずは必要なパッケージのインストールです。以下のようにして今回使うパッケージの中をインストールしていきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-file="install" data-lang="Bash"><code>!pip install openai langchain python-dotenv transformers google-search-results</code></pre></div>



<p>次に各種API Keyの情報を環境変数にいれます。ここでは先ほど準備した<code>lang_chain_env</code> をdotenvで読み込んで環境変数をセットします。</p>



<p>まずはGoogle ColabからGoogle Driveにアクセスできるようにします。コードとしては以下のものを実行します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="mount_google_drive" data-lang="Python"><code>from google.colab import drive
drive.mount(&#39;/content/drive&#39;)</code></pre></div>



<p>実行するとGoogle Driveへのアクセス認証を聞かれるので認証してください。</p>



<p>うまくGoogle Driveへのアクセスの認証ができれば以下のlsコマンドで先ほどアップロードしたファイルにアクセスできるようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-file="check_file" data-lang="Bash"><code>!ls /content/drive/MyDrive/colab_env/lang_chain_env</code></pre></div>



<p>そして、dotevを利用して環境変数をセットします。コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="load_envs" data-lang="Python"><code>from dotenv import load_dotenv

load_dotenv(dotenv_path=&quot;/content/drive/MyDrive/colab_env/lang_chain_env&quot;)</code></pre></div>



<p>これでGoogle ColabでLangChainのexampleを動かす準備が整いました。</p>



<h3 class="wp-block-heading">LangChainのExampleを動かす</h3>



<p>ここからはLangChainのExampleを実際に動かしてみます。と言っても基本的には以下のコードをそのまま動かします。</p>



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



<p>今回はLangChainの機能の中のAgentを使ったコードです。AgentとはLLMを利用して実行するアクションとその順序を決めるクラスです。</p>



<p>まずはLangChainの中から今回のコードで必要なものをimportします。</p>



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



<p>次に、使うLLMのモデルとツールを作ってAgentを作ります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>llm = OpenAI(temperature=0)
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)</code></pre></div>



<p>ここではLLMのモデルはOpenAIのものを利用します。LangChain自体はOpenAI以外のものも選択できるようです。詳しくはこちらをご覧ください。</p>



<p><a href="https://python.langchain.com/en/latest/reference/modules/llms.html">https://python.langchain.com/en/latest/reference/modules/llms.html</a></p>



<p>またツールとはAgentがアクションの中で使う関数みたいなものです。今回はSerpApiと数学に関する質問をするときに答えてくれるツールである<code>llm-math</code>を指定します。<br>他にもいろいろあります。詳しくはこちらをごらんください。</p>



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



<p>最後にツールやLLMを引数にとってAgentのクラスのインスタンスを作ります。</p>



<p>そしていよいよやってほしいタスクの文章をAgentのインスタンスに渡して実行します。今回は最初に見せた通り、以下のタスクをやらせます。</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-plain"><code>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>



<p>実行結果は以下の通りです。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="445" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/agent_result-1024x445.png" alt="agentのresult" class="wp-image-2446" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/agent_result-1024x445.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/agent_result-300x130.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/agent_result-768x334.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2023/03/agent_result.png 1469w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>すごくないですか？</strong></p>



<p>この質問、人が答えるならGoogle検索と簡単な計算で確かにできます。ただ、これを自動で答えられるようにするとなるとかなり面倒なコードを書かなければなりません。それが一発です。すごい時代になったものです。</p>



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



<p>今回は「<a href="https://langchain.readthedocs.io/en/latest/#" target="_blank" rel="noopener" title="LangCHain">LangChain</a>」を実際に使ってみたまとめになります。実は同僚にはこれを教えてもらった際、「全エンジニア試したほがいい」と言われて、さすがに言い過ぎでは？と一瞬思ったんのですが、使ってみてびっくり。マジで「全エンジニア試したほうがいい」って印象を受けました。</p>



<p>今回は説明しきれませんでしたが、LangChainは他にもすごいサンプルが以下のところにありますので、今回紹介したコードをベースにGoogle Colabで試しに実行してみてはいかがでしょうか？</p>



<p><a href="https://python.langchain.com/en/latest/index.html#use-cases">https://python.langchain.com/en/latest/index.html#use-cases</a></p>



<p>この記事が少しでも皆さんの役に立てば幸いです。</p>



<h2 class="wp-block-heading">参考情報</h2>



<ol class="wp-block-list">
<li>LangChainドキュメント <a href="https://langchain.readthedocs.io/en/latest/" target="_blank" rel="noopener" title="">https://langchain.readthedocs.io/en/latest/</a></li>
</ol><p>The post <a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</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/03/28/langchain_example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2428</post-id>	</item>
	</channel>
</rss>
