LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
LangGraph SDK
  • Client
  • Auth
  • React
  • Logging
  • React Ui
  • Server
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
  • Store
LangGraph Checkpoint Redis
  • Shallow
  • Store
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
  • Cli
LangGraph API
LangGraph CLI
LangGraph CUA
  • Utils
LangGraph Supervisor
LangGraph Swarm
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangGraph
WebChannelsPregelPrebuiltRemote
LangGraph SDK
ClientAuthReactLoggingReact UiServer
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
Store
LangGraph Checkpoint Redis
ShallowStore
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
Cli
LangGraph API
LangGraph CLI
LangGraph CUA
Utils
LangGraph Supervisor
LangGraph Swarm
Language
Theme
JavaScript@langchain/langgraphwebmessagesStateReducer
Function●Since v0.3

messagesStateReducer

Reducer function for combining two sets of messages in LangGraph's state system.

This reducer handles several tasks:

  1. Normalizes both left and right message inputs to arrays.
  2. Coerces any message-like objects into real BaseMessage instances.
  3. Ensures all messages have unique, stable IDs by generating missing ones.
  4. If a RemoveMessage instance is encountered in right with the ID REMOVE_ALL_MESSAGES, all previous messages are discarded and only the subsequent messages in right are returned.
  5. Otherwise, merges left and right messages together following these rules:
    • If a message in right shares an ID with a message in left:
      • If it is a RemoveMessage, that message (by ID) is marked for removal.
      • If it is a normal message, it replaces the message with the same ID from left.
    • If a message in right does not exist in left:
      • If it is a RemoveMessage, this is considered an error (cannot remove non-existent ID).
      • Otherwise, the message is appended.
    • Messages flagged for removal are omitted from the final output.
Copy
messagesStateReducer(
  left: Messages,
  right: Messages
): BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]

Used in Docs

  • Use the graph API

Parameters

NameTypeDescription
left*Messages

The existing array (or single message) of messages from current state.

right*Messages

The new array (or single message) of messages to be applied.

Example

Copy
const msg1 = new AIMessage("hello");
const msg2 = new HumanMessage("hi");
const removal = new RemoveMessage({ id: msg1.id });
const newState = messagesStateReducer([msg1], [msg2, removal]);
// newState will only contain msg2 (msg1 is removed)
View source on GitHub