Skip to main content

Adding memory (state)

Chains can be initialized with a Memory object, which will persist data across calls to the chain. This makes a Chain stateful.

Get started

npm install @langchain/openai
import { ChatOpenAI } from "@langchain/openai";
import { ConversationChain } from "langchain/chains";
import { BufferMemory } from "langchain/memory";

const chat = new ChatOpenAI({});

const memory = new BufferMemory();

// This particular chain automatically initializes a BufferMemory instance if none is provided,
// but we pass it explicitly here. It also has a default prompt.
const chain = new ConversationChain({ llm: chat, memory });

const res1 = await
"Answer briefly. What are the first 3 colors of a rainbow?"

// The first three colors of a rainbow are red, orange, and yellow.

const res2 = await"And the next 4?");

// The next four colors of a rainbow are green, blue, indigo, and violet.

Essentially, BaseMemory defines an interface of how LangChain stores memory. It allows reading of stored data through loadMemoryVariables method and storing new data through saveContext method. You can learn more about it in the Memory section.

Help us out by providing feedback on this documentation page: