You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API为Dialogflow CX意图新增训练短语(NodeJS)

在Node.js中通过Dialogflow CX API新增意图训练短语

可以实现给指定意图新增训练短语,无需覆盖现有内容。核心思路是先获取目标意图的当前训练短语列表,将新短语追加后再调用更新接口,具体步骤如下:

实现步骤

  1. 获取目标意图的现有训练短语
    使用Dialogflow CX的IntentsClient.getIntent()方法,传入意图的完整资源名称,获取当前意图的所有配置,从中提取trainingPhrases数组。

  2. 合并现有短语与新短语
    将新构造的训练短语对象追加到现有数组中,注意保持Dialogflow CX要求的训练短语格式(每个短语需包含parts数组,用于存储文本内容)。

  3. 调用更新接口并指定更新范围
    使用IntentsClient.updateIntent()方法,通过updateMask指定仅更新training_phrases字段,避免覆盖意图的其他配置。

代码示例

const { IntentsClient } = require('@google-cloud/dialogflow-cx');

async function addTrainingPhraseToIntent() {
  // 替换为你的实际配置
  const projectId = '你的项目ID';
  const location = '你的区域'; // 例如 'us-central1'
  const agentId = '你的代理ID';
  const intentId = '目标意图ID';
  const newPhraseText = '需要新增的训练短语内容';

  // 初始化客户端
  const intentsClient = new IntentsClient({ 
    apiEndpoint: `${location}-dialogflow.googleapis.com` 
  });

  // 构造意图的完整资源路径
  const intentPath = intentsClient.intentPath(projectId, location, agentId, intentId);

  // 获取现有意图数据
  const [existingIntent] = await intentsClient.getIntent({ name: intentPath });

  // 合并训练短语:现有短语 + 新短语
  const updatedTrainingPhrases = [...(existingIntent.trainingPhrases || [])];
  const newTrainingPhrase = {
    parts: [{ text: newPhraseText }],
    type: 'EXAMPLE' // 可选,默认即为EXAMPLE,也可设为TEMPLATE
  };
  updatedTrainingPhrases.push(newTrainingPhrase);

  // 配置更新参数
  const updateMask = { paths: ['training_phrases'] };
  const intentToUpdate = {
    name: intentPath,
    trainingPhrases: updatedTrainingPhrases
  };

  // 执行更新
  const [response] = await intentsClient.updateIntent({
    intent: intentToUpdate,
    updateMask: updateMask
  });

  console.log(`训练短语已成功添加,更新后的意图:${response.name}`);
}

// 执行函数
addTrainingPhraseToIntent().catch(console.error);

关键注意事项

  • 必须先获取现有训练短语再合并,若直接设置trainingPhrases会覆盖原有内容;
  • updateMask的paths需使用下划线分隔的字段名(training_phrases),而非驼峰式;
  • 若需添加带参数的训练短语,可在parts数组中加入包含parameterId的对象,例如:
    const newTrainingPhrase = {
      parts: [
        { text: '我要预订' },
        { text: '明天', parameterId: 'date' },
        { text: '的房间' }
      ]
    };
    

内容的提问来源于stack exchange,提问作者Saer El Masri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:12:44