Skip to content

Commit

Permalink
aws[patch]: Fix error when processing empty string chunk conent (#6137)
Browse files Browse the repository at this point in the history
* aws[patch]: Fix error when processing empty string chunk conent

* chore: lint files
  • Loading branch information
bracesproul authored Jul 18, 2024
1 parent 9b6a764 commit 7b8891f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
11 changes: 6 additions & 5 deletions libs/langchain-aws/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export function handleConverseStreamContentBlockDelta(
if (!contentBlockDelta.delta) {
throw new Error("No delta found in content block.");
}
if (contentBlockDelta.delta.text) {
if (typeof contentBlockDelta.delta.text === "string") {
return new ChatGenerationChunk({
text: contentBlockDelta.delta.text,
message: new AIMessageChunk({
Expand All @@ -404,11 +404,12 @@ export function handleConverseStreamContentBlockDelta(
}),
});
} else {
const unsupportedField = Object.entries(contentBlockDelta.delta).filter(
([_, value]) => !!value
);
throw new Error(
`Unsupported content block type: ${unsupportedField[0][0]}`
`Unsupported content block type(s): ${JSON.stringify(
contentBlockDelta.delta,
null,
2
)}`
);
}
}
Expand Down
40 changes: 39 additions & 1 deletion libs/langchain-aws/src/tests/chat_models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ import {
HumanMessage,
AIMessage,
ToolMessage,
AIMessageChunk,
} from "@langchain/core/messages";
import { convertToConverseMessages } from "../common.js";
import { concat } from "@langchain/core/utils/stream";
import {
convertToConverseMessages,
handleConverseStreamContentBlockDelta,
} from "../common.js";

test("convertToConverseMessages works", () => {
const messages = [
Expand Down Expand Up @@ -71,3 +76,36 @@ test("convertToConverseMessages works", () => {
url: "https://weather.com",
});
});

test("Streaming supports empty string chunks", async () => {
const contentBlocks = [
{
contentBlockIndex: 0,
delta: {
text: "Hello ",
},
},
{
contentBlockIndex: 0,
delta: {
text: "",
},
},
{
contentBlockIndex: 0,
delta: {
text: "world!",
},
},
];

let finalChunk: AIMessageChunk | undefined;
for (const block of contentBlocks) {
const chunk = handleConverseStreamContentBlockDelta(block).message;
finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);
}

expect(finalChunk).toBeDefined();
if (!finalChunk) return;
expect(finalChunk.content).toBe("Hello world!");
});

0 comments on commit 7b8891f

Please sign in to comment.