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

如何通过Dialogflow ES Python SDK添加训练短语并关联现有实体

使用Dialogflow ES Python SDK关联训练短语与现有实体

核心原理

Dialogflow的训练短语由多个TrainingPhrasePart组成,普通文本仅需指定text字段;需要关联实体的文本片段,额外指定实体的完整资源名称和别名,即可将文本标记关联到现有实体。

具体步骤

  • 步骤1:获取目标实体的完整资源名称
    你需要先拿到现有实体的完整资源路径,格式为:
projects/[YOUR_PROJECT_ID]/agent/entityTypes/[ENTITY_ID]

如果不知道实体ID,可以通过SDK查询实体列表获取:

from google.cloud import dialogflow_v2 as dialogflow

client = dialogflow.EntityTypesClient()
parent = f"projects/[YOUR_PROJECT_ID]/agent"
response = client.list_entity_types(parent=parent)

for entity_type in response:
    print(f"实体名称: {entity_type.display_name}, 资源名称: {entity_type.name}")

运行后复制目标实体的name字段值即可。

  • 步骤2:构建带实体关联的训练短语
    创建TrainingPhrase对象时,将短语拆分为多个TrainingPhrasePart:
    • 普通文本片段:仅设置text
    • 需关联实体的片段:设置text(短语中的实体文本)、entity_type_name(步骤1获取的实体完整资源名称)、alias(实体的显示名称,或自定义别名)

示例代码:

# 假设现有实体是"restaurant_type",完整资源名称为:
entity_full_name = "projects/your-project-id/agent/entityTypes/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# 构建训练短语的各个片段
parts = [
    dialogflow.Intent.TrainingPhrase.Part(text="我想找一家"),
    dialogflow.Intent.TrainingPhrase.Part(
        text="川菜馆",
        entity_type_name=entity_full_name,
        alias="restaurant_type"
    ),
    dialogflow.Intent.TrainingPhrase.Part(text="")
]

# 创建训练短语对象
training_phrase = dialogflow.Intent.TrainingPhrase(
    parts=parts,
    type=dialogflow.Intent.TrainingPhrase.Type.EXAMPLE
)
  • 步骤3:将训练短语添加到目标意图
    把构建好的训练短语添加到指定意图的training_phrases列表中,更新意图:
intent_client = dialogflow.IntentsClient()
intent_path = intent_client.intent_path("[YOUR_PROJECT_ID]", "[YOUR_AGENT_ID]", "[TARGET_INTENT_ID]")

# 获取现有意图
intent = intent_client.get_intent(name=intent_path)

# 添加新的训练短语
intent.training_phrases.append(training_phrase)

# 更新意图
update_mask = {"paths": ["training_phrases"]}
response = intent_client.update_intent(intent=intent, update_mask=update_mask)

print(f"训练短语已添加并关联实体,意图更新成功: {response.name}")

常见问题排查

  • 实体关联不生效:检查entity_type_name是否为完整资源路径,而非仅实体显示名称;alias需与实体名称一致,或在意图的实体参数中已配置对应别名。
  • 短语文本拼接错误:确保parts列表的文本顺序与完整短语一致,避免出现断句或遗漏。
  • 权限问题:确认SDK使用的服务账号拥有dialogflow.intents.update权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:58:44