Skip to main content

voice.addTools()

addTools() 方法为语音提供商配备了工具(函数),模型在实时交互中可以调用这些工具。这使得语音助手能够执行诸如查找信息、进行计算或与外部系统交互等操作。

🌐 The addTools() method equips a voice provider with tools (functions) that can be called by the model during real-time interactions. This enables voice assistants to perform actions like searching for information, making calculations, or interacting with external systems.

使用示例
Direct link to 使用示例

🌐 Usage Example

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();

参数
Direct link to 参数

🌐 Parameters


tools:

ToolsInput
Object containing tool definitions that can be called by the voice model

返回值
Direct link to 返回值

🌐 Return Value

此方法不返回值。

🌐 This method does not return a value.

注意
Direct link to 注意

🌐 Notes

  • 工具必须遵循 Mastra 工具格式,包括名称、描述、输入架构和执行功能
  • 该方法主要用于支持函数调用的实时语音提供商
  • 如果调用不支持工具的语音提供商,它将记录一个警告并且不会执行任何操作
  • 通过这种方法添加的工具通常会与相关代理提供的任何工具结合使用
  • 为了获得最佳效果,请在开始对话之前添加工具(在调用 connect() 之前)
  • 当模型决定使用工具时,语音提供商将自动处理工具处理程序的调用
  • 多次调用 addTools() 可能会根据提供商的实现方式,替换或合并现有工具