fix(react): handle non-concatenable messages (#3536)

This commit is contained in:
David Duong
2025-02-20 21:28:02 +01:00
committed by GitHub
2 changed files with 31 additions and 6 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@langchain/langgraph-sdk",
"version": "0.0.44",
"version": "0.0.45",
"description": "Client library for interacting with the LangGraph API",
"type": "module",
"packageManager": "yarn@1.22.19",
+30 -5
View File
@@ -43,6 +43,7 @@ import {
type BaseMessage,
coerceMessageLikeToMessage,
convertToChunk,
isBaseMessageChunk,
} from "@langchain/core/messages";
class StreamError extends Error {
@@ -60,8 +61,19 @@ class StreamError extends Error {
}
}
function tryConvertToChunk(message: BaseMessage): BaseMessageChunk | null {
try {
return convertToChunk(message);
} catch {
return null;
}
}
class MessageTupleManager {
chunks: Record<string, { chunk?: BaseMessageChunk; index?: number }> = {};
chunks: Record<
string,
{ chunk?: BaseMessageChunk | BaseMessage; index?: number }
> = {};
constructor() {
this.chunks = {};
@@ -76,13 +88,26 @@ class MessageTupleManager {
.toLowerCase() as Message["type"];
}
const chunk = convertToChunk(coerceMessageLikeToMessage(serialized));
const message = coerceMessageLikeToMessage(serialized);
const chunk = tryConvertToChunk(message);
const id = chunk.id;
if (!id) return null;
const id = (chunk ?? message).id;
if (!id) {
console.warn(
"No message ID found for chunk, ignoring in state",
serialized,
);
return null;
}
this.chunks[id] ??= {};
this.chunks[id].chunk = this.chunks[id]?.chunk?.concat(chunk) ?? chunk;
if (chunk) {
const prev = this.chunks[id].chunk;
this.chunks[id].chunk =
(isBaseMessageChunk(prev) ? prev : null)?.concat(chunk) ?? chunk;
} else {
this.chunks[id].chunk = message;
}
return id;
}