Mastering RunnableWithMessageHistory in LangChain.js
Aug 25,2026

Introduction

So far in our LangChain.js series, we've learned how to build powerful Runnable workflows.

We've covered:

  • RunnableSequence

  • RunnableParallel

  • RunnableLambda

  • RunnablePassthrough

  • RunnableAssign

  • RunnableBranch

  • RunnableWithFallbacks

These components allow us to build workflows that are sequential, parallel, conditional, reusable, and resilient.

But there is one major capability missing.

Conversation memory.

Consider a normal AI request:

User:
What is React?

AI:
React is a JavaScript library...

Now the user asks:

User:
Who created it?

A stateless application might not know what "it" refers to.

The model receives only:

Who created it?

It doesn't automatically know that the previous conversation was:

User:
What is React?

AI:
React is a JavaScript library...

A chatbot needs to remember previous messages.

The workflow should become:

User Message
      ↓
Conversation History
      ↓
Current Message
      ↓
LLM
      ↓
AI Response
      ↓
Save to History

This is where:

RunnableWithMessageHistory

becomes useful.

In this article, we'll learn:

  • What conversation memory means

  • Stateless vs stateful AI applications

  • What RunnableWithMessageHistory is

  • Why message history is important

  • HumanMessage

  • AIMessage

  • MessagesPlaceholder

  • InMemoryChatMessageHistory

  • Creating a basic chatbot

  • Managing sessionId

  • Maintaining multiple conversations

  • OpenAI integration

  • Gemini integration

  • How messages are stored

  • How history is retrieved

  • How history is updated

  • Clearing conversation history

  • Common mistakes

  • Production considerations

  • Database-backed conversation memory

  • Best practices

Let's get started.


What Is Conversation Memory?

Conversation memory means maintaining previous messages so that an AI model can understand the context of an ongoing conversation.

For example:

User:
What is Node.js?

AI:
Node.js is a JavaScript runtime.

User:
Who created it?

AI:
Node.js was originally created by Ryan Dahl.

The second question:

Who created it?

depends on the previous message.

Without conversation history, the model may not know what "it" means.

With history:

HumanMessage:
What is Node.js?

AIMessage:
Node.js is a JavaScript runtime.

HumanMessage:
Who created it?

the model can understand the context.


Stateless vs Stateful AI

Before learning RunnableWithMessageHistory, we need to understand two important concepts.

Stateless Application

A stateless request doesn't remember previous requests.

For example:

Request 1
   ↓
LLM
   ↓
Response

Request 2
   ↓
LLM
   ↓
Response

Each request is independent.

For example:

await model.invoke(
  "What is React?"
);

await model.invoke(
  "Who created it?"
);

The second call does not automatically receive the first conversation.


Stateful Application

A stateful chatbot maintains conversation history.

Message 1
   ↓
History

Message 2
   ↓
History

Message 3
   ↓
History

      ↓

LLM receives conversation

For example:

User:
What is React?

AI:
React is a JavaScript library.

User:
Who created it?

AI:
React was created by Jordan Walke.

The chatbot can understand the context because previous messages are available.


Important: LLMs Don't Automatically Remember

This is one of the most important concepts to understand.

An LLM API call is generally independent.

When you call:

await model.invoke(
  "What is React?"
);

and later:

await model.invoke(
  "Who created it?"
);

the second request doesn't automatically contain the first conversation.

Your application needs to provide the previous messages.

Conceptually:

Application
    ↓
Load History
    ↓
Current Message
    ↓
Prompt
    ↓
LLM

RunnableWithMessageHistory helps manage this process.


What Is RunnableWithMessageHistory?

RunnableWithMessageHistory is a LangChain Runnable wrapper that adds message-history management around another Runnable.

Its job is essentially:

1. Identify conversation/session
2. Load previous messages
3. Pass messages to the Runnable
4. Receive the response
5. Store the new messages

Conceptually:

User Message
     ↓
sessionId
     ↓
Load History
     ↓
Previous Messages
     +
Current Message
     ↓
Chat Model
     ↓
AI Response
     ↓
Save Messages

This allows us to turn a normal LangChain chain into a stateful conversational chain.


Why Do We Need RunnableWithMessageHistory?

Without message history:

User → LLM
User → LLM
User → LLM

Every request is independent.

With message history:

User
 ↓
History
 ↓
LLM
 ↓
History
 ↓
LLM
 ↓
History

This is useful for:

  • AI chatbots

  • Customer support

  • AI tutors

  • Coding assistants

  • Interview assistants

  • Personal assistants

  • Multi-turn conversations


Important Concepts Before Starting

Before writing the complete implementation, let's understand four important message types/components:

  1. HumanMessage

  2. AIMessage

  3. MessagesPlaceholder

  4. InMemoryChatMessageHistory


HumanMessage

HumanMessage represents a message sent by the user.

Example:

import {
  HumanMessage,
} from "@langchain/core/messages";

const message =
  new HumanMessage(
    "What is Node.js?"
  );

Conceptually:

HumanMessage
     ↓
User's message

AIMessage

AIMessage represents a response generated by an AI model.

Example:

import {
  AIMessage,
} from "@langchain/core/messages";

const message =
  new AIMessage(
    "Node.js is a JavaScript runtime."
  );

Conceptually:

AIMessage
   ↓
AI response

HumanMessage + AIMessage

A conversation can be represented as:

[
  new HumanMessage(
    "What is React?"
  ),

  new AIMessage(
    "React is a JavaScript library."
  ),

  new HumanMessage(
    "Who created it?"
  ),

  new AIMessage(
    "React was created by Jordan Walke."
  ),
]

This is the foundation of chat history.


MessagesPlaceholder

Now we need a way to insert a dynamic list of messages into a prompt.

That's what:

MessagesPlaceholder

does.

For example:

import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

Create a chat prompt:

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a helpful AI assistant.",
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

The important part is:

new MessagesPlaceholder(
  "history"
)

It tells LangChain:

Insert the conversation history here.


Understanding MessagesPlaceholder

Suppose our history is:

[
  new HumanMessage(
    "What is React?"
  ),

  new AIMessage(
    "React is a JavaScript library."
  ),
]

The prompt effectively becomes:

System:
You are a helpful AI assistant.

Human:
What is React?

AI:
React is a JavaScript library.

Human:
Who created it?

This is exactly what we need for a conversational application.


InMemoryChatMessageHistory

For learning and simple examples, we can store messages in memory.

LangChain provides:

InMemoryChatMessageHistory

Import it:

import {
  InMemoryChatMessageHistory,
} from "@langchain/core/chat_history";

Create a history:

const history =
  new InMemoryChatMessageHistory();

Add a user message:

await history.addUserMessage(
  "What is React?"
);

Add an AI message:

await history.addAIMessage(
  "React is a JavaScript library."
);

Retrieve messages:

const messages =
  await history.getMessages();

console.log(messages);

Why Is It Called InMemory?

Because the messages are stored in the application's memory.

For example:

Node.js Process
     │
     └── Conversation History

If the Node.js process restarts:

Node.js Restart
      ↓
Memory Cleared
      ↓
History Lost

Therefore, InMemoryChatMessageHistory is useful for:

  • Learning

  • Development

  • Testing

  • Simple prototypes

For production applications, persistent storage is usually required.

We'll discuss that later.


Project Setup

Let's create a new project.

mkdir runnable-message-history
cd runnable-message-history
npm init -y

Install the required packages:

npm install @langchain/core @langchain/openai @langchain/google-genai dotenv

Project Structure

runnable-message-history/
│
├── index.js
├── .env
├── package.json
└── .gitignore

Configure Environment Variables

Create .env:

OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key

Create .gitignore:

node_modules/
.env

Never commit API keys.


Step 1 — Initialize OpenAI

Let's start with OpenAI.

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

Step 2 — Create ChatPromptTemplate

Import:

import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

Create the prompt:

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      `You are a helpful AI assistant.
Remember the conversation context
and answer clearly.`,
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

Let's understand this carefully.


Understanding the Prompt

Our prompt contains three sections:

System Message
      ↓
Conversation History
      ↓
Current User Message

In code:

ChatPromptTemplate.fromMessages([
  ["system", "..."],

  new MessagesPlaceholder(
    "history"
  ),

  ["human", "{input}"],
]);

The placeholder is dynamically replaced with previous messages.


Step 3 — Create the Basic Chain

Now connect the prompt and model:

const chain =
  prompt.pipe(model);

At this point:

Input
 ↓
Prompt
 ↓
OpenAI
 ↓
AIMessage

But this chain doesn't remember anything yet.

We need to add message history.


Step 4 — Create Message History Storage

Import:

import {
  InMemoryChatMessageHistory,
} from "@langchain/core/chat_history";

We'll create a store.

const messageHistory =
  new InMemoryChatMessageHistory();

But if we want multiple users, we need multiple histories.

For that, we'll use a Map.


Creating a Session Store

const store =
  new Map();

The idea is:

sessionId
    ↓
ChatMessageHistory

For example:

"user-1" → History A
"user-2" → History B
"user-3" → History C

Step 5 — Create getMessageHistory()

Create a function:

const getMessageHistory =
  (sessionId) => {

    if (!store.has(sessionId)) {
      store.set(
        sessionId,
        new InMemoryChatMessageHistory()
      );
    }

    return store.get(sessionId);
  };

Let's understand this.

If the session doesn't exist:

store.has(sessionId)

returns:

false

So we create a new history:

store.set(
  sessionId,
  new InMemoryChatMessageHistory()
);

If it already exists, we return the existing history.


Why Do We Need sessionId?

Imagine two users:

User A:
What is React?

and:

User B:
What is React?

They need separate conversations.

We can identify them using:

sessionId

For example:

session-101
session-202

So:

session-101 → User A History

session-202 → User B History

This prevents conversations from mixing.


Step 6 — Import RunnableWithMessageHistory

import {
  RunnableWithMessageHistory,
} from "@langchain/core/runnables";

Now wrap our chain.

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

This is the central part of today's article.


Understanding RunnableWithMessageHistory Configuration

Let's break it down.

runnable

runnable: chain

This is the actual chain that should process the request.

Our chain is:

Prompt
 ↓
OpenAI

getMessageHistory

getMessageHistory

This function tells LangChain:

Given a session ID, where can I find the conversation history?

For example:

const getMessageHistory =
  (sessionId) => {
    ...
  };

inputMessagesKey

inputMessagesKey: "input"

Our current user message is stored under:

{
  input: "What is React?"
}

historyMessagesKey

historyMessagesKey: "history"

This must match:

new MessagesPlaceholder(
  "history"
)

This is very important.

These names need to match:

historyMessagesKey
        ↓
     "history"
        ↓
MessagesPlaceholder
        ↓
     "history"

Step 7 — Invoke the Chain

Now invoke the chain:

const response =
  await conversationalChain.invoke(
    {
      input:
        "What is React?",
    },
    {
      configurable: {
        sessionId:
          "session-1",
      },
    }
  );

console.log(
  response.content
);

Notice that sessionId is passed through:

configurable: {
  sessionId: "session-1"
}

This tells LangChain which conversation history to use.


First Request

The first request is:

User:
What is React?

There is no history yet.

So the model receives:

System:
You are a helpful AI assistant.

Human:
What is React?

The AI responds:

AI:
React is a JavaScript library...

The message history is updated.

Now the history contains:

Human:
What is React?

AI:
React is a JavaScript library...

Second Request

Now ask:

const response =
  await conversationalChain.invoke(
    {
      input:
        "Who created it?",
    },
    {
      configurable: {
        sessionId:
          "session-1",
      },
    }
  );

console.log(
  response.content
);

The model now receives:

System:
You are a helpful AI assistant.

Human:
What is React?

AI:
React is a JavaScript library...

Human:
Who created it?

The model understands:

"it" = React

and can respond appropriately.


Complete Conversation Flow

The workflow is:

First Request
     ↓
session-1
     ↓
History
     ↓
"What is React?"
     ↓
OpenAI
     ↓
AI Response
     ↓
Save History

Second request:

"Who created it?"
     ↓
session-1
     ↓
Load Existing History
     ↓
Previous Messages
     +
Current Message
     ↓
OpenAI
     ↓
Response
     ↓
Save History

Complete OpenAI Example

Here is the complete implementation.

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

import {
  InMemoryChatMessageHistory,
} from "@langchain/core/chat_history";

import {
  RunnableWithMessageHistory,
} from "@langchain/core/runnables";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      `You are a helpful AI assistant.
Remember the conversation context
and answer clearly.`,
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

const chain =
  prompt.pipe(model);

const store =
  new Map();

const getMessageHistory =
  (sessionId) => {

    if (!store.has(sessionId)) {
      store.set(
        sessionId,
        new InMemoryChatMessageHistory()
      );
    }

    return store.get(sessionId);
  };

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

const sessionId =
  "session-1";

const response1 =
  await conversationalChain.invoke(
    {
      input:
        "What is React?",
    },
    {
      configurable: {
        sessionId,
      },
    }
  );

console.log(
  "AI:",
  response1.content
);

const response2 =
  await conversationalChain.invoke(
    {
      input:
        "Who created it?",
    },
    {
      configurable: {
        sessionId,
      },
    }
  );

console.log(
  "AI:",
  response2.content
);

The important part is that both requests use:

sessionId: "session-1"

Therefore, they belong to the same conversation.


Multiple Sessions

Now let's create two different conversations.

Session 1

const session1 =
  "user-1";

Ask:

await conversationalChain.invoke(
  {
    input:
      "What is React?",
  },
  {
    configurable: {
      sessionId: session1,
    },
  }
);

Session 2

const session2 =
  "user-2";

Ask:

await conversationalChain.invoke(
  {
    input:
      "What is Node.js?",
  },
  {
    configurable: {
      sessionId: session2,
    },
  }
);

Now the histories are completely separate:

user-1
  ↓
React Conversation

user-2
  ↓
Node.js Conversation

Why Session IDs Matter

Without session IDs:

User A
   ↓
Shared History
   ↑
User B

This would be a serious problem.

User A could see context from User B.

With session IDs:

User A
   ↓
session-A
   ↓
History A


User B
   ↓
session-B
   ↓
History B

Each conversation is isolated.


Session IDs in a Real Application

In a web application, the session ID might come from:

  • Authenticated user ID

  • Conversation ID

  • Chat ID

  • UUID

  • Database record ID

For example:

const sessionId =
  req.body.chatId;

Then:

await conversationalChain.invoke(
  {
    input: req.body.message,
  },
  {
    configurable: {
      sessionId,
    },
  }
);

This is a common architecture for a backend chatbot API.


RunnableWithMessageHistory with Gemini

The same concept works with Gemini.

Import:

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

Create the model:

const model =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

The prompt remains the same:

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a helpful AI assistant.",
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

Create the chain:

const chain =
  prompt.pipe(model);

Then use the same:

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

Invoke:

const response =
  await conversationalChain.invoke(
    {
      input:
        "What is Node.js?",
    },
    {
      configurable: {
        sessionId:
          "gemini-session-1",
      },
    }
  );

console.log(
  response.content
);

The architecture doesn't change.

Only the model changes.


OpenAI and Gemini Comparison

OpenAI

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

Gemini

const model =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

Everything else can remain essentially the same:

ChatPromptTemplate
       ↓
MessagesPlaceholder
       ↓
Model
       ↓
RunnableWithMessageHistory

This is another example of why LangChain's Runnable architecture is useful.


Understanding the Internal Workflow

Let's visualize what happens internally.

When we call:

await conversationalChain.invoke(
  {
    input: "Who created it?"
  },
  {
    configurable: {
      sessionId: "session-1"
    }
  }
);

LangChain roughly needs to perform these steps:

1. Read sessionId
       ↓
2. Get history
       ↓
3. Load previous messages
       ↓
4. Insert history into prompt
       ↓
5. Add current user message
       ↓
6. Call model
       ↓
7. Receive AI response
       ↓
8. Update message history

This is the key reason RunnableWithMessageHistory is useful.

It handles the history integration around the Runnable.


Inspecting Message History

We can inspect the stored messages.

const history =
  getMessageHistory(
    "session-1"
  );

const messages =
  await history.getMessages();

console.log(messages);

You'll get message objects similar to:

[
  HumanMessage {
    content: "What is React?"
  },

  AIMessage {
    content:
      "React is a JavaScript library..."
  },

  HumanMessage {
    content: "Who created it?"
  },

  AIMessage {
    content:
      "React was created by..."
  }
]

This is extremely useful for debugging.


HumanMessage and AIMessage in History

The conversation is represented as a sequence of messages:

HumanMessage
     ↓
AIMessage
     ↓
HumanMessage
     ↓
AIMessage

For example:

[
  new HumanMessage(
    "What is Node.js?"
  ),

  new AIMessage(
    "Node.js is a JavaScript runtime."
  ),

  new HumanMessage(
    "Where is it used?"
  ),

  new AIMessage(
    "It is commonly used for..."
  ),
]

The history is essentially the conversation state.


Adding Messages Manually

You can also add messages directly.

const history =
  new InMemoryChatMessageHistory();

await history.addUserMessage(
  "What is React?"
);

await history.addAIMessage(
  "React is a JavaScript library."
);

Then:

const messages =
  await history.getMessages();

console.log(messages);

This can be useful when restoring an existing conversation.


Clearing History

Sometimes you need to clear a conversation.

For example:

store.delete(
  "session-1"
);

Now a new history will be created the next time that session is used.

Alternatively, if you have the history object:

const history =
  getMessageHistory(
    "session-1"
  );

await history.clear();

After clearing:

session-1
   ↓
Empty History

This can be useful for a:

"New Chat"

button in a UI.


Building a Chat API

Now let's think about how this would look in a real backend.

Suppose the frontend sends:

POST /chat

with:

{
  "sessionId": "abc-123",
  "message": "What is React?"
}

The backend can call:

const response =
  await conversationalChain.invoke(
    {
      input:
        req.body.message,
    },
    {
      configurable: {
        sessionId:
          req.body.sessionId,
      },
    }
  );

Return:

{
  "response": "React is a JavaScript library..."
}

The next request:

{
  "sessionId": "abc-123",
  "message": "Who created it?"
}

uses the same session:

abc-123
   ↓
Same Conversation

Therefore the model can understand the context.


Building a Multi-User Chatbot

Imagine:

User A
  ↓
chat-001
  ↓
History A

User B
  ↓
chat-002
  ↓
History B

User C
  ↓
chat-003
  ↓
History C

The application can use:

const store =
  new Map();

and:

const getMessageHistory =
  (sessionId) => {

    if (!store.has(sessionId)) {
      store.set(
        sessionId,
        new InMemoryChatMessageHistory()
      );
    }

    return store.get(sessionId);
  };

Each session gets its own history.


Conversation Memory vs Long-Term Memory

These are related but different concepts.

Conversation Memory

Stores messages from the current conversation.

User
 ↓
AI
 ↓
User
 ↓
AI

Example:

"What is React?"
"Who created it?"
"When was it released?"

Long-Term Memory

Stores information that may be useful across different conversations.

For example:

User prefers JavaScript examples.
User works with React.
User prefers concise explanations.

This usually requires a more deliberate storage and retrieval architecture.

RunnableWithMessageHistory primarily addresses conversation/message history, not arbitrary long-term user memory.


Message History Can Become Large

There is an important problem with conversation history.

Suppose the user has 500 messages:

Message 1
Message 2
Message 3
...
Message 500

If we send the entire history to the model every time:

500 messages
   ↓
Prompt
   ↓
LLM

the request can become:

  • Expensive

  • Slow

  • Large

  • Difficult to manage

It can also eventually exceed the model's context window.

Therefore, production applications often need strategies for controlling history.


History Management Strategies

Common approaches include:

1. Keep the latest N messages

For example:

Keep last 20 messages

2. Summarize older messages

Instead of:

Message 1
Message 2
...
Message 100

store:

Summary of previous conversation
+
Recent messages

3. Use token-based trimming

Keep the history within a specific token budget.


4. Use retrieval

Store older conversation information externally and retrieve only relevant parts.

These approaches become increasingly important in production applications.


InMemoryChatMessageHistory Limitations

InMemoryChatMessageHistory is excellent for learning.

But it has a major limitation:

Node.js Process
     ↓
Memory

If the application restarts:

Restart
  ↓
Memory Lost

This means it isn't suitable by itself for persistent production chat history.


Production Message History

For production applications, you generally want persistent storage.

Possible options include:

  • PostgreSQL

  • Redis

  • MongoDB

  • MySQL

  • DynamoDB

  • Other databases

  • Dedicated message-history stores

The architecture becomes:

User
 ↓
Node.js API
 ↓
RunnableWithMessageHistory
 ↓
Database
 ↓
Conversation History

For example:

chat-123
   ↓
Database
   ↓
Messages

When the user sends a new message:

Load chat-123
     ↓
Previous Messages
     ↓
Current Message
     ↓
LLM
     ↓
Save New Messages

RunnableWithMessageHistory with a Database

The exact storage implementation depends on the database and LangChain integration you're using.

The important abstraction is:

getMessageHistory(sessionId)

Instead of:

return new InMemoryChatMessageHistory();

you could implement a history provider that loads messages from persistent storage.

Conceptually:

const getMessageHistory =
  async (sessionId) => {

    const messages =
      await database.getMessages(
        sessionId
      );

    return createHistory(messages);
  };

The rest of your Runnable workflow can remain largely unchanged.

This separation is one of the useful aspects of the design.


Important: Session ID Is Not the Message

This is a common beginner confusion.

Consider:

{
  input: "What is React?"
}

This is the message.

While:

{
  configurable: {
    sessionId: "session-1"
  }
}

identifies the conversation.

Think:

sessionId
   ↓
Which conversation?

input
   ↓
What did the user say?

Session ID vs User ID

They are not necessarily the same.

A user can have multiple conversations.

For example:

User ID:
user-101

Chat 1:
chat-001

Chat 2:
chat-002

Chat 3:
chat-003

Therefore, a conversation ID is often a better session identifier than the user's ID alone.

You might model:

userId
   ↓
multiple chat sessions

RunnableWithMessageHistory with ChatPromptTemplate

This combination is extremely common:

ChatPromptTemplate
       ↓
MessagesPlaceholder
       ↓
Chat Model
       ↓
RunnableWithMessageHistory

The prompt controls how history is presented to the model.

The history wrapper controls where the history comes from and how it is maintained.

This distinction is important.


Example with System Instructions

We can have a system instruction:

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      `
You are a senior JavaScript developer.

Always:
- Explain concepts clearly.
- Provide practical examples.
- Use modern JavaScript.
`,
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

Now the system instruction remains consistent across the conversation while the history changes dynamically.


Example Conversation

First:

User:
What is a closure?

AI:

A closure is a function that remembers
variables from its outer scope...

Next:

User:
Can you show an example?

The model receives the history:

Human:
What is a closure?

AI:
A closure is a function...

Human:
Can you show an example?

It understands what "an example" refers to.


RunnableWithMessageHistory + Output Parser

We can also add an output parser.

For example:

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

const parser =
  new StringOutputParser();

const chain =
  prompt
    .pipe(model)
    .pipe(parser);

Then:

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

The final response will be a string instead of an AIMessage.


Complete OpenAI Example with StringOutputParser

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

import {
  InMemoryChatMessageHistory,
} from "@langchain/core/chat_history";

import {
  RunnableWithMessageHistory,
} from "@langchain/core/runnables";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const prompt =
  ChatPromptTemplate.fromMessages([
    [
      "system",
      "You are a helpful AI assistant.",
    ],

    new MessagesPlaceholder(
      "history"
    ),

    [
      "human",
      "{input}",
    ],
  ]);

const parser =
  new StringOutputParser();

const chain =
  prompt
    .pipe(model)
    .pipe(parser);

const store =
  new Map();

const getMessageHistory =
  (sessionId) => {

    if (!store.has(sessionId)) {
      store.set(
        sessionId,
        new InMemoryChatMessageHistory()
      );
    }

    return store.get(sessionId);
  };

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

const sessionId =
  "chat-101";

const response1 =
  await conversationalChain.invoke(
    {
      input:
        "What is Node.js?",
    },
    {
      configurable: {
        sessionId,
      },
    }
  );

console.log(
  "AI:",
  response1
);

const response2 =
  await conversationalChain.invoke(
    {
      input:
        "What is it used for?",
    },
    {
      configurable: {
        sessionId,
      },
    }
  );

console.log(
  "AI:",
  response2
);

The Complete Architecture

The final architecture is:

                ┌──────────────────────┐
                │   sessionId          │
                └──────────┬───────────┘
                           ↓
                    Message History
                           ↓
User Input ────────────────┤
                           ↓
                  MessagesPlaceholder
                           ↓
                   ChatPromptTemplate
                           ↓
                       AI Model
                           ↓
                    Output Parser
                           ↓
                      AI Response
                           ↓
                   Save to History

This is the basic architecture behind many conversational AI applications.


Common Beginner Mistakes

Mistake 1 — Forgetting sessionId

If you call:

await conversationalChain.invoke(
  {
    input: "Hello"
  }
);

without the required configurable session information, the message-history wrapper cannot identify which conversation history to use.

Always provide the appropriate session configuration.


Mistake 2 — Mismatching History Names

Suppose you have:

new MessagesPlaceholder(
  "history"
)

but configure:

historyMessagesKey:
  "messages"

These don't match.

Use:

new MessagesPlaceholder(
  "history"
)

and:

historyMessagesKey:
  "history"

Mistake 3 — Mixing Conversations

Don't use one fixed session ID for every user:

sessionId: "chat"

for all requests.

Otherwise:

User A
   ↓
chat
   ↑
User B

can share the same history.

Generate or retrieve a unique conversation identifier.


Mistake 4 — Using In-Memory Storage in Production Without Understanding the Limitation

Remember:

InMemory
   ↓
Process Memory
   ↓
Restart
   ↓
History Lost

For production, use persistent storage.


Mistake 5 — Sending Unlimited History

A conversation can grow indefinitely.

Don't assume you can send every previous message forever.

Eventually you'll need:

  • Trimming

  • Summarization

  • Token management

  • Retrieval


Mistake 6 — Confusing Memory with Model Training

Conversation history does not mean you're training the model.

The model isn't permanently learning:

"What is React?"

Instead, your application sends the previous messages again as context.

Think:

Stored History
      ↓
Prompt Context
      ↓
Model

not:

Stored History
      ↓
Model Training

Best Practices

1. Use a unique conversation/session ID

For example:

chat-uuid-123

This isolates conversations.


2. Separate user identity from conversation identity

A user may have multiple conversations.

User
 ├── Chat 1
 ├── Chat 2
 └── Chat 3

3. Use persistent storage for production

Don't depend solely on:

InMemoryChatMessageHistory

for production systems.


4. Limit conversation history

Large histories can increase:

  • Cost

  • Latency

  • Token usage

Use appropriate history management.


5. Keep system instructions separate

Use:

[
  "system",
  "You are a helpful assistant."
]

and keep dynamic conversation history inside:

new MessagesPlaceholder(
  "history"
)

6. Keep your history provider independent

Your application should ideally be able to switch from:

InMemory

to:

Redis

or:

PostgreSQL

without rewriting the entire AI workflow.


RunnableWithMessageHistory vs RunnableWithFallbacks

We learned RunnableWithFallbacks in the previous article.

These solve completely different problems.

RunnableWithFallbacks

Handles failures:

Primary
   ↓
Failure
   ↓
Fallback

RunnableWithMessageHistory

Handles conversation state:

Message
   ↓
History
   ↓
Model
   ↓
New History

They can also be combined.

For example:

User
 ↓
Message History
 ↓
OpenAI
 ↓
Failure
 ↓
Gemini
 ↓
Save Response

This creates a more resilient conversational application.


RunnableWithMessageHistory + RunnableWithFallbacks

Conceptually:

const reliableModel =
  openAIModel.withFallbacks({
    fallbacks: [
      geminiModel,
    ],
  });

const chain =
  prompt
    .pipe(reliableModel)
    .pipe(parser);

const conversationalChain =
  new RunnableWithMessageHistory({
    runnable: chain,

    getMessageHistory,

    inputMessagesKey: "input",

    historyMessagesKey:
      "history",
  });

Now:

Conversation History
       ↓
Prompt
       ↓
OpenAI
       ↓
Failure?
       ↓
Gemini
       ↓
Response
       ↓
Save History

This is a useful production pattern.


Real-World Use Case: Customer Support Chatbot

Imagine an e-commerce chatbot.

User:

Where is my order?

AI:

Your order is currently in transit.

User:

When will it arrive?

The chatbot needs the previous context.

The conversation history might contain:

Human:
Where is my order?

AI:
Your order is currently in transit.

Human:
When will it arrive?

Without history, "it" can be ambiguous.

With message history, the chatbot can understand the context.


Real-World Use Case: Coding Assistant

User:

Create a React counter component.

AI:

Here's a React counter component...

User:

Now add TypeScript.

The AI needs the previous response.

Conversation history provides:

Human:
Create a React counter component.

AI:
...

Human:
Now add TypeScript.

The assistant can understand what needs to be modified.


Real-World Use Case: Interview Assistant

User:

Explain useMemo.

AI:

useMemo is a React hook...

User:

Give me an interview example.

The assistant understands that the user is still talking about useMemo.

This is exactly the type of multi-turn interaction where message history is important.


Real-World Use Case: AI Tutor

Conversation:

Student:
What is a closure?

AI:
A closure is...

Student:
Can you explain it with a real-world example?

AI:
Sure...

Student:
What about in React?

The tutor can follow the topic because previous messages are available.


Message History Lifecycle

A useful mental model is:

1. User sends message
        ↓
2. Identify session
        ↓
3. Load history
        ↓
4. Add current message
        ↓
5. Send context to model
        ↓
6. Receive AI response
        ↓
7. Save user + AI messages
        ↓
8. Return response

This is the lifecycle you should remember.


The Bigger Picture

At this stage of our LangChain.js series, we've moved from simple chains to stateful workflows.

Our architecture now looks like:

RunnableSequence
        ↓
RunnableParallel
        ↓
RunnableLambda
        ↓
RunnablePassthrough
        ↓
RunnableAssign
        ↓
RunnableBranch
        ↓
RunnableWithFallbacks
        ↓
RunnableWithMessageHistory

Each component solves a different problem.


What's Next?

Our chatbot can now remember conversations.

But there is another important requirement in production applications.

We often want to make Runnable behavior configurable at runtime.

For example:

Model:
OpenAI / Gemini

Temperature:
0.2 / 0.7

Provider:
OpenAI / Gemini

User configuration:
Different settings

Instead of hardcoding these values, we can make them configurable.

LangChain provides mechanisms for creating configurable Runnables.

This leads us to the next topic:

Blog 17 — Configurable Runnables

We'll learn how to dynamically configure Runnable components and make our AI workflows more flexible and reusable.


Final Thoughts

RunnableWithMessageHistory is one of the most important concepts when building conversational AI applications.

The core problem it solves is simple:

How do we maintain conversation context across multiple requests?

Instead of:

Request 1 → Model

Request 2 → Model

Request 3 → Model

we can build:

Request 1
    ↓
History
    ↓
Model
    ↓
Save

Request 2
    ↓
Load History
    ↓
Model
    ↓
Save

Request 3
    ↓
Load History
    ↓
Model
    ↓
Save

The key components are:

RunnableWithMessageHistory
        +
InMemoryChatMessageHistory
        +
MessagesPlaceholder
        +
sessionId

Remember the responsibilities:

sessionId
    ↓
Identifies conversation

MessageHistory
    ↓
Stores conversation

MessagesPlaceholder
    ↓
Places history into prompt

RunnableWithMessageHistory
    ↓
Connects history with Runnable

Once you understand these concepts, you can build:

  • Stateful chatbots

  • Customer support assistants

  • AI tutors

  • Coding assistants

  • Interview assistants

  • Multi-user conversational applications

And when combined with fallbacks, branches, parallel workflows, and sequences, you can start designing production-oriented AI systems.

Happy Coding! 🚀