voice.addTools()
addTools() 方法為語音 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 及執行函數
- 此方法主要用於支援函數呼叫的實時語音 Provider
- 如在不支援 Tool 的語音 Provider 上呼叫,系統會記錄警告,而不會執行任何操作
- 使用此方法加入的 Tool 通常會與相關 Agent 所提供的任何 Tool 合併使用
- 為獲得最佳效果,請在開始對話前(即呼叫
connect()前)加入 Tool - 當模型決定使用 Tool 時,語音 Provider 會自動處理 Tool handler 的呼叫
- 多次呼叫
addTools()可能會取代現有 Tool,或與其合併,實際行為視乎 Provider 的實作方式