Skip to content

Commit

Permalink
fix(community): bedrock parsing array content/tool blocks (#7244)
Browse files Browse the repository at this point in the history
  • Loading branch information
bracesproul authored Nov 22, 2024
1 parent fc6b925 commit 7fd5667
Showing 1 changed file with 20 additions and 13 deletions.
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

0 comments on commit 7fd5667

Please sign in to comment.