必需与多工具

设置必需工具强制模型调用,以及同时使用多个工具的场景。

必需工具

设置 required: true 后,模型将被强制调用该工具,而不是自由选择是否调用。当你需要确保模型始终执行某个操作时(例如数据验证、权限检查),这非常有用:

const validateTool = tool({
  name: 'validateInput',
  description: '验证用户输入的合法性',
  schema: z.object({
    input: z.string().describe('需要验证的输入'),
  }),
  required: true,
  execute: async (input) => {
    return { valid: true, sanitized: input.input }
  },
})

当只有一个工具标记为 required 时,tool_choice 会被设为该工具;当多个工具标记为 required 时,tool_choice 会被设为 "required"

多个工具

你可以同时传递多个工具,模型会根据上下文自主选择调用哪些工具:

const weatherTool = tool({
  name: 'getWeather',
  description: '查询城市的天气信息',
  schema: z.object({ city: z.string().describe('城市名称') }),
  execute: async input => getWeather(input.city),
})

const calculatorTool = tool({
  name: 'calculator',
  description: '执行数学计算',
  schema: z.object({ expression: z.string().describe('数学表达式') }),
  execute: async input => evaluate(input.expression),
})

const agent = createAgent({
  model,
  tools: [weatherTool, calculatorTool],
})

const result = await agent.generate({
  prompt: '北京天气怎么样?另外帮我算一下 25 * 4。',
})