Class BufferMemory

The BufferMemory class is a type of memory component used for storing and managing previous chat messages. It is a wrapper around ChatMessageHistory that extracts the messages into an input variable. This class is particularly useful in applications like chatbots where it is essential to remember previous interactions. Note: The memory instance represents the history of a single conversation. Therefore, it is not recommended to share the same history or memory instance between two different chains. If you deploy your LangChain app on a serverless environment, do not store memory instances in a variable, as your hosting provider may reset it by the next time the function is called.

Example

// Initialize the memory to store chat history and set up the language model with a specific temperature.
const memory = new BufferMemory({ memoryKey: "chat_history" });
const model = new ChatOpenAI({ temperature: 0.9 });

// Create a prompt template for a friendly conversation between a human and an AI.
const prompt =
PromptTemplate.fromTemplate(`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:
{chat_history}
Human: {input}
AI:`);

// Set up the chain with the language model, prompt, and memory.
const chain = new LLMChain({ llm: model, prompt, memory });

// Example usage of the chain to continue the conversation.
// The `call` method sends the input to the model and returns the AI's response.
const res = await chain.call({ input: "Hi! I'm Jim." });
console.log({ res });

Hierarchy

Implements

Constructors

Properties

aiPrefix: string = "AI"
humanPrefix: string = "Human"
memoryKey: string = "history"
returnMessages: boolean = false
inputKey?: string
outputKey?: string

Accessors

  • get memoryKeys(): string[]
  • Returns string[]

Methods

  • Method to clear the chat history.

    Returns Promise<void>

    Promise that resolves when the chat history has been cleared.

  • Loads the memory variables. It takes an InputValues object as a parameter and returns a Promise that resolves with a MemoryVariables object.

    Parameters

    Returns Promise<MemoryVariables>

    A Promise that resolves with a MemoryVariables object.

  • Method to add user and AI messages to the chat history in sequence.

    Parameters

    • inputValues: InputValues

      The input values from the user.

    • outputValues: OutputValues

      The output values from the AI.

    Returns Promise<void>

    Promise that resolves when the context has been saved.

Generated using TypeDoc