-
Notifications
You must be signed in to change notification settings - Fork 282
[E-4] 05-Memory / 01-ConversationBufferMemory, / 02-ConversationBufferWindowMemory #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d1366ef
Add ConversationBufferWindowMemory and TokenBufferMemory examples
gyjong 75c4e44
Add ConversationBufferWindowMemory and TokenBufferMemory
gyjong 3e6b423
Add ConversationBufferWindowMemory and TokenBufferMemory
gyjong 6cf5008
Merge branch 'LangChain-OpenTutorial:main' into main
gyjong 62abdbf
Merge branch 'LangChain-OpenTutorial:main' into main
gyjong dbaa6d7
Merge branch 'LangChain-OpenTutorial:main' into main
gyjong 6514639
Merge branch 'LangChain-OpenTutorial:main' into main
gyjong 602a583
수정사항 반영
teddylee777 40c7a78
Merge branch 'LangChain-OpenTutorial:main' into main
gyjong File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,262 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"# ConversationBufferWindowMemory\n", | ||
"\n", | ||
"- Author: [Kenny Jung](https://www.linkedin.com/in/kwang-yong-jung)\n", | ||
"- Design: [Kenny Jung](https://www.linkedin.com/in/kwang-yong-jung)\n", | ||
"- Peer Review: [Teddy](https://github.com/teddylee777)\n", | ||
"- This is a part of [LangChain Open Tutorial](https://github.com/LangChain-OpenTutorial/LangChain-OpenTutorial)\n", | ||
"\n", | ||
"[](https://colab.research.google.com/github/gyjong/LangChain-OpenTutorial/blob/main/05-Memory/02-ConversationBufferWindowMemory.ipynb) [](https://academy.langchain.com/courses/take/intro-to-langgraph/lessons/58239937-lesson-2-sub-graphs)\n", | ||
"\n", | ||
"## Overview\n", | ||
"\n", | ||
"`ConversationBufferWindowMemory` maintains a list of conversation interactions over time.\n", | ||
"\n", | ||
"In this case, `ConversationBufferWindowMemory` uses only the **most recent K** interactions instead of utilizing all conversation content.\n", | ||
"\n", | ||
"This can be useful for maintaining a sliding window of the most recent interactions to prevent the buffer from becoming too large.\n", | ||
"\n", | ||
"\n", | ||
"### Table of Contents\n", | ||
"\n", | ||
"- [Overview](#overview)\n", | ||
"- [Environement Setup](#environment-setup)\n", | ||
"- [Online Bank Account Opening Conversation Example](#online-bank-account-opening-conversation-example)\n", | ||
"- [Retrieving Conversation History](#retrieving-conversation-history)\n", | ||
"\n", | ||
"### References\n", | ||
"\n", | ||
"- [LangChain Python API Reference > langchain: 0.3.13 > memory > ConversationBufferWindowMemory](https://python.langchain.com/api_reference/langchain/memory/langchain.memory.buffer_window.ConversationBufferWindowMemory.html)\n", | ||
"----" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"## Environment Setup\n", | ||
"\n", | ||
"Set up the environment. You may refer to [Environment Setup](https://wikidocs.net/257836) for more details.\n", | ||
"\n", | ||
"**[Note]**\n", | ||
"- `langchain-opentutorial` is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials. \n", | ||
"- You can checkout the [`langchain-opentutorial`](https://github.com/LangChain-OpenTutorial/langchain-opentutorial-pypi) for more details." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 1, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"%%capture --no-stderr\n", | ||
"!pip install langchain-opentutorial" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 2, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"# Install required packages\n", | ||
"from langchain_opentutorial import package\n", | ||
"\n", | ||
"package.install(\n", | ||
" [\n", | ||
" \"langsmith\",\n", | ||
" \"langchain\",\n", | ||
" \"langchain_core\",\n", | ||
" \"langchain-anthropic\",\n", | ||
" \"langchain_community\",\n", | ||
" \"langchain_text_splitters\",\n", | ||
" \"langchain_openai\",\n", | ||
" ],\n", | ||
" verbose=False,\n", | ||
" upgrade=False,\n", | ||
")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 3, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"name": "stdout", | ||
"output_type": "stream", | ||
"text": [ | ||
"Environment variables have been set successfully.\n" | ||
] | ||
} | ||
], | ||
"source": [ | ||
"# Set environment variables\n", | ||
"from langchain_opentutorial import set_env\n", | ||
"\n", | ||
"set_env(\n", | ||
" {\n", | ||
" \"OPENAI_API_KEY\": \"\",\n", | ||
" \"LANGCHAIN_API_KEY\": \"\",\n", | ||
" \"LANGCHAIN_TRACING_V2\": \"true\",\n", | ||
" \"LANGCHAIN_ENDPOINT\": \"https://api.smith.langchain.com\",\n", | ||
" \"LANGCHAIN_PROJECT\": \"ConversationBufferWindowMemory\",\n", | ||
" }\n", | ||
")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"You can alternatively set `OPENAI_API_KEY` in `.env` file and load it.\n", | ||
"\n", | ||
"[Note] This is not necessary if you've already set `OPENAI_API_KEY` in previous steps." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 4, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"data": { | ||
"text/plain": [ | ||
"True" | ||
] | ||
}, | ||
"execution_count": 4, | ||
"metadata": {}, | ||
"output_type": "execute_result" | ||
} | ||
], | ||
"source": [ | ||
"from dotenv import load_dotenv\n", | ||
"\n", | ||
"load_dotenv(override=True)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"## Online Bank Account Opening Conversation Example\n", | ||
"\n", | ||
"This example demonstrates how to use `ConversationBufferWindowMemory` to simulate a virtual banking assistant conversation. The conversation flow shows a typical online bank account opening process, from initial greeting to account creation confirmation, while maintaining only the most recent interactions in memory." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 7, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"from langchain.memory import ConversationBufferWindowMemory\n", | ||
"\n", | ||
"memory = ConversationBufferWindowMemory(k=2, return_messages=True)\n", | ||
"\n", | ||
"memory.save_context(\n", | ||
" inputs={\n", | ||
" \"human\": \"Hello, I'd like to open a bank account online. How do I get started?\"\n", | ||
" },\n", | ||
" outputs={\n", | ||
" \"ai\": \"Hello! I'm glad you want to open an account. First, could you please prepare your ID for verification?\"\n", | ||
" },\n", | ||
")\n", | ||
"memory.save_context(\n", | ||
" inputs={\"human\": \"Yes, I have my ID ready. What should I do next?\"},\n", | ||
" outputs={\n", | ||
" \"ai\": \"Thank you. Please take clear photos of both sides of your ID and upload them. Then we'll proceed with the identity verification process.\"\n", | ||
" },\n", | ||
")\n", | ||
"memory.save_context(\n", | ||
" inputs={\n", | ||
" \"human\": \"I've uploaded the photos. How does the identity verification work?\"\n", | ||
" },\n", | ||
" outputs={\n", | ||
" \"ai\": \"I've confirmed your uploaded photos. Now, please proceed with phone verification. You'll receive a verification code via text message - please enter that code.\"\n", | ||
" },\n", | ||
")\n", | ||
"memory.save_context(\n", | ||
" inputs={\n", | ||
" \"human\": \"I've entered the verification code. How do I proceed with opening the account?\"\n", | ||
" },\n", | ||
" outputs={\n", | ||
" \"ai\": \"Your identity has been verified. Now, please select the type of account you want and enter the required information. You can choose the type of deposit, currency, and other options.\"\n", | ||
" },\n", | ||
")\n", | ||
"memory.save_context(\n", | ||
" inputs={\"human\": \"I've entered all the information. What's the next step?\"},\n", | ||
" outputs={\n", | ||
" \"ai\": \"I've confirmed your information. The account opening process is almost complete. Finally, please agree to the terms of service and confirm the account opening.\"\n", | ||
" },\n", | ||
")\n", | ||
"memory.save_context(\n", | ||
" inputs={\"human\": \"I've completed all the steps. Has the account been opened?\"},\n", | ||
" outputs={\n", | ||
" \"ai\": \"Yes, your account has been successfully opened. Your account number and related information have been sent to your registered email. Please let us know if you need any further assistance. Thank you!\"\n", | ||
" },\n", | ||
")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"## Retrieving Conversation History\n", | ||
"\n", | ||
"Let's examine the conversation history stored in memory using the `load_memory_variables()` method to verify our window-based memory retention." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 8, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"data": { | ||
"text/plain": [ | ||
"[HumanMessage(content=\"I've entered all the information. What's the next step?\", additional_kwargs={}, response_metadata={}),\n", | ||
" AIMessage(content=\"I've confirmed your information. The account opening process is almost complete. Finally, please agree to the terms of service and confirm the account opening.\", additional_kwargs={}, response_metadata={}),\n", | ||
" HumanMessage(content=\"I've completed all the steps. Has the account been opened?\", additional_kwargs={}, response_metadata={}),\n", | ||
" AIMessage(content='Yes, your account has been successfully opened. Your account number and related information have been sent to your registered email. Please let us know if you need any further assistance. Thank you!', additional_kwargs={}, response_metadata={})]" | ||
] | ||
}, | ||
"execution_count": 8, | ||
"metadata": {}, | ||
"output_type": "execute_result" | ||
} | ||
], | ||
"source": [ | ||
"# Check the conversation history\n", | ||
"memory.load_memory_variables({})[\"history\"]" | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "py-test", | ||
"language": "python", | ||
"name": "python3" | ||
}, | ||
"language_info": { | ||
"codemirror_mode": { | ||
"name": "ipython", | ||
"version": 3 | ||
}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.11.11" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
한 가지 의견을 제안드리자면, 마지막에 마크다운 블럭 하나 추가해서
ConversationBufferWindowMemory
를 선언할 때 k=2로 설정해 주었기 때문에 결과적으로 최근의 2개의 메세지만이 메모리에 저장된 것을 확인할 수 있다~라는 느낌의 멘트를 추가해주어 마무리를 해주면 더 완성도 높은 결과가 될 수 있지 않을까 싶습니다 :)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@YellowGangneng 좋은 의견 감사합니다!