LangChain OpenTutorial
  • 🦜️🔗 The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • Extracting messages as strings
  • Extracting messages as HumanMessage and AIMessage objects
  • Applying to a Chain
  1. 05-Memory

ConversationBufferMemory

Previous05-MemoryNextConversationBufferWindowMemory

Last updated 28 days ago

  • Author:

  • Peer Review : , ,

  • Proofread :

  • This is a part of

Overview

This tutorial introduces ConversationBufferMemory, a memory class that stores conversation history in a buffer.

Typically, no additional processing is required. Sometimes, however, it may be necessary when the conversation history exceeds the model's context window.

In this tutorial, we will learn how to use ConversationBufferMemory to store and retrieve conversation history.

Table of Contents

References


Environment Setup

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

%%capture --no-stderr
%pip install langchain-opentutorial
# Install required packages
from langchain_opentutorial import package

package.install(
    [
        "langsmith",
        "langchain",
        "langchain_openai",
    ],
    verbose=False,
    upgrade=False,
)
# Set environment variables
from langchain_opentutorial import set_env

set_env(
    {
        "OPENAI_API_KEY": "",
        "LANGCHAIN_API_KEY": "",
        "LANGCHAIN_TRACING_V2": "true",
        "LANGCHAIN_ENDPOINT": "https://api.smith.langchain.com",
        "LANGCHAIN_PROJECT": "ConversationBufferMemory",
    }
)
Environment variables have been set successfully.

You can alternatively set OPENAI_API_KEY in .env file and load it.

[Note]

  • This is not necessary if you've already set OPENAI_API_KEY in previous steps.

from dotenv import load_dotenv

load_dotenv()
True

Extracting messages as strings

After storing conversation messages, this memory allows you to extract messages into a variable.

from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory
/tmp/ipykernel_188575/2223904900.py:1: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/
      memory = ConversationBufferMemory()
ConversationBufferMemory(chat_memory=InMemoryChatMessageHistory(messages=[]))

You can use the save_context(inputs, outputs) method to save conversation records.

  • This method accepts two arguments, inputs and outputs.

  • inputs stores the user's question, and outputs stores the AI's answer.

  • The conversation record is stored internally under the history key.

  • You can then use the load_memory_variables method to retrieve and inspect the saved conversation history.

# inputs: dictionary(key: "human" or "ai", value: question)
# outputs: dictionary(key: "ai" or "human", value: answer)
memory.save_context(
    inputs={
        "human": "Hello, I want to open a bank account remotely. How do I start?",
    },
    outputs={
        "ai": "Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification."
    },
)
memory
ConversationBufferMemory(chat_memory=InMemoryChatMessageHistory(messages=[HumanMessage(content='Hello, I want to open a bank account remotely. How do I start?', additional_kwargs={}, response_metadata={}), AIMessage(content="Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.", additional_kwargs={}, response_metadata={})]))

The load_memory_variables({}) method of the memory object returns the complete message history as a string.

# Check the message history stored in the 'history' key.
print(memory.load_memory_variables({})["history"])
Human: Hello, I want to open a bank account remotely. How do I start?
    AI: Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.
memory.save_context(
    inputs={
        "human": "Yes, I've prepared my ID for identity verification. What should I do next?"
    },
    outputs={
        "ai": "Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next."
    },
)
# Check the message history stored in the 'history' key.
print(memory.load_memory_variables({})["history"])
Human: Hello, I want to open a bank account remotely. How do I start?
    AI: Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.
    Human: Yes, I've prepared my ID for identity verification. What should I do next?
    AI: Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next.
# Save 2 conversations.
memory.save_context(
    inputs={
        "human": "I uploaded the photo. How do I proceed with identity verification?"
    },
    outputs={
        "ai": "We have confirmed the photo you uploaded. Please proceed with identity verification through your mobile phone. Please enter the verification number sent by text."
    },
)
memory.save_context(
    inputs={
        "human": "I entered the verification number. How do I open an account now?"
    },
    outputs={
        "ai": "Identity verification has been completed. Please select the type of account you want and enter the necessary information. You can choose the type of deposit, currency, etc."
    },
)
# Check the conversation history stored in the 'history' key.
print(memory.load_memory_variables({})["history"])
Human: Hello, I want to open a bank account remotely. How do I start?
    AI: Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.
    Human: Yes, I've prepared my ID for identity verification. What should I do next?
    AI: Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next.
    Human: I uploaded the photo. How do I proceed with identity verification?
    AI: We have confirmed the photo you uploaded. Please proceed with identity verification through your mobile phone. Please enter the verification number sent by text.
    Human: I entered the verification number. How do I open an account now?
    AI: Identity verification has been completed. Please select the type of account you want and enter the necessary information. You can choose the type of deposit, currency, etc.
# Save 2 more conversations.
memory.save_context(
    inputs={
        "human": "I've entered all the information. What's the next step?",
    },
    outputs={
        "ai": "I've confirmed the information you've entered. The account opening process is almost complete. Please agree to the terms of use and confirm the account opening."
    },
)
memory.save_context(
    inputs={
        "human": "I've completed all the steps. Has the account been opened?",
    },
    outputs={
        "ai": "Yes, the account has been opened. Your account number and related information have been sent to the email you registered. If you need additional help, please contact us at any time. Thank you!"
    },
)
# Check the conversation history stored in the 'history' key.
print(memory.load_memory_variables({})["history"])
Human: Hello, I want to open a bank account remotely. How do I start?
    AI: Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.
    Human: Yes, I've prepared my ID for identity verification. What should I do next?
    AI: Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next.
    Human: I uploaded the photo. How do I proceed with identity verification?
    AI: We have confirmed the photo you uploaded. Please proceed with identity verification through your mobile phone. Please enter the verification number sent by text.
    Human: I entered the verification number. How do I open an account now?
    AI: Identity verification has been completed. Please select the type of account you want and enter the necessary information. You can choose the type of deposit, currency, etc.
    Human: I've entered all the information. What's the next step?
    AI: I've confirmed the information you've entered. The account opening process is almost complete. Please agree to the terms of use and confirm the account opening.
    Human: I've completed all the steps. Has the account been opened?
    AI: Yes, the account has been opened. Your account number and related information have been sent to the email you registered. If you need additional help, please contact us at any time. Thank you!

Extracting messages as HumanMessage and AIMessage objects

Setting return_messages=True returns HumanMessage and AIMessage objects.

memory = ConversationBufferMemory(return_messages=True)

memory.save_context(
    inputs={
        "human": "Hello, I want to open a bank account remotely. How do I start?",
    },
    outputs={
        "ai": "Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.",
    },
)

memory.save_context(
    inputs={
        "human": "Yes, I've prepared my ID for identity verification. What should I do next?"
    },
    outputs={
        "ai": "Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next."
    },
)

memory.save_context(
    inputs={
        "human": "I uploaded the photo. How do I proceed with identity verification?"
    },
    outputs={
        "ai": "We have confirmed the photo you uploaded. Please proceed with identity verification through your mobile phone. Please enter the verification number sent by text."
    },
)
# Check the conversation history stored in the 'history' key.
memory.load_memory_variables({})["history"]
[HumanMessage(content='Hello, I want to open a bank account remotely. How do I start?', additional_kwargs={}, response_metadata={}),
     AIMessage(content="Hello! I'm glad you want to open an account. First, please prepare your ID for identity verification.", additional_kwargs={}, response_metadata={}),
     HumanMessage(content="Yes, I've prepared my ID for identity verification. What should I do next?", additional_kwargs={}, response_metadata={}),
     AIMessage(content='Thank you. Please upload the front and back of your ID clearly. We will proceed with the identity verification process next.', additional_kwargs={}, response_metadata={}),
     HumanMessage(content='I uploaded the photo. How do I proceed with identity verification?', additional_kwargs={}, response_metadata={}),
     AIMessage(content='We have confirmed the photo you uploaded. Please proceed with identity verification through your mobile phone. Please enter the verification number sent by text.', additional_kwargs={}, response_metadata={})]

Applying to a Chain

Let's apply ConversationBufferMemory to a ConversationChain.

from langchain_openai import ChatOpenAI
from langchain.chains import ConversationChain

# Create an LLM model.
llm = ChatOpenAI(temperature=0, model_name="gpt-4o")

# Create a ConversationChain.
conversation = ConversationChain(
    # Use ConversationBufferMemory.
    llm=llm,
    memory=ConversationBufferMemory(),
)
/tmp/ipykernel_188575/3549519840.py:8: LangChainDeprecationWarning: The class `ConversationChain` was deprecated in LangChain 0.2.7 and will be removed in 1.0. Use :meth:`~RunnableWithMessageHistory: https://python.langchain.com/v0.2/api_reference/core/runnables/langchain_core.runnables.history.RunnableWithMessageHistory.html` instead.
      conversation = ConversationChain(

Proceed with the conversation using the ConversationChain.

# Start the conversation.
response = conversation.predict(
    input="Hello, I want to open a bank account remotely. How do I start?"
)
print(response)
Hello again! Opening a bank account remotely is a convenient process, and I’m happy to guide you through it. Here’s a detailed step-by-step guide to help you get started:
    
    1. **Research and Choose a Bank**: Start by researching different banks to find one that suits your needs. Consider factors like account fees, interest rates, customer service, and any special features they offer. Online reviews and comparison websites can be helpful in making your decision.
    
    2. **Visit the Bank’s Website**: Once you’ve chosen a bank, head to their official website. Look for the section dedicated to personal banking or account opening. Most banks have a clear pathway for opening accounts online.
    
    3. **Select the Type of Account**: Decide on the type of account you want to open. Common options include checking accounts, savings accounts, or a combination of both. Some banks also offer specialized accounts like student accounts or high-yield savings accounts.
    
    4. **Prepare Required Documents**: Gather the necessary documents and information. Typically, you’ll need:
       - A government-issued ID (such as a passport or driver’s license)
       - Social Security Number or Tax Identification Number
       - Proof of address (like a utility bill or lease agreement)
       - Employment and income information
    
    5. **Fill Out the Application**: Complete the online application form by entering your personal details, selecting your account preferences, and agreeing to the bank’s terms and conditions.
    
    6. **Verify Your Identity**: The bank will likely require you to verify your identity. This might involve uploading a photo of your ID, answering security questions, or participating in a video call with a bank representative.
    
    7. **Fund Your Account**: You’ll need to make an initial deposit to activate your account. This can usually be done via a transfer from another bank account, a credit card, or a check.
    
    8. **Receive Confirmation**: Once your application is approved and your account is funded, you’ll receive confirmation from the bank. This might include your account number, online banking login details, and information on how to manage your account.
    
    9. **Set Up Online Banking**: If you haven’t already, set up online banking to manage your account. This will allow you to check your balance, transfer funds, pay bills, and more.
    
    If you have any specific questions about a particular bank or need further assistance, feel free to ask!

Verify if the system remembers the previous conversation.

# Send a request to summarize the previous conversation in bullet points.
response = conversation.predict(input="Summarize the previous answer in bullet points.")
print(response)
Certainly! Here’s a summarized version of the steps to open a bank account remotely:
    
    - **Research and Choose a Bank**: Consider fees, interest rates, customer service, and special features.
    - **Visit the Bank’s Website**: Navigate to the personal banking or account opening section.
    - **Select the Type of Account**: Choose between checking, savings, or specialized accounts.
    - **Prepare Required Documents**: Gather ID, Social Security Number, proof of address, and income information.
    - **Fill Out the Application**: Enter personal details and agree to terms and conditions.
    - **Verify Your Identity**: Upload ID, answer security questions, or join a video call.
    - **Fund Your Account**: Make an initial deposit via transfer, credit card, or check.
    - **Receive Confirmation**: Get account number and online banking details.
    - **Set Up Online Banking**: Manage your account online for transactions and bill payments.

Set up the environment. You may refer to for more details.

You can checkout the for more details.

LangChain: ConversationBufferMemory
Environment Setup
langchain-opentutorial
Sungchul Kim
Shinar12
BAEM1N
YellowGangneng
Chaeyoon Kim
LangChain Open Tutorial
Overview
Environment Setup
Extracting messages as strings
Extracting messages as HumanMessage and AIMessage objects
Applying to a Chain