Skip to main content

如何禁用并行工具调用

前提条件

本指南假定您已熟悉以下概念:

仅适用于 OpenAI

此 API 目前仅受 OpenAI 支持。

OpenAI 模型默认执行并行工具调用。这意味着,如果我们提出类似 "东京、纽约和芝加哥的天气如何?" 的问题,并且我们有一个获取天气的工具,它将会并行调用该工具三次。我们可以通过使用 parallel_tool_call 调用选项来强制其仅调用一次工具。

首先,让我们设置我们的工具和模型:

import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
import { tool } from "@langchain/core/tools";

const adderTool = tool(
async ({ a, b }) => {
return a + b;
},
{
name: "add",
description: "Adds a and b",
schema: z.object({
a: z.number(),
b: z.number(),
}),
}
);

const multiplyTool = tool(
async ({ a, b }) => {
return a * b;
},
{
name: "multiply",
description: "Multiplies a and b",
schema: z.object({
a: z.number(),
b: z.number(),
}),
}
);

const tools = [adderTool, multiplyTool];

const llm = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0,
});

现在让我们快速展示一个关于如何禁用并行工具调用的示例:

const llmWithTools = llm.bindTools(tools, { parallel_tool_calls: false });

const result = await llmWithTools.invoke(
"Please call the first tool two times"
);

result.tool_calls;
[
{
name: 'add',
args: { a: 5, b: 3 },
type: 'tool_call',
id: 'call_5bKOYerdQU6J5ERJJYnzYsGn'
}
]

如我们所见,尽管我们明确告诉模型调用两次工具,但通过禁用并行工具调用,模型被限制只能调用一个。

将此与不将 parallel_tool_calls 设为 false 时调用模型的情况进行比较:

const llmWithNoBoundParam = llm.bindTools(tools);

const result2 = await llmWithNoBoundParam.invoke(
"Please call the first tool two times"
);

result2.tool_calls;
[
{
name: 'add',
args: { a: 1, b: 2 },
type: 'tool_call',
id: 'call_Ni0tF0nNtY66BBwB5vEP6oI4'
},
{
name: 'add',
args: { a: 3, b: 4 },
type: 'tool_call',
id: 'call_XucnTCfFqP1JBs3LtbOq5w3d'
}
]

你会看到你得到了两个工具调用。

你也可以像这样在运行时传入参数:

const result3 = await llmWithNoBoundParam.invoke(
"Please call the first tool two times",
{
parallel_tool_calls: false,
}
);

result3.tool_calls;
[
{
name: 'add',
args: { a: 1, b: 2 },
type: 'tool_call',
id: 'call_TWo6auul71NUg1p0suzBKARt'
}
]

相关内容


Was this page helpful?


You can also leave detailed feedback on GitHub.