如何强制工具调用行为
先决条件
本指南假设您熟悉以下概念
为了强制 LLM 选择特定工具,我们可以使用 tool_choice
参数来确保特定行为。首先,让我们定义我们的模型和工具
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const add = tool(
(input) => {
return `${input.a + input.b}`;
},
{
name: "add",
description: "Adds a and b.",
schema: z.object({
a: z.number(),
b: z.number(),
}),
}
);
const multiply = tool(
(input) => {
return `${input.a * input.b}`;
},
{
name: "Multiply",
description: "Multiplies a and b.",
schema: z.object({
a: z.number(),
b: z.number(),
}),
}
);
const tools = [add, multiply];
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "gpt-3.5-turbo",
});
例如,我们可以使用以下代码强制工具调用 multiply 工具
const llmForcedToMultiply = llm.bindTools(tools, {
tool_choice: "Multiply",
});
const multiplyResult = await llmForcedToMultiply.invoke("what is 2 + 4");
console.log(JSON.stringify(multiplyResult.tool_calls, null, 2));
[
{
"name": "Multiply",
"args": {
"a": 2,
"b": 4
},
"type": "tool_call",
"id": "call_d5isFbUkn17Wjr6yEtNz7dDF"
}
]
即使我们传递给它不需要乘法的操作,它仍然会调用工具!
我们还可以通过将 "any"
(或对于 OpenAI 模型,等效的 "required"
)传递给 tool_choice
参数来强制工具至少选择一个工具。
const llmForcedToUseTool = llm.bindTools(tools, {
tool_choice: "any",
});
const anyToolResult = await llmForcedToUseTool.invoke("What day is today?");
console.log(JSON.stringify(anyToolResult.tool_calls, null, 2));
[
{
"name": "add",
"args": {
"a": 2,
"b": 3
},
"type": "tool_call",
"id": "call_La72g7Aj0XHG0pfPX6Dwg2vT"
}
]