<?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>「メモリ」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/%E3%83%A1%E3%83%A2%E3%83%AA/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 13 Oct 2024 03:44:03 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「メモリ」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】LangChain: Memoryで情報を保存・管理する</title>
		<link>https://tech.nkhn37.net/python-langchain-memory-basics/</link>
					<comments>https://tech.nkhn37.net/python-langchain-memory-basics/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sat, 20 Jul 2024 20:00:00 +0000</pubDate>
				<category><![CDATA[LangChain]]></category>
		<category><![CDATA[ConversationBufferMemory]]></category>
		<category><![CDATA[ConversationBufferWindowMemory]]></category>
		<category><![CDATA[ConversationEntityMemory]]></category>
		<category><![CDATA[ConversationKGMemory]]></category>
		<category><![CDATA[ConversationSummaryBufferMemory]]></category>
		<category><![CDATA[ConversationSummaryMemory]]></category>
		<category><![CDATA[ConversationTokenBufferMemory]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[VectorStoreRetrieverMemory]]></category>
		<category><![CDATA[メモリ]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=10937</guid>

					<description><![CDATA[Pythonで大規模言語モデル（LLM: Large Language Model）を活用する際に使用できるLangChainでMemory（メモリ）機能を使用する方法を解説します。 LangChainのMemory機能 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Pythonで大規模言語モデル（LLM: Large Language Model）を活用する際に使用できる<span class="marker"><strong>LangChainでMemory（メモリ）機能を使用する方法</strong></span>を解説します。</p>



<h2 class="wp-block-heading">LangChainのMemory機能</h2>



<p>LangChainは、大規模言語モデル（LLM: Large Language Model）を活用するためのオープンソースPythonライブラリです。LangChain自体の概要については「<a href="https://tech.nkhn37.net/python-langchain-overview/" target="_blank" rel="noreferrer noopener">LangChainで大規模言語モデル（LLM）を活用する</a>」で説明していますので参考にしてください。</p>



<p>LangChainは、LLMの複雑なタスクを実行するためのライブラリですが、構成要素として<span class="marker"><strong>Memory（メモリ）</strong></span>という機能があります。Memoryは、LangChainが過去の対話やデータを保存しておくための機能となっており、モデルが以前の情報を参照して一貫性のある応答や新たな問い合わせに対する文脈を理解できます。</p>



<p>この記事では、<span class="marker"><strong>LangChainでMemory（メモリ）機能を使用する方法</strong></span>について紹介します。</p>



<div class="wp-block-jin-gb-block-box simple-box3">
<p>この記事で紹介しているプログラムは以下のバージョンで動作確認しています。生成AIの分野は進歩が速いため、API等の変更により最新バージョンではプログラムがそのままでは動作しない可能性もありますので注意してください。</p>



<ul class="wp-block-list">
<li>Python: 3.11.5</li>



<li>langchain: 0.2.11</li>



<li>langchain-core: 0.2.26</li>



<li>langchain-community: 0.2.10</li>



<li>langchain-openai: 0.1.16</li>
</ul>
</div>



<h3 class="wp-block-heading">Memory（メモリ）機能</h3>



<p>LangChainの<strong>Memory（メモリ）</strong>では、複数種類が提供されています。以下の表は、公式ページの<a href="https://python.langchain.com/v0.1/docs/modules/memory/types/" target="_blank" rel="noreferrer noopener">こちら</a>から参照できるメモリ機能の種類です。（最新では種類が追加されている可能性があります。）</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Memory（メモリ）の種類</th><th>概要</th></tr></thead><tbody><tr><td>Conversation Buffer</td><td>最もシンプルなMemoryで、過去の対話を記憶し、継続的な対話の管理ができます。<br>クラス：<code>ConversationBufferMemory</code></td></tr><tr><td>Conversation Buffer Window</td><td>特定回数（ウィンドウサイズ）の最新の対話のみを保持します。<br>クラス：<code>ConversationBufferWindowMemory</code></td></tr><tr><td>Conversation Token Buffer</td><td>指定トークン数を超えた場合には、過去のメッセージを削除します。<br>クラス：<code>ConversationTokenBufferMemory</code></td></tr><tr><td>Conversation Summary</td><td>対話を要約し、簡潔な形で保持します。<br>クラス：<code>ConversationSummaryMemory</code></td></tr><tr><td>Conversation Summary Buffer</td><td>指定トークン数を超えた場合に要約が行われます。<br>クラス：<code>ConversationSummaryBufferMemory</code></td></tr><tr><td>Entity</td><td>対話中に言及されたエンティティ（人物、場所、オブジェクトなど）の情報を記憶します。<br>クラス：<code>ConversationEntityMemory</code></td></tr><tr><td>Conversation Knowledge Graph</td><td>対話中のエンティティ間の関係をグラフとして構築し、複雑なクエリや推論を支援します。<br>クラス：<code>ConversationKGMemory</code></td></tr><tr><td>Backed by a Vector Store</td><td>ベクトルデータベースに対話内容を保存し、関連情報を効率的に検索します。<br>クラス：<code>VectorStoreRetrieverMemory</code></td></tr></tbody></table></figure>



<p>今回は、代表的な<strong>Conversation Buffer</strong>、<strong>Conversation Buffer Window</strong>、<strong>Conversation Token Buffer</strong>、<strong>Conversation Summary</strong>、<strong>Conversation Summary Buffer</strong>の5つを取り上げて、以降で簡単な例を紹介しようと思います。</p>



<h4 class="wp-block-heading">Conversation Buffer</h4>



<p><strong>Conversation Buffer</strong>は、最もシンプルで基本的なMemoryで過去の対話を記憶し、継続的な対話の管理するのに役立ちます。クラスは、<span class="marker"><strong><code>ConversationBufferMemory</code></strong></span>として実装されています。</p>



<p>この機能により、対話履歴をメモリ内に保持し、必要に応じて参照することが可能になります。</p>



<h5 class="wp-block-heading">一般的な使用方法</h5>



<p>以下は、Conversation Bufferを使ってメモリにメッセージを記録する例です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from langchain.memory import ConversationBufferMemory
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# メモリを用意する
memory = ConversationBufferMemory()

# メモリにユーザーメッセージを記録する
memory.chat_memory.add_user_message("ユーザーのメッセージ１")
# メモリーにAIのメッセージを記録する
memory.chat_memory.add_ai_message("AIのメッセージ１")

# メモリーに汎用的にメッセージを記録する
memory.chat_memory.add_message(HumanMessage(content="ユーザーのメッセージ２"))
memory.chat_memory.add_message(AIMessage(content="AIのメッセージ２"))
memory.chat_memory.add_message(SystemMessage(content="システムのメッセージ１"))

# メモリの情報を取得する（辞書）
print(type(memory.load_memory_variables({})))
print(memory.load_memory_variables({}))
print("-----")

# 文字列で取得する
print(type(memory.load_memory_variables({})["history"]))
print(memory.load_memory_variables({})["history"])
print("-----")

# メモリを削除する
memory.clear()
print(memory.load_memory_variables({}))
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;class 'dict'>
{'history': 'Human: ユーザーのメッセージ１\nAI: AIのメッセージ１\nHuman: ユーザーのメッセージ２\nAI: AIのメッセージ２\nSystem: システムのメッセージ１'}
-----
&lt;class 'str'>
Human: ユーザーのメッセージ１
AI: AIのメッセージ１
Human: ユーザーのメッセージ２
AI: AIのメッセージ２
System: システムのメッセージ１
-----
{'history': ''}</pre>



<p>Conversation Bufferを使うには、<code>ConversationBufferMemory</code>クラスをインポートして使用します。</p>



<p>メモリにメッセージを追加する場合には、ユーザーのメッセージ（質問）を記録する<span class="marker"><strong><code>add_user_message</code></strong></span>やAIのメッセージ（回答）を記録する<span class="marker"><strong><code>add_ai_message</code></strong></span>を使用します。また、汎用的なメソッドとして<span class="marker"><strong><code>add_message</code></strong></span>というメソッドを使用することも可能です。</p>



<p>なお、<code>add_message</code>を使用する場合は「<code>HumanMessage</code>」「<code>AIMessage</code>」「<code>SystemMessage</code>」といったクラスに<code>content</code>引数でメッセージを渡します。これらのクラスは、<code>langchain_core.messages</code>からインポートして使用します。</p>



<p>記録したメッセージを取り出す場合には、<code>load_memory_variables</code>メソッドを使用します。<code>history</code>というキーを持った辞書が返却され、値の中に過去のメッセージの文字列が格納されています。文字列を取り出したい場合は「<code>memory.load_memory_variables({})['history']</code>」のようにすることで文字列の取り出しが可能です。</p>



<h5 class="wp-block-heading">リストで結果を取得する</h5>



<p>リストで過去のやり取りを取得する場合には、以下のように<code>ConversationBufferMemory</code>を生成する際に<span class="marker"><strong><code>return_messages=True</code></strong></span>を引数として設定します。</p>



<p>※変更箇所のみ抜粋</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># メモリを用意する
memory = ConversationBufferMemory(return_messages=True)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;class 'dict'>
{'history': [HumanMessage(content='ユーザーのメッセージ１'), AIMessage(content='AIのメッセージ１'), HumanMessage(content='ユーザーのメッセージ２'), AIMessage(content='AIのメッセージ２'), SystemMessage(content='システムのメッセージ１')]}
-----
&lt;class 'list'>
[HumanMessage(content='ユーザーのメッセージ１'), AIMessage(content='AIのメッセージ１'), HumanMessage(content='ユーザーのメッセージ２'), AIMessage(content='AIのメッセージ２'), SystemMessage(content='システムのメッセージ１')]
-----
{'history': []}</pre>



<p>上記結果から、リスト形式で過去のメッセージ情報を取得できていることが分かります。以降の他クラスの紹介でも、<code>return_messages=True</code>を指定して紹介していきます。</p>



<h5 class="wp-block-heading">1回のやり取り（質問と回答）をまとめて記録する</h5>



<p>質問と回答のやり取りをまとめて1回で記録することも可能です。まとめて記録を行う場合は、以下のように<span class="marker"><strong><code>save_content</code></strong></span>メソッドを使用します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from langchain.memory import ConversationBufferMemory

# メモリを用意する
memory = ConversationBufferMemory(return_messages=True)

# 入力と回答をまとめて記録する
memory.save_context(
    {"input": "ユーザーのメッセージ１"},
    {"output": "AIのメッセージ１"},
)

# メモリの情報をで取得する
print(type(memory.load_memory_variables({})["history"]))
print(memory.load_memory_variables({})["history"])
print("-----")

# メモリを削除する
memory.clear()
print(memory.load_memory_variables({}))
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;class 'list'>
[HumanMessage(content='ユーザーのメッセージ１'), AIMessage(content='AIのメッセージ１')]
-----
{'history': []}</pre>



<p>上記例のように、ユーザーのメッセージ（質問）を<code>"input"</code>として、AIのメッセージ（回答）を<code>"output"</code>として<code>save_content</code>に渡します。</p>



<p>今回は<code>add_message</code>といったメソッドは呼び出していませんが、結果を見てみると<code>save_content</code>によりユーザーのメッセージ（質問）は<code>HumanMessage</code>、AIのメッセージ（回答）は<code>AIMessage</code>として記録されていることが分かるかと思います。</p>



<h4 class="wp-block-heading">Conversation Buffer Window</h4>



<p><strong>Conversation Buffer Window</strong>は、特定の回数（ウィンドウサイズ）で最新の対話のみを保持します。クラスは<span class="marker"><strong><code>ConversationBufferWindowMemory</code></strong></span>として実装されています。</p>



<p>例えば、メモリ容量を節約したい場合や、直近2回の質問・回答の情報を考慮に入れて後続のやり取りをしたい場合などに便利です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from langchain.memory import ConversationBufferWindowMemory
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# メモリを用意する
memory = ConversationBufferWindowMemory(return_messages=True, k=2)

# メッセージを記録する
memory.chat_memory.add_message(HumanMessage(content="ユーザーのメッセージ１"))
memory.chat_memory.add_message(AIMessage(content="AIの回答１"))
memory.chat_memory.add_message(HumanMessage(content="ユーザーのメッセージ２"))
memory.chat_memory.add_message(AIMessage(content="AIの回答２"))
memory.chat_memory.add_message(HumanMessage(content="ユーザーのメッセージ３"))
memory.chat_memory.add_message(AIMessage(content="AIの回答３"))

# メモリの情報を取得する
print(memory.load_memory_variables({})["history"])

# メモリを削除する
memory.clear()
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[HumanMessage(content='ユーザーのメッセージ２'), AIMessage(content='AIの回答２'), HumanMessage(content='ユーザーのメッセージ３'), AIMessage(content='AIの回答３')]</pre>



<p>使用するクラスは「<code>ConversationBufferWindowMemory</code>」ですので、上記例に従ってインポートして使用してください。</p>



<p>上記の実行結果を見ると直近2回の質問・回答となる２と３のメッセージのみ結果が保持されており１のメッセージは保存されていないことが分かるかと思います。</p>



<p>このようにすることでメモリの使用を制限することができます。また、直近の情報をベースにして次の質問に渡すことで、過去の情報を考慮したAIの回答をさせるといったことも可能になります。</p>



<h4 class="wp-block-heading">Conversation Token Buffer</h4>



<p><strong>Conversation Token Buffer</strong>は、指定トークン数を超えた場合には、過去のメッセージを削除します。クラスは<span class="marker"><strong><code>ConversationTokenBufferMemory</code></strong></span>として実装されています。</p>



<p>このメモリでは指定したトークン数までしか過去のメッセージを保持しませんので、メモリの節約に役立ちます。</p>



<p>以降で紹介するプログラムでは、有償のOpenAIのAPIを使用しますのでご注意ください。APIの使い方は「<a href="https://tech.nkhn37.net/python-openai-api-basics/" target="_blank" rel="noreferrer noopener">OpenAI APIの使い方の基本</a>」でまとめていますので参考にしてください。</p>



<p>キー情報は以下のようなコンフィグファイルから読み込むことにします。以下のような<code>config.ini</code>ファイルを作成し、キーを設定しておいてください。<code>xxxx</code>の部分にはご自身のキー情報が入ります。</p>



<p>【<strong><code>config.ini</code></strong>】キー情報の設定ファイル</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[OPENAI]
key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre>



<p>Conversation Token Bufferは以下のように使用します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

from langchain.memory import ConversationTokenBufferMemory
from langchain_openai import ChatOpenAI

# コンフィグファイルからキーを取得する
config = configparser.ConfigParser()
config.read("config.ini")

# モデルを初期化する
model = ChatOpenAI(
    openai_api_key=config["OPENAI"]["key"],
    model="gpt-3.5-turbo",
)

# メモリを用意する
memory = ConversationTokenBufferMemory(
    llm=model, max_token_limit=50, return_messages=True
)
memory.save_context(
    {"input": "Pythonの概要を教えてください。"},
    {
        "output": "Pythonは、シンプルでわかりやすい文法を持つ高水準のプログラミング言語です。"
    },
)
print(memory.load_memory_variables({})["history"])

# メモリを削除する
memory.clear()
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[AIMessage(content='Pythonは、シンプルでわかりやすい文法を持つ高水準のプログラミング言語です。')]</pre>



<p>使用するクラスは「<code>ConversationTokenBufferMemory</code>」ですので、上記例に従ってインポートして使用してください。また、OpenAIの<code>ChatOpenAI</code>をインポートしておきます。</p>



<p>コンフィグファイルからは<code>configparser</code>を使ってキーを読み込み、<code>ChatOpenAI</code>に指定してモデルを生成します。<code>ConversationTokenBufferMemory</code>をインスタンス化する際には、トークン数を計算するためのベースとなるモデルを<code>llm</code>引数で指定します。メモリへの記録は<code>save_content</code>を使って入力しています。</p>



<p>今回は、<code>max_token_limit=50</code>として指定しましたが、直近の回答のみしかメモリに保存されませんでした。この数値を大きくすると質問も含めてメモリに保持されます。このように<code>ConversationTokenBufferMemory</code>を使用することで、記録する過去の対話の量を制限しながらメモリーに情報を保持することができます。</p>



<div class="wp-block-jin-gb-block-box concept-box5">
<p>configparserについては「<a href="https://tech.nkhn37.net/python-configparser-basic/" target="_blank" rel="noreferrer noopener">configparserによる設定ファイル管理</a>」にまとめてありますので、使い方をご存じでない方は参考にしてください。</p>
</div>



<h4 class="wp-block-heading">Conversation Summary</h4>



<p><strong>Conversation Summary</strong>は、対話を要約し、簡潔な形で保持することができます。クラスは<span class="marker"><strong><code>ConversationSummaryMemory</code></strong></span>として実装されています。</p>



<p>Conversation Summaryの機能を使用する場合には、以下のように実行します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

from langchain.memory import ConversationSummaryMemory
from langchain_openai import ChatOpenAI

# コンフィグファイルからキーを取得する
config = configparser.ConfigParser()
config.read("config.ini")

# モデルを初期化する
model = ChatOpenAI(
    openai_api_key=config["OPENAI"]["key"],
    model="gpt-3.5-turbo",
)

# メモリを初期化し、モデルを設定する
memory = ConversationSummaryMemory(llm=model, return_messages=True)
memory.save_context(
    {"input": "Pythonの概要を教えてください。"},
    {
        "output": "Pythonは、シンプルでわかりやすい文法を持つ高水準のプログラミング言語です。"
    },
)
print(memory.load_memory_variables({})["history"])

# メモリを削除する
memory.clear()
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[SystemMessage(content='The human asks the AI to explain an overview of Python. The AI responds that Python is a high-level programming language with simple and easy-to-understand syntax.')]</pre>



<p>使用するクラスは「<code>ConversationSummaryMemory</code>」ですので、上記例に従ってインポートして使用してください。</p>



<p><code>ConversationSummaryMemory</code>をインスタンス化する際には、要約のために使うモデルとして上記で準備したモデルを渡します。メモリへの記録は<code>save_content</code>を使って入力しています。</p>



<p>実行結果を見ていただくと分かりますが、質問と回答がそのまま記録されているわけではなく、そのやり取りを要約した文字列が記録されていることが分かります。このように<code>ConversationSummaryMemory</code>を使用することで、過去の対話を要約して簡潔な形で保持することができます。</p>



<h4 class="wp-block-heading">Conversation Summary Buffer</h4>



<p><strong>Conversation Summary Buffer</strong>は、指定トークン数を超えた場合に要約が行われます。クラスは<span class="marker"><strong><code>ConversationSummaryBufferMemory</code></strong></span>として実装されています。</p>



<p>使用方法は、<code>ConversationSummaryMemory</code>とほとんど同じですが、以下のように<span class="marker"><strong><code>max_token_limit</code></strong></span>引数を指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

from langchain.memory import ConversationSummaryBufferMemory
from langchain_openai import ChatOpenAI

# コンフィグファイルからキーを取得する
config = configparser.ConfigParser()
config.read("config.ini")

# モデルを初期化する
model = ChatOpenAI(
    openai_api_key=config["OPENAI"]["key"],
    model="gpt-3.5-turbo",
)

# メモリを初期化し、モデルを設定する
# ※max_token_limitを変更して試してください。
memory = ConversationSummaryBufferMemory(
    llm=model, max_token_limit=100, return_messages=True
)
memory.save_context(
    {"input": "Pythonの概要を教えてください。"},
    {
        "output": "Pythonは、シンプルでわかりやすい文法を持つ高水準のプログラミング言語です。"
    },
)
print(memory.load_memory_variables({})["history"])

# メモリを削除する
memory.clear()
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[HumanMessage(content='Pythonの概要を教えてください。'), AIMessage(content='Pythonは、シンプルでわかりやすい文法を持つ高水準のプログラミング言語です。')]</pre>



<p>上記は、まず<code>max_token_limit</code>を100にしました。この場合、このトークン内に質問と回答が収まるので質問と回答はそのままの形式で保存されています。</p>



<p>ここで、上記の<code>max_token_limit</code>を以下のように30といった小さな値に変えて実行してみます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">memory = ConversationSummaryBufferMemory(
    llm=model, max_token_limit=30, return_messages=True
)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[SystemMessage(content='The human asks for an overview of Python. The AI explains that Python is a high-level programming language with simple and easy-to-understand syntax.')]</pre>



<p>結果は、上記のように<code>max_token_limit</code>で指定した最大トークン数を超えた場合に要約が行われました。このようにトークン数に応じて要約を行うかを制御する際に便利です。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Pythonで大規模言語モデル（LLM: Large Language Model）を活用する際に使用できる<span class="marker"><strong>LangChainでMemory（メモリ）機能を使用する方法</strong></span>を解説しました。</p>



<p>Memoryは、LangChainが過去の対話やデータを保存しておくための便利な機能となっており、モデルが以前の情報を参照して一貫性のある応答や新たな問い合わせに対する文脈を理解できます。</p>



<p>メモリ機能には、いくつも種類が用意されていますが、この記事では基本的な<strong>Conversation Buffer</strong>、<strong>Conversation Buffer Window</strong>、<strong>Conversation Token Buffer</strong>、<strong>Conversation Summary</strong>、<strong>Conversation Summary Buffer</strong>といった5つのメモリ機能を簡単な例を使って紹介しました。</p>



<p>実際にはLangChainには、他にも様々な機能があります。皆さんもLangChainの使い方をぜひ覚えていってもらえるといいと思います。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-python-tech wp-block-embed-python-tech"><div class="wp-block-embed__wrapper">
https://tech.nkhn37.net/python-tech-summary-page
</div></figure>


]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-langchain-memory-basics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-05-09 23:08:37 by W3 Total Cache
-->