@langchain/langgraph
Version:
1 lines • 10.8 kB
Source Map (JSON)
{"version":3,"file":"messages_reducer.cjs","names":["coerceMessageLikeToMessage","RemoveMessage","BaseMessage"],"sources":["../../src/graph/messages_reducer.ts"],"sourcesContent":["import {\n BaseMessage,\n BaseMessageLike,\n coerceMessageLikeToMessage,\n RemoveMessage,\n} from \"@langchain/core/messages\";\nimport { v4 } from \"@langchain/core/utils/uuid\";\n\n/**\n * Special value that signifies the intent to remove all previous messages in the state reducer.\n * Used as the unique identifier for a `RemoveMessage` instance which, when encountered,\n * causes all prior messages to be discarded, leaving only those following this marker.\n */\nexport const REMOVE_ALL_MESSAGES = \"__remove_all__\";\n\n/**\n * Type that represents an acceptable input for the messages state reducer.\n *\n * - Can be a single `BaseMessage` or `BaseMessageLike`.\n * - Can be an array of `BaseMessage` or `BaseMessageLike`.\n */\nexport type Messages =\n | Array<BaseMessage | BaseMessageLike>\n | BaseMessage\n | BaseMessageLike;\n\n/**\n * Reducer function for combining two sets of messages in LangGraph's state system.\n *\n * This reducer handles several tasks:\n * 1. Normalizes both `left` and `right` message inputs to arrays.\n * 2. Coerces any message-like objects into real `BaseMessage` instances.\n * 3. Ensures all messages have unique, stable IDs by generating missing ones.\n * 4. If a `RemoveMessage` instance is encountered in `right` with the ID `REMOVE_ALL_MESSAGES`,\n * all previous messages are discarded and only the subsequent messages in `right` are returned.\n * 5. Otherwise, merges `left` and `right` messages together following these rules:\n * - If a message in `right` shares an ID with a message in `left`:\n * - If it is a `RemoveMessage`, that message (by ID) is marked for removal.\n * - If it is a normal message, it replaces the message with the same ID from `left`.\n * - If a message in `right` **does not exist** in `left`:\n * - If it is a `RemoveMessage`, this is considered an error (cannot remove non-existent ID).\n * - Otherwise, the message is appended.\n * - Messages flagged for removal are omitted from the final output.\n *\n * @param left - The existing array (or single message) of messages from current state.\n * @param right - The new array (or single message) of messages to be applied.\n * @returns A new array of `BaseMessage` objects representing the updated state.\n *\n * @throws Error if a `RemoveMessage` is used to delete a message with an ID that does not exist in the merged list.\n *\n * @example\n * ```ts\n * const msg1 = new AIMessage(\"hello\");\n * const msg2 = new HumanMessage(\"hi\");\n * const removal = new RemoveMessage({ id: msg1.id });\n * const newState = messagesStateReducer([msg1], [msg2, removal]);\n * // newState will only contain msg2 (msg1 is removed)\n * ```\n */\nexport function messagesStateReducer(\n left: Messages,\n right: Messages\n): BaseMessage[] {\n // Ensure both left and right are arrays\n const leftArray = Array.isArray(left) ? left : [left];\n const rightArray = Array.isArray(right) ? right : [right];\n\n // Convert all input to BaseMessage instances\n const leftMessages = (leftArray as BaseMessageLike[]).map(\n coerceMessageLikeToMessage\n );\n const rightMessages = (rightArray as BaseMessageLike[]).map(\n coerceMessageLikeToMessage\n );\n\n // Assign missing IDs to any message in the left array\n for (const m of leftMessages) {\n if (m.id === null || m.id === undefined) {\n m.id = v4();\n m.lc_kwargs.id = m.id;\n }\n }\n\n // Assign missing IDs and check for \"remove all\" marker in right array\n let removeAllIdx: number | undefined;\n for (let i = 0; i < rightMessages.length; i += 1) {\n const m = rightMessages[i];\n if (m.id === null || m.id === undefined) {\n m.id = v4();\n m.lc_kwargs.id = m.id;\n }\n\n // If RemoveMessage with special REMOVE_ALL_MESSAGES id is found\n if (RemoveMessage.isInstance(m) && m.id === REMOVE_ALL_MESSAGES) {\n removeAllIdx = i;\n }\n }\n\n // If remove-all is present, all previous messages are wiped; return only subsequent ones\n if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1);\n\n // Begin normal merging logic\n const merged = [...leftMessages];\n const mergedById = new Map(merged.map((m, i) => [m.id, i]));\n const idsToRemove = new Set();\n\n for (const m of rightMessages) {\n const existingIdx = mergedById.get(m.id);\n if (existingIdx !== undefined) {\n // Case: updating or removing an existing message by id\n if (RemoveMessage.isInstance(m)) {\n idsToRemove.add(m.id);\n } else {\n idsToRemove.delete(m.id);\n merged[existingIdx] = m;\n }\n } else {\n // Case: inserting a completely new message\n if (RemoveMessage.isInstance(m)) {\n throw new Error(\n `Attempting to delete a message with an ID that doesn't exist ('${m.id}')`\n );\n }\n mergedById.set(m.id, merged.length);\n merged.push(m);\n }\n }\n\n // Remove any messages whose IDs are marked for removal\n return merged.filter((m) => !idsToRemove.has(m.id));\n}\n\n/**\n * **Experimental.** Batch reducer for use with `DeltaChannel`.\n *\n * Processes all writes in one pass — dedup by ID and `RemoveMessage`\n * tombstoning — without calling {@link messagesStateReducer}.\n *\n * This reducer is batching-invariant, as required by `DeltaChannel`:\n * `reducer(reducer(state, xs), ys) === reducer(state, xs.concat(ys))`.\n *\n * A `RemoveMessage` carrying the {@link REMOVE_ALL_MESSAGES} sentinel id\n * clears all messages accumulated so far (prior state plus earlier writes in\n * the same batch) and keeps only the messages that follow it, mirroring\n * {@link messagesStateReducer}. Clearing happens in the same single linear\n * pass, so the batching-invariant still holds.\n *\n * Raw object / string inputs are coerced to typed `BaseMessage` objects so\n * that HTTP-driven graphs work without a separate coercion step. This is not\n * full {@link messagesStateReducer} parity — unknown-id `RemoveMessage`\n * errors and missing-id UUID assignment are not handled here.\n *\n * @param state - The current accumulated list of messages.\n * @param writes - Batch of writes, each a single message-like or an array.\n * @returns The new accumulated list of messages.\n *\n * @example\n * ```typescript\n * import { DeltaChannel, messagesDeltaReducer } from \"@langchain/langgraph\";\n *\n * const channel = new DeltaChannel(messagesDeltaReducer);\n * ```\n */\nexport function messagesDeltaReducer(\n state: BaseMessage[],\n writes: Messages[]\n): BaseMessage[] {\n // Each write is either an array of message-likes or a single message-like.\n // Only arrays flatten; everything else is one message.\n const flat: BaseMessageLike[] = [];\n for (const w of writes) {\n if (Array.isArray(w)) {\n flat.push(...(w as BaseMessageLike[]));\n } else {\n flat.push(w as BaseMessageLike);\n }\n }\n\n // Steady state: the reducer's own output is already typed, so skip coercion\n // on state when the first element is a BaseMessage. Only raw input (initial\n // objects, deserialized blobs) hits the slow path.\n const stateMsgs: BaseMessage[] =\n state.length > 0 && BaseMessage.isInstance(state[0])\n ? state\n : (state as BaseMessageLike[]).map(coerceMessageLikeToMessage);\n const msgs: BaseMessage[] = flat.map(coerceMessageLikeToMessage);\n\n const index = new Map<string, number>();\n for (let i = 0; i < stateMsgs.length; i += 1) {\n const mid = stateMsgs[i].id;\n if (mid != null) index.set(mid, i);\n }\n\n const result: (BaseMessage | null)[] = [...stateMsgs];\n for (const msg of msgs) {\n const mid = msg.id;\n if (RemoveMessage.isInstance(msg) && mid === REMOVE_ALL_MESSAGES) {\n // Discard everything accumulated so far (prior state and earlier writes\n // in this batch); only messages following the sentinel are kept. Doing\n // this inline keeps the reducer batching-invariant.\n result.length = 0;\n index.clear();\n } else if (mid == null) {\n result.push(msg);\n } else if (RemoveMessage.isInstance(msg)) {\n if (index.has(mid)) {\n result[index.get(mid)!] = null;\n index.delete(mid);\n }\n } else if (index.has(mid)) {\n result[index.get(mid)!] = msg;\n } else {\n index.set(mid, result.length);\n result.push(msg);\n }\n }\n return result.filter((m): m is BaseMessage => m !== null);\n}\n"],"mappings":";;;;;;;;AAaA,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CnC,SAAgB,qBACd,MACA,OACe;CAEf,MAAM,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK;CACrD,MAAM,aAAa,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM;CAGzD,MAAM,eAAgB,UAAgC,IACpDA,yBAAAA,2BACD;CACD,MAAM,gBAAiB,WAAiC,IACtDA,yBAAAA,2BACD;AAGD,MAAK,MAAM,KAAK,aACd,KAAI,EAAE,OAAO,QAAQ,EAAE,OAAO,KAAA,GAAW;AACvC,IAAE,MAAA,GAAA,2BAAA,KAAS;AACX,IAAE,UAAU,KAAK,EAAE;;CAKvB,IAAI;AACJ,MAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK,GAAG;EAChD,MAAM,IAAI,cAAc;AACxB,MAAI,EAAE,OAAO,QAAQ,EAAE,OAAO,KAAA,GAAW;AACvC,KAAE,MAAA,GAAA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