跳到主要内容

voice.addTools()

addTools() 方法为 Voice Provider 配备模型可在实时交互期间调用的 Tool(函数)。语音助手可以使用这些 Tool 搜索信息或执行计算,也可以与外部系统交互。

使用示例
使用示例的直接链接

import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

// Define tools
const weatherTool = createTool({
id: 'getWeather',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string().describe('The city and state, e.g. San Francisco, CA'),
}),
outputSchema: z.object({
message: z.string(),
}),
execute: async inputData => {
// Fetch weather data from an API
const response = await fetch(
`https://api.weather.com?location=${encodeURIComponent(inputData.location)}`,
)
const data = await response.json()
return {
message: `The current temperature in ${inputData.location} is ${data.temperature}°F with ${data.conditions}.`,
}
},
})

// Initialize a real-time voice provider
const voice = new OpenAIRealtimeVoice({
realtimeConfig: {
model: 'gpt-5.1-realtime',
apiKey: process.env.OPENAI_API_KEY,
},
})

// Add tools to the voice provider
voice.addTools({
getWeather: weatherTool,
})

// Connect to the real-time service
await voice.connect()

参数
参数的直接链接


tools:

ToolsInput
包含可由语音模型调用的 Tool 定义的对象

返回值
返回值的直接链接

此方法不返回值。

注意事项
注意事项的直接链接

  • Tool 必须遵循 Mastra Tool 格式,包含名称、描述、输入 schema 和 execute 函数
  • 此方法主要用于支持函数调用的实时 Voice Provider
  • 如果在不支持 Tool 的 Voice Provider 上调用此方法,它会记录警告且不执行任何操作
  • 通过此方法添加的 Tool 通常会与关联 Agent 提供的 Tool 合并
  • 为获得最佳效果,请在开始对话前(调用 connect() 前)添加 Tool
  • 当模型决定使用 Tool 时,Voice Provider 会自动调用 Tool 处理程序
  • 多次调用 addTools() 可能会替换现有 Tool,也可能会与现有 Tool 合并,具体取决于 Provider 的实现