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