使用 API 管理意图

意图决定系统可理解哪些用户请求以及要采取怎样的操作。在大多数情况下,您将使用 Dialogflow ES 控制台来管理意图。在高级场景中,您可能希望使用 API 来管理意图。本页介绍如何使用 API 创建、列出和删除意图。

准备工作

在阅读本指南之前,请先完成以下事项:

  1. 阅读 Dialogflow 基础知识
  2. 执行设置步骤

创建代理

如果尚未创建代理,请立即创建一个:

  1. 转到 Dialogflow ES 控制台
  2. 如果系统要求登录 Dialogflow 控制台,请登录。如需了解详情,请参阅 Dialogflow 控制台概览
  3. 点击左侧边栏菜单中的创建代理 (Create Agent)。如果您已有其他代理,请点击代理名称,滚动到底部,然后点击创建新代理 (Create new agent)。
  4. 输入您的代理名称、默认语言和默认时区。
  5. 如果您已经创建了项目,请输入该项目。如果要允许 Dialogflow 控制台创建项目,请选择创建新 Google 项目 (Create a new Google project)。
  6. 点击创建 (Create) 按钮。

将示例文件导入代理

本指南中的步骤对您的代理进行了假设,因此您需要导入为本指南准备的代理。 导入时,这些步骤使用“恢复”(restore) 选项,该选项会覆盖所有代理设置、意图和实体。

如需导入文件,请按以下步骤操作:

  1. 下载 room-booking-agent.zip 文件。
  2. 转到 Dialogflow ES 控制台
  3. 选择您的代理。
  4. 点击代理名称旁边的设置 按钮。
  5. 选择导出和导入 (Export and Import) 标签页。
  6. 选择从 ZIP 文件恢复 (Restore from ZIP),然后按照说明恢复下载的 zip 文件。

使用 IntentView 返回所有意图数据

创建、列出或获取意图时,意图数据会返回给调用方。默认情况下,此返回数据为缩写形式。 以下示例使用此默认值。

如需检索所有意图数据,必须将 IntentView 参数设置为 INTENT_VIEW_FULL。如需了解详情,请参阅意图类型方法。

创建意图

以下示例展示如何创建意图。如需了解详情,请参阅意图参考

REST

如需为代理创建意图,请对 intent 资源调用 create 方法。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents

请求 JSON 正文:

{
  "displayName": "ListRooms",
  "priority": 500000,
  "webhookState": "WEBHOOK_STATE_UNSPECIFIED",
  "trainingPhrases": [
    {
      "type": "EXAMPLE",
      "parts": [
        {
          "text": "What rooms are available at 10am today?"
        }
      ]
    }
  ],
  "action": "listRooms",
  "messages": [
    {
      "text": {
        "text": [
          "Here are the available rooms:"
        ]
      }
    }
  ]
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

intents 后面的路径段包含新的意图 ID。

Go

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

func CreateIntent(projectID, displayName string, trainingPhraseParts, messageTexts []string) error {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return clientErr
	}
	defer intentsClient.Close()

	if projectID == "" || displayName == "" {
		return errors.New(fmt.Sprintf("Received empty project (%s) or intent (%s)", projectID, displayName))
	}

	parent := fmt.Sprintf("projects/%s/agent", projectID)

	var targetTrainingPhrases []*dialogflowpb.Intent_TrainingPhrase
	var targetTrainingPhraseParts []*dialogflowpb.Intent_TrainingPhrase_Part
	for _, partString := range trainingPhraseParts {
		part := dialogflowpb.Intent_TrainingPhrase_Part{Text: partString}
		targetTrainingPhraseParts = []*dialogflowpb.Intent_TrainingPhrase_Part{&part}
		targetTrainingPhrase := dialogflowpb.Intent_TrainingPhrase{Type: dialogflowpb.Intent_TrainingPhrase_EXAMPLE, Parts: targetTrainingPhraseParts}
		targetTrainingPhrases = append(targetTrainingPhrases, &targetTrainingPhrase)
	}

	intentMessageTexts := dialogflowpb.Intent_Message_Text{Text: messageTexts}
	wrappedIntentMessageTexts := dialogflowpb.Intent_Message_Text_{Text: &intentMessageTexts}
	intentMessage := dialogflowpb.Intent_Message{Message: &wrappedIntentMessageTexts}

	target := dialogflowpb.Intent{DisplayName: displayName, WebhookState: dialogflowpb.Intent_WEBHOOK_STATE_UNSPECIFIED, TrainingPhrases: targetTrainingPhrases, Messages: []*dialogflowpb.Intent_Message{&intentMessage}}

	request := dialogflowpb.CreateIntentRequest{Parent: parent, Intent: &target}

	_, requestErr := intentsClient.CreateIntent(ctx, &request)
	if requestErr != nil {
		return requestErr
	}

	return nil
}

Java

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * Create an intent of the given intent type
 *
 * @param displayName The display name of the intent.
 * @param projectId Project/Agent Id.
 * @param trainingPhrasesParts Training phrases.
 * @param messageTexts Message texts for the agent's response when the intent is detected.
 * @return The created Intent.
 */
public static Intent createIntent(
    String displayName,
    String projectId,
    List<String> trainingPhrasesParts,
    List<String> messageTexts)
    throws ApiException, IOException {
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    // Set the project agent name using the projectID (my-project-id)
    AgentName parent = AgentName.of(projectId);

    // Build the trainingPhrases from the trainingPhrasesParts
    List<TrainingPhrase> trainingPhrases = new ArrayList<>();
    for (String trainingPhrase : trainingPhrasesParts) {
      trainingPhrases.add(
          TrainingPhrase.newBuilder()
              .addParts(Part.newBuilder().setText(trainingPhrase).build())
              .build());
    }

    // Build the message texts for the agent's response
    Message message =
        Message.newBuilder().setText(Text.newBuilder().addAllText(messageTexts).build()).build();

    // Build the intent
    Intent intent =
        Intent.newBuilder()
            .setDisplayName(displayName)
            .addMessages(message)
            .addAllTrainingPhrases(trainingPhrases)
            .build();

    // Performs the create intent request
    Intent response = intentsClient.createIntent(parent, intent);
    System.out.format("Intent created: %s\n", response);

    return response;
  }
}

Node.js

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The Project ID to use, e.g. 'YOUR_GCP_ID';
// const displayName = 'The display name of the intent, e.g. 'MAKE_RESERVATION';
// const trainingPhrasesParts = 'Training phrases, e.g. 'How many people are staying?';
// const messageTexts = 'Message texts for the agent's response when the intent is detected, e.g. 'Your reservation has been confirmed';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates the Intent Client
const intentsClient = new dialogflow.IntentsClient();

async function createIntent() {
  // Construct request

  // The path to identify the agent that owns the created intent.
  const agentPath = intentsClient.projectAgentPath(projectId);

  const trainingPhrases = [];

  trainingPhrasesParts.forEach(trainingPhrasesPart => {
    const part = {
      text: trainingPhrasesPart,
    };

    // Here we create a new training phrase for each provided part.
    const trainingPhrase = {
      type: 'EXAMPLE',
      parts: [part],
    };

    trainingPhrases.push(trainingPhrase);
  });

  const messageText = {
    text: messageTexts,
  };

  const message = {
    text: messageText,
  };

  const intent = {
    displayName: displayName,
    trainingPhrases: trainingPhrases,
    messages: [message],
  };

  const createIntentRequest = {
    parent: agentPath,
    intent: intent,
  };

  // Create the intent
  const [response] = await intentsClient.createIntent(createIntentRequest);
  console.log(`Intent ${response.name} created`);
}

createIntent();

Python

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def create_intent(project_id, display_name, training_phrases_parts, message_texts):
    """Create an intent of the given intent type."""
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    parent = dialogflow.AgentsClient.agent_path(project_id)
    training_phrases = []
    for training_phrases_part in training_phrases_parts:
        part = dialogflow.Intent.TrainingPhrase.Part(text=training_phrases_part)
        # Here we create a new training phrase for each provided part.
        training_phrase = dialogflow.Intent.TrainingPhrase(parts=[part])
        training_phrases.append(training_phrase)

    text = dialogflow.Intent.Message.Text(text=message_texts)
    message = dialogflow.Intent.Message(text=text)

    intent = dialogflow.Intent(
        display_name=display_name, training_phrases=training_phrases, messages=[message]
    )

    response = intents_client.create_intent(
        request={"parent": parent, "intent": intent}
    )

    print("Intent created: {}".format(response))

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Dialogflow 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Dialogflow 参考文档

Ruby: 请遵循 Ruby 设置说明 在客户端库页面上 然后访问 Ruby 版 Dialogflow 参考文档。

列出意图

以下示例展示如何列出意图。如需了解详情,请参阅意图参考

REST

如需列出代理的意图,请对 intents 资源调用 list 方法。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID

HTTP 方法和网址:

GET https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "intents": [
    {
      "name": "projects/PROJECT_ID/agent/intents/5b290a94-55d6-4074-96f4-9c4c4879c2bb",
      "displayName": "ListRooms",
      "priority": 500000,
      "action": "listRooms",
      "messages": [
        {
          "text": {
            "text": [
              "Here are the available rooms:"
            ]
          }
        }
      ]
    },
    ...
  ]
}

intents 后面的路径段包含您的 intent ID。

Go

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


func ListIntents(projectID string) ([]*dialogflowpb.Intent, error) {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return nil, clientErr
	}
	defer intentsClient.Close()

	if projectID == "" {
		return nil, errors.New(fmt.Sprintf("Received empty project (%s)", projectID))
	}

	parent := fmt.Sprintf("projects/%s/agent", projectID)

	request := dialogflowpb.ListIntentsRequest{Parent: parent}

	intentIterator := intentsClient.ListIntents(ctx, &request)
	var intents []*dialogflowpb.Intent

	for intent, status := intentIterator.Next(); status != iterator.Done; {
		intents = append(intents, intent)
		intent, status = intentIterator.Next()
	}

	return intents, nil
}

Java

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * List intents
 *
 * @param projectId Project/Agent Id.
 * @return Intents found.
 */
public static List<Intent> listIntents(String projectId) throws ApiException, IOException {
  List<Intent> intents = Lists.newArrayList();
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    // Set the project agent name using the projectID (my-project-id)
    AgentName parent = AgentName.of(projectId);

    // Performs the list intents request
    for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
      System.out.println("====================");
      System.out.format("Intent name: '%s'\n", intent.getName());
      System.out.format("Intent display name: '%s'\n", intent.getDisplayName());
      System.out.format("Action: '%s'\n", intent.getAction());
      System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName());
      System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName());

      System.out.format("Input contexts:\n");
      for (String inputContextName : intent.getInputContextNamesList()) {
        System.out.format("\tName: %s\n", inputContextName);
      }
      System.out.format("Output contexts:\n");
      for (Context outputContext : intent.getOutputContextsList()) {
        System.out.format("\tName: %s\n", outputContext.getName());
      }

      intents.add(intent);
    }
  }
  return intents;
}

Node.js

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The Project ID to use, e.g. 'YOUR_GCP_ID';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates clients
const intentsClient = new dialogflow.IntentsClient();

async function listIntents() {
  // Construct request

  // The path to identify the agent that owns the intents.
  const projectAgentPath = intentsClient.projectAgentPath(projectId);

  console.log(projectAgentPath);

  const request = {
    parent: projectAgentPath,
  };

  // Send the request for listing intents.
  const [response] = await intentsClient.listIntents(request);
  response.forEach(intent => {
    console.log('====================');
    console.log(`Intent name: ${intent.name}`);
    console.log(`Intent display name: ${intent.displayName}`);
    console.log(`Action: ${intent.action}`);
    console.log(`Root folowup intent: ${intent.rootFollowupIntentName}`);
    console.log(`Parent followup intent: ${intent.parentFollowupIntentName}`);

    console.log('Input contexts:');
    intent.inputContextNames.forEach(inputContextName => {
      console.log(`\tName: ${inputContextName}`);
    });

    console.log('Output contexts:');
    intent.outputContexts.forEach(outputContext => {
      console.log(`\tName: ${outputContext.name}`);
    });
  });
}

listIntents();

Python

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def list_intents(project_id):
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    parent = dialogflow.AgentsClient.agent_path(project_id)

    intents = intents_client.list_intents(request={"parent": parent})

    for intent in intents:
        print("=" * 20)
        print("Intent name: {}".format(intent.name))
        print("Intent display_name: {}".format(intent.display_name))
        print("Action: {}\n".format(intent.action))
        print("Root followup intent: {}".format(intent.root_followup_intent_name))
        print("Parent followup intent: {}\n".format(intent.parent_followup_intent_name))

        print("Input contexts:")
        for input_context_name in intent.input_context_names:
            print("\tName: {}".format(input_context_name))

        print("Output contexts:")
        for output_context in intent.output_contexts:
            print("\tName: {}".format(output_context.name))

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Dialogflow 参考文档

PHP: 请遵循 PHP 设置说明 在客户端库页面上 然后访问 PHP 版 Dialogflow 参考文档

Ruby 版:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Dialogflow 参考文档

删除意图

以下示例展示如何删除意图。如需了解详情,请参阅意图参考

REST

如需删除代理的意图,请对 intents 资源调用 delete 方法。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • INTENT_ID:您的意图 ID

HTTP 方法和网址:

DELETE https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/intents/INTENT_ID

如需发送您的请求,请展开以下选项之一:

您应该会收到一个成功的状态代码 (2xx) 和一个空响应。

Go

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

func DeleteIntent(projectID, intentID string) error {
	ctx := context.Background()

	intentsClient, clientErr := dialogflow.NewIntentsClient(ctx)
	if clientErr != nil {
		return clientErr
	}
	defer intentsClient.Close()

	if projectID == "" || intentID == "" {
		return errors.New(fmt.Sprintf("Received empty project (%s) or intent (%s)", projectID, intentID))
	}

	targetPath := fmt.Sprintf("projects/%s/agent/intents/%s", projectID, intentID)

	request := dialogflowpb.DeleteIntentRequest{Name: targetPath}

	requestErr := intentsClient.DeleteIntent(ctx, &request)
	if requestErr != nil {
		return requestErr
	}

	return nil
}

Java

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


/**
 * Delete intent with the given intent type and intent value
 *
 * @param intentId The id of the intent.
 * @param projectId Project/Agent Id.
 */
public static void deleteIntent(String intentId, String projectId)
    throws ApiException, IOException {
  // Instantiates a client
  try (IntentsClient intentsClient = IntentsClient.create()) {
    IntentName name = IntentName.of(projectId, intentId);
    // Performs the delete intent request
    intentsClient.deleteIntent(name);
  }
}

Node.js

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates clients
const intentsClient = new dialogflow.IntentsClient();

const intentPath = intentsClient.projectAgentIntentPath(projectId, intentId);

const request = {name: intentPath};

// Send the request for deleting the intent.
const result = await intentsClient.deleteIntent(request);
console.log(`Intent ${intentPath} deleted`);
return result;

Python

如需向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def delete_intent(project_id, intent_id):
    """Delete intent with the given intent type and intent value."""
    from google.cloud import dialogflow

    intents_client = dialogflow.IntentsClient()

    intent_path = intents_client.intent_path(project_id, intent_id)

    intents_client.delete_intent(request={"name": intent_path})

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Dialogflow 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Dialogflow 参考文档

Ruby 版:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Dialogflow 参考文档