!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
        *   [Memory](/v0.1/docs/modules/memory/)
            
            *   [\[Beta\] Memory](/v0.1/docs/modules/memory/)
            *   [Chat Message History](/v0.1/docs/modules/memory/chat_messages/)
                
            *   [Memory types](/v0.1/docs/modules/memory/types/)
                
        *   [Callbacks](/v0.1/docs/modules/callbacks/)
            
        *   [Experimental](/v0.1/docs/modules/experimental/)
            
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   More
*   Memory

On this page

\[Beta\] Memory
===============

Many LLM applications have a conversational interface. An essential component of a conversation is being able to refer to information introduced earlier in the conversation. At bare minimum, a conversational system should be able to access some window of past messages directly. A more complex system will need to have a world model that it is constantly updating, which allows it to do things like maintain information about entities and their relationships.

We call this ability to store information about past interactions "memory". LangChain provides utilities for adding memory to a system. These utilities can be used by themselves or incorporated seamlessly into a chain.

Most memory-related functionality in LangChain is marked as beta. This is for two reasons:

1.  Most functionality (with some exceptions, see below) is not production ready.
2.  Most functionality (with some exceptions, see below) works with Legacy chains, not the newer LCEL syntax.

The main exception to this is the ChatMessageHistory functionality. This functionality is largely production ready and does integrate with LCEL.

*   [LCEL Runnables](/v0.1/docs/expression_language/how_to/message_history/): See these docs for an overview of how to use ChatMessageHistory with LCEL runnables.
*   [Integrations](/v0.1/docs/integrations/chat_memory/): See these docs for an introduction to the various ChatMessageHistory integrations.

Introduction[​](#introduction "Direct link to Introduction")
------------------------------------------------------------

A memory system needs to support two basic actions: reading and writing. Recall that every chain defines some core execution logic that expects certain inputs. Some of these inputs come directly from the user, but some of these inputs can come from memory. A chain will interact with its memory system twice in a given run.

1.  AFTER receiving the initial user inputs but BEFORE executing the core logic, a chain will READ from its memory system and augment the user inputs.
2.  AFTER executing the core logic but BEFORE returning the answer, a chain will WRITE the inputs and outputs of the current run to memory, so that they can be referred to in future runs.

![](/v0.1/assets/images/memory_diagram-0627c68230aa438f9b5419064d63cbbc.png)

Building memory into a system[​](#building-memory-into-a-system "Direct link to Building memory into a system")
---------------------------------------------------------------------------------------------------------------

The two core design decisions in any memory system are:

*   How state is stored
*   How state is queried

### Storing: List of chat messages[​](#storing-list-of-chat-messages "Direct link to Storing: List of chat messages")

Underlying any memory is a history of all chat interactions. Even if these are not all used directly, they need to be stored in some form. One of the key parts of the LangChain memory module is a series of integrations for storing these chat messages, from in-memory lists to persistent databases.

*   [Chat message storage](/v0.1/docs/modules/memory/chat_messages/): How to work with Chat Messages, and the various integrations offered.

### Querying: Data structures and algorithms on top of chat messages[​](#querying-data-structures-and-algorithms-on-top-of-chat-messages "Direct link to Querying: Data structures and algorithms on top of chat messages")

Keeping a list of chat messages is fairly straight-forward. What is less straight-forward are the data structures and algorithms built on top of chat messages that serve a view of those messages that is most useful.

A very simple memory system might just return the most recent messages each run. A slightly more complex memory system might return a succinct summary of the past K messages. An even more sophisticated system might extract entities from stored messages and only return information about entities referenced in the current run.

Each application can have different requirements for how memory is queried. The memory module should make it easy to both get started with simple memory systems and write your own custom systems if needed.

*   [Memory types](/v0.1/docs/modules/memory/types/): The various data structures and algorithms that make up the memory types LangChain supports

Get started[​](#get-started "Direct link to Get started")
---------------------------------------------------------

Let's take a look at what Memory actually looks like in LangChain. Here we'll cover the basics of interacting with an arbitrary memory class.

Let's take a look at how to use `BufferMemory` in chains. `BufferMemory` is an extremely simple form of memory that just keeps a list of chat messages in a buffer and passes those into the prompt template:

    import { BufferMemory } from "langchain/memory";import { HumanMessage, AIMessage } from "@langchain/core/messages";const memory = new BufferMemory();await memory.chatHistory.addMessage(new HumanMessage("Hi!"));await memory.chatHistory.addMessage(new AIMessage("What's up?"));

When using memory in a chain, there are a few key concepts to understand. Note that here we cover general concepts that are useful for most types of memory. Each individual memory type may have its own parameters and concepts.

### What variables get returned from memory[​](#what-variables-get-returned-from-memory "Direct link to What variables get returned from memory")

Before going into the chain, various variables are read from memory. These have specific names which need to align with the variables the chain expects. You can see what these variables are by calling `await memory.loadMemoryVariables({})`. Note that the empty dictionary that we pass in is just a placeholder for real variables. If the memory type you are using is dependent upon the input variables, you may need to pass values here.

    await memory.loadMemoryVariables({});// { history: "Human: Hi!\AI: What's up?" }

In this case, you can see that `loadMemoryVariables` returns a single key, `history`. This means that your chain (and likely your prompt) should expect an input named `history`. You can generally control this variable through parameters on the memory class. For example, if you want the memory variables to be returned under the key `chat_history` you can do:

    const memory2 = new BufferMemory({  memoryKey: "chat_history",});await memory2.chatHistory.addMessage(new HumanMessage("Hi!"));await memory2.chatHistory.addMessage(new AIMessage("What's up?"));await memory2.loadMemoryVariables({});// { chat_history: "Human: Hi!\AI: What's up?" }

The parameter name to control these keys may vary per memory type, but it's important to understand that (1) this is controllable, and (2) how to control it.

### Whether memory is a string or a list of messages[​](#whether-memory-is-a-string-or-a-list-of-messages "Direct link to Whether memory is a string or a list of messages")

One of the most common types of memory involves returning a list of chat messages. These can either be returned as a single string, all concatenated together (useful when they will be passed into LLMs) or a list of ChatMessages (useful when passed into ChatModels).

By default, they are returned as a single string. In order to return as a list of messages, you can set `returnMessages` to `true`.

    const messageMemory = new BufferMemory({  returnMessages: true,});await messageMemory.chatHistory.addMessage(new HumanMessage("Hi!"));await messageMemory.chatHistory.addMessage(new AIMessage("What's up?"));await messageMemory.loadMemoryVariables({});/*  {    history: [      HumanMessage {        content: 'Hi!',        additional_kwargs: {}      },      AIMessage {        content: "What's up?",        additional_kwargs: {}      }    ]  }*/

### What keys are saved to memory[​](#what-keys-are-saved-to-memory "Direct link to What keys are saved to memory")

Often times chains take in or return multiple input/output keys. In these cases, how can we know which keys we want to save to the chat message history? This is generally controllable by `inputKey` and `outputKey` parameters on the memory types. These default to None - and if there is only one input/output key the class will default to just use that key. However, if there are multiple input/output keys then you MUST specify the name of which one to use.

### End to end example[​](#end-to-end-example "Direct link to End to end example")

Finally, let's take a look at using this in a chain. We'll use an `LLMChain`, and show working with both an LLM and a ChatModel.

#### Using an LLM[​](#using-an-llm "Direct link to Using an LLM")

    import { OpenAI } from "@langchain/openai";import { PromptTemplate } from "@langchain/core/prompts";import { LLMChain } from "langchain/chains";const llm = new OpenAI({ temperature: 0 });// Notice that a "chat_history" variable is present in the prompt templateconst template = `You are a nice chatbot having a conversation with a human.Previous conversation:{chat_history}New human question: {question}Response:`;const prompt = PromptTemplate.fromTemplate(template);// Notice that we need to align the `memoryKey` with the variable in the promptconst llmMemory = new BufferMemory({ memoryKey: "chat_history" });const conversationChain = new LLMChain({  llm,  prompt,  verbose: true,  memory: llmMemory,});// Notice that we just pass in the `question` variable.// `chat_history` gets populated by the memory classawait conversationChain.invoke({ question: "What is your name?" });await conversationChain.invoke({ question: "What did I just ask you?" });

    // { text: ' My name is OpenAI. What is your name?' }// { text: ' You just asked me what my name is.' }

#### Using a chat model[​](#using-a-chat-model "Direct link to Using a chat model")

    import { ChatOpenAI } from "@langchain/openai";import {  ChatPromptTemplate,  MessagesPlaceholder,} from "@langchain/core/prompts";const chatModel = new ChatOpenAI({ temperature: 0 });const chatPrompt = ChatPromptTemplate.fromMessages([  ["system", "You are a nice chatbot having a conversation with a human."],  // The variable name here is what must align with memory  new MessagesPlaceholder("chat_history"),  ["human", "{question}"],]);// Notice that we set `returnMessages: true` to return raw chat messages that are inserted// into the MessagesPlaceholder.// Additionally, note that `"chat_history"` aligns with the MessagesPlaceholder name.const chatPromptMemory = new BufferMemory({  memoryKey: "chat_history",  returnMessages: true,});const chatConversationChain = new LLMChain({  llm: chatModel,  prompt: chatPrompt,  verbose: true,  memory: chatPromptMemory,});// Notice that we just pass in the `question` variables - `chat_history` gets populated by memoryawait chatConversationChain.invoke({ question: "What is your name?" });await chatConversationChain.invoke({ question: "What did I just ask you?" });

    // { text: "Hello! I'm an AI chatbot, so I don't have a personal name. You can just call me Chatbot. How can I assist you today?" }// { text: 'You just asked me what my name is.' }

Next steps[​](#next-steps "Direct link to Next steps")
------------------------------------------------------

And that's it for getting started! Please see the other sections for walkthroughs of more advanced topics.

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Vector stores as tools

](/v0.1/docs/modules/agents/tools/how_to/agents_with_vectorstores/)[

Next

\[Beta\] Memory

](/v0.1/docs/modules/memory/)

*   [Introduction](#introduction)
*   [Building memory into a system](#building-memory-into-a-system)
    *   [Storing: List of chat messages](#storing-list-of-chat-messages)
    *   [Querying: Data structures and algorithms on top of chat messages](#querying-data-structures-and-algorithms-on-top-of-chat-messages)
*   [Get started](#get-started)
    *   [What variables get returned from memory](#what-variables-get-returned-from-memory)
    *   [Whether memory is a string or a list of messages](#whether-memory-is-a-string-or-a-list-of-messages)
    *   [What keys are saved to memory](#what-keys-are-saved-to-memory)
    *   [End to end example](#end-to-end-example)
*   [Next steps](#next-steps)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.