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

Dialogflow意图添加新训练短语时旧语料丢失的技术求助

解决Dialogflow Intent训练短语被覆盖的问题
  • 问题本质:Dialogflow的UpdateIntent接口默认是全量替换Intent数据,如果你直接给TrainingPhrases字段赋值新的短语列表,原有内容会被完全覆盖,而非追加。

  • 修复方案:

    1. 先获取目标Intent的现有训练短语
    2. 合并新短语与原有短语(建议去重,避免重复训练数据)
    3. 调用UpdateIntent时,指定只更新trainingPhrases字段,避免影响Intent其他配置
  • 修正后的Go代码示例:

import (
	"context"
	"fmt"
	dialogflow "cloud.google.com/go/dialogflow/apiv2"
	dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

func addTrainingPhrase(projectID, intentID string, newPhrases []string) error {
	ctx := context.Background()
	client, err := dialogflow.NewIntentsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewIntentsClient error: %v", err)
	}
	defer client.Close()

	// 获取现有Intent数据
	getReq := &dialogflowpb.GetIntentRequest{
		Name: fmt.Sprintf("projects/%s/agent/intents/%s", projectID, intentID),
	}
	existingIntent, err := client.GetIntent(ctx, getReq)
	if err != nil {
		return fmt.Errorf("GetIntent error: %v", err)
	}

	// 合并新短语到原有列表(去重逻辑可按需调整)
	existingPhrases := existingIntent.GetTrainingPhrases()
	phraseSet := make(map[string]bool)
	// 记录原有短语文本
	for _, tp := range existingPhrases {
		phraseText := ""
		for _, part := range tp.GetParts() {
			phraseText += part.GetText()
		}
		phraseSet[phraseText] = true
	}
	// 添加不重复的新短语
	for _, text := range newPhrases {
		if !phraseSet[text] {
			newTp := &dialogflowpb.Intent_TrainingPhrase{
				Parts: []*dialogflowpb.Intent_TrainingPhrase_Part{
					{Text: text},
				},
				Type: dialogflowpb.Intent_TrainingPhrase_EXAMPLE,
			}
			existingPhrases = append(existingPhrases, newTp)
			phraseSet[text] = true
		}
	}
	existingIntent.TrainingPhrases = existingPhrases

	// 更新Intent,仅指定training_phrases字段更新
	updateReq := &dialogflowpb.UpdateIntentRequest{
		Intent: existingIntent,
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{"training_phrases"},
		},
	}
	_, err = client.UpdateIntent(ctx, updateReq)
	if err != nil {
		return fmt.Errorf("UpdateIntent error: %v", err)
	}

	return nil
}
  • 关键注意点:
    • 必须使用FieldMask指定training_phrases(遵循Protobuf字段蛇形命名规则),否则会全量替换整个Intent的所有配置
    • 去重逻辑可避免训练短语重复,提升Intent识别效率
    • 调用GetIntent时要确保获取到完整的Intent数据,包含所有现有训练短语

内容的提问来源于stack exchange,提问作者Sakeezt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:22:36