如何用Node.js编程修改Dialogflow Essentials的谷歌助手音色与显示名
可行方案说明
你可以根据自己的需求选择以下两种实现方案:
场景1:单会话动态指定显示名、音色(推荐,无需修改全局配置)
如果你的需求是不同会话/不同触发条件下使用不同的显示名和音色,不需要修改Dialogflow全局Agent配置,直接在webhook返回的响应 payload 中指定对应参数即可,实现成本更低,不会影响其他会话。
实现步骤
- 在你的webhook逻辑中,构造Google Assistant专属的响应payload,指定显示名和语音配置
- 把payload添加到agent的返回内容中
修改后的示例代码
const express = require('express'); const app = express(); const df = require('dialogflow-fulfillment'); app.post('/', express.json(), (req, res) => { const agent = new df.WebhookClient({ request: req, response: res }); function getTime(agent) { var breakfastTime = agent.context.get('breakfast_time'); // 示例:根据breakfastTime的参数值判断使用的音色和显示名 let voiceName, displayName; if(breakfastTime.parameters.time < '10:00') { voiceName = 'cmn-CN-Wavenet-A'; displayName = '早餐小助手'; } else { voiceName = 'cmn-CN-Wavenet-B'; displayName = '通用小助手'; } // 构造Google Assistant的payload const payload = { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: "Thank you, Have a great day", displayText: "Thank you, Have a great day" } } ] }, // 指定语音配置 voice: { name: voiceName, ssmlGender: "NEUTRAL" }, // 指定显示名称 agentInfo: { name: displayName } } }; agent.add(new df.Payload(agent.ACTIONS_ON_GOOGLE, payload)); } var intentMap = new Map(); intentMap.set('breakfast', getTime); agent.handleRequest(intentMap); })
场景2:全局修改Agent的显示名、音色
如果你需要批量修改Dialogflow Agent的全局配置,替换控制台手动操作的流程,可以调用Dialogflow官方的Node.js客户端库实现。
实现步骤
- 安装依赖包:
npm install @google-cloud/dialogflow - 在Google Cloud IAM控制台为你的服务账号分配
Dialogflow Agent Editor权限,下载服务账号的JSON密钥文件到项目中 - 编写修改Agent配置的代码,示例如下:
const { AgentsClient } = require('@google-cloud/dialogflow'); const agentsClient = new AgentsClient({ keyFilename: './你的服务账号密钥文件名.json' }); async function updateAgentConfig(projectId, displayName, voiceName) { const agentPath = agentsClient.projectAgentPath(projectId); const agent = { name: agentPath, displayName: displayName, voiceConfig: { voiceName: voiceName, ssmlGender: "SSML_VOICE_GENDER_NEUTRAL" } }; const request = { agent: agent, updateMask: { paths: ['displayName', 'voiceConfig'] } }; const [response] = await agentsClient.updateAgent(request); console.log('Agent配置更新完成', response); } // 调用示例:updateAgentConfig('你的GCP项目ID', '新的显示名称', 'cmn-CN-Wavenet-C')
注意事项
- 场景2修改的是全局配置,修改后所有会话都会生效,不适合需要按会话动态切换的需求
- 音色名称需要和你Agent使用的语言匹配,中文音色可选用cmn-CN开头的Wavenet系列音色,英文可选用en-US开头的对应音色
内容的提问来源于stack exchange,提问作者Felix Christo
相关产品推荐
相关产品推荐

