Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aws[patch]: Fix error when processing empty string chunk conent #6137

Merged
merged 2 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!");
});
Loading