Skip to content

Commit 7959da5

Browse files
jonathanfdshntrl
andauthored
fix: ValidationException for blank text blocks in ChatBedrockConverse (#8618)
Co-authored-by: Hunter Lovell <[email protected]>
1 parent 714d106 commit 7959da5

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

libs/langchain-aws/src/common.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -377,23 +377,35 @@ function convertAIMessageToConverseMessage(msg: AIMessage): BedrockMessage {
377377
});
378378
} else if (Array.isArray(msg.content)) {
379379
const concatenatedBlocks = concatenateLangchainReasoningBlocks(msg.content);
380-
const contentBlocks: ContentBlock[] = concatenatedBlocks.map((block) => {
380+
const contentBlocks: ContentBlock[] = [];
381+
concatenatedBlocks.forEach((block) => {
381382
if (block.type === "text" && block.text !== "") {
382-
return {
383-
text: block.text,
384-
};
383+
// Merge whitespace/newlines with previous text blocks to avoid validation errors.
384+
const cleanedText = block.text?.replace(/\n/g, "").trim();
385+
if (cleanedText === "") {
386+
if (contentBlocks.length > 0) {
387+
const mergedTextContent = `${
388+
contentBlocks[contentBlocks.length - 1].text
389+
}${block.text}`;
390+
contentBlocks[contentBlocks.length - 1].text = mergedTextContent;
391+
}
392+
} else {
393+
contentBlocks.push({
394+
text: block.text,
395+
});
396+
}
385397
} else if (block.type === "reasoning_content") {
386-
return {
398+
contentBlocks.push({
387399
reasoningContent: langchainReasoningBlockToBedrockReasoningBlock(
388400
block as MessageContentReasoningBlock
389401
),
390-
};
402+
});
391403
} else if (isDefaultCachePoint(block)) {
392-
return {
404+
contentBlocks.push({
393405
cachePoint: {
394406
type: "default",
395407
},
396-
};
408+
});
397409
} else {
398410
const blockValues = Object.fromEntries(
399411
Object.entries(block).filter(([key]) => key !== "type")

libs/langchain-aws/src/tests/chat_models.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ test("Streaming supports empty string chunks", async () => {
416416
{
417417
contentBlockIndex: 0,
418418
delta: {
419-
text: "Hello ",
419+
text: "Hello",
420420
},
421421
},
422422
{
@@ -425,6 +425,12 @@ test("Streaming supports empty string chunks", async () => {
425425
text: "",
426426
},
427427
},
428+
{
429+
contentBlockIndex: 0,
430+
delta: {
431+
text: " ",
432+
},
433+
},
428434
{
429435
contentBlockIndex: 0,
430436
delta: {

0 commit comments

Comments
 (0)