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(anthropic): Handle parallel tool result blocks #7386

Merged
merged 2 commits into from
Dec 16, 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
61 changes: 61 additions & 0 deletions libs/langchain-anthropic/src/tests/chat_models-tools.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -625,3 +625,64 @@ test("Can bound and invoke different tool types", async () => {
);
expect(result.tool_calls?.length).toBeGreaterThanOrEqual(1);
});

test("Can call and use two tool calls at once", async () => {
const tool = {
name: "generate_random_joke",
description: "Generate a random joke.",
schema: z.object({
prompt: z.string().describe("The prompt to generate the joke for."),
}),
};
const largeModel = new ChatAnthropic({
model: "claude-3-5-sonnet-latest",
temperature: 0,
}).bindTools([tool]);

const inputMessage = new HumanMessage(
"Generate three (3) random jokes. Please use the generate_random_joke tool, and call it three times in your response to me. Ensure you call the tool three times before responding to me. This is very important."
);

const result = await largeModel.invoke([inputMessage]);
expect(result.tool_calls).toHaveLength(3);

const toolResult1 = new ToolMessage({
tool_call_id: result.tool_calls?.[0].id || "",
name: "generate_random_joke",
content: [
{
type: "text",
text: "This is a joke.",
},
],
});
const toolResult2 = new ToolMessage({
tool_call_id: result.tool_calls?.[1].id || "",
name: "generate_random_joke",
content: [
{
type: "text",
text: "This is the second joke!!",
},
],
});
const toolResult3 = new ToolMessage({
tool_call_id: result.tool_calls?.[2].id || "",
name: "generate_random_joke",
content: "This is the third joke!!",
});

const responseHumanMessage = new HumanMessage(
"Please rate all these jokes on a scale of 1-10. Rate them on how funny you think they are."
);
const result2 = await largeModel.invoke([
inputMessage,
result,
toolResult1,
toolResult2,
toolResult3,
responseHumanMessage,
]);

expect(result2.content.length).toBeGreaterThan(5);
});
5 changes: 5 additions & 0 deletions libs/langchain-anthropic/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ export type AnthropicToolChoice =
| "none"
| string;
export type ChatAnthropicToolType = AnthropicTool | BindToolsInput;
export type AnthropicTextBlockParam = Anthropic.Messages.TextBlockParam;
export type AnthropicImageBlockParam = Anthropic.Messages.ImageBlockParam;
export type AnthropicToolUseBlockParam = Anthropic.Messages.ToolUseBlockParam;
export type AnthropicToolResultBlockParam =
Anthropic.Messages.ToolResultBlockParam;
78 changes: 77 additions & 1 deletion libs/langchain-anthropic/src/utils/message_inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ import {
} from "@langchain/core/messages";
import { ToolCall } from "@langchain/core/messages/tool";
import {
AnthropicImageBlockParam,
AnthropicMessageCreateParams,
AnthropicTextBlockParam,
AnthropicToolResponse,
AnthropicToolResultBlockParam,
AnthropicToolUseBlockParam,
} from "../types.js";

function _formatImage(imageUrl: string) {
Expand Down Expand Up @@ -250,7 +254,79 @@ export function _convertMessagesToAnthropicPayload(
}
});
return {
messages: formattedMessages,
messages: mergeMessages(formattedMessages),
system,
} as AnthropicMessageCreateParams;
}

function mergeMessages(messages: AnthropicMessageCreateParams["messages"]) {
if (!messages || messages.length <= 1) {
return messages;
}

const result: AnthropicMessageCreateParams["messages"] = [];
let currentMessage = messages[0];

const normalizeContent = (
content:
| string
| Array<
| AnthropicTextBlockParam
| AnthropicImageBlockParam
| AnthropicToolUseBlockParam
| AnthropicToolResultBlockParam
>
): Array<
| AnthropicTextBlockParam
| AnthropicImageBlockParam
| AnthropicToolUseBlockParam
| AnthropicToolResultBlockParam
> => {
if (typeof content === "string") {
return [
{
type: "text",
text: content,
},
];
}
return content;
};

const isToolResultMessage = (msg: (typeof messages)[0]) => {
if (msg.role !== "user") return false;

if (typeof msg.content === "string") {
return false;
}

return (
Array.isArray(msg.content) &&
msg.content.every((item) => item.type === "tool_result")
);
};

for (let i = 1; i < messages.length; i += 1) {
const nextMessage = messages[i];

if (
isToolResultMessage(currentMessage) &&
isToolResultMessage(nextMessage)
) {
// Merge the messages by combining their content arrays
currentMessage = {
...currentMessage,
content: [
...normalizeContent(currentMessage.content),
...normalizeContent(nextMessage.content),
],
};
} else {
result.push(currentMessage);
currentMessage = nextMessage;
}
}

result.push(currentMessage);
return result;
}
Loading