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

fix(community): bedrock parsing array content/tool blocks #7244

Merged
merged 3 commits into from
Nov 22, 2024
Merged
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
33 changes: 20 additions & 13 deletions libs/langchain-community/src/utils/bedrock/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ function _formatContent(content: MessageContent) {
if (typeof content === "string") {
return content;
} else {
const contentBlocks = content.map((contentPart) => {
const contentBlocks = content.flatMap((contentPart) => {
if (contentPart.type === "image_url") {
let source;
if (typeof contentPart.image_url === "string") {
Expand All @@ -133,7 +133,13 @@ function _formatContent(content: MessageContent) {
type: "image" as const, // Explicitly setting the type as "image"
source,
};
} else if (contentPart.type === "text") {
} else if (
contentPart.type === "text" ||
contentPart.type === "text_delta"
) {
if (contentPart.text === "") {
return [];
}
// Assuming contentPart is of type MessageContentText here
return {
type: "text" as const, // Explicitly setting the type as "text"
Expand All @@ -148,6 +154,8 @@ function _formatContent(content: MessageContent) {
...contentPart,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;
} else if (contentPart.type === "input_json_delta") {
return [];
} else {
throw new Error("Unsupported message content format");
}
Expand Down Expand Up @@ -204,21 +212,20 @@ export function formatMessagesForAnthropic(messages: BaseMessage[]): {
};
}
} else {
const { content } = message;
const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>
content.find(
(contentPart) =>
contentPart.type === "tool_use" && contentPart.id === toolCall.id
)
);
if (hasMismatchedToolCalls) {
console.warn(
`The "tool_calls" field on a message is only respected if content is a string.`
const formattedContent = _formatContent(message.content);
if (Array.isArray(formattedContent)) {
const formattedToolsContent = message.tool_calls.map(
_convertLangChainToolCallToAnthropic
);
return {
role,
content: [...formattedContent, ...formattedToolsContent],
};
}

return {
role,
content: _formatContent(message.content),
content: formattedContent,
};
}
} else {
Expand Down
Loading