Reducer function for combining two sets of messages in LangGraph's state system.
This reducer handles several tasks:
left and right message inputs to arrays.BaseMessage instances.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.left and right messages together following these rules:
right shares an ID with a message in left:
RemoveMessage, that message (by ID) is marked for removal.left.right does not exist in left:
RemoveMessage, this is considered an error (cannot remove non-existent ID).messagesStateReducer(
left: Messages,
right: Messages
): BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]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)