API でインテントを管理する

インテントは、どのユーザー リクエストを理解し、どのようなアクションを取るかを決定します。通常は、Dialogflow ES コンソールを使用してインテントを管理します。高度なシナリオでは、API を使用してインテントを管理することも考えられます。このページでは、API を使用してインテントを作成、一覧表示、削除する方法について説明します。

始める前に

このガイドを読む前に、次の手順を行ってください。

  1. Dialogflow の基本をご覧ください。
  2. 手順に沿って設定してください。

エージェントを作成する

エージェントをまだ作成していない場合は、ここで作成します。

  1. Dialogflow ES コンソールに移動します。
  2. Dialogflow コンソールにログインするよう求められたら、ログインします。詳細については、Dialogflow コンソールの概要をご覧ください。
  3. 左側のサイドバー メニューで [Create Agent] をクリックします。(すでに他のエージェントをお持ちの場合は、エージェント名をクリックし、一番下までスクロールして [Create new agent] をクリックします)。
  4. エージェント名、デフォルトの言語、デフォルトのタイムゾーンを入力します。
  5. すでにプロジェクトを作成している場合は、そのプロジェクトを入力します。Dialogflow コンソールでプロジェクトを作成できるようにする場合は、[Create a new Google project] を選択します。
  6. [Create] ボタンをクリックします。

エージェントにサンプル ファイルをインポートする

このガイドの手順でエージェントの前提条件を設定するため、このガイド用に準備されたエージェントをインポートする必要があります。インポート時に、この手順では restore オプションが使用されます。これにより、すべてのエージェント設定、インテント、エンティティが上書きされます。

ファイルをインポートする手順は次のとおりです。

  1. room-booking-agent.zip ファイルをダウンロードします。
  2. Dialogflow ES コンソールに移動します。
  3. エージェントを選択します。
  4. エージェント名の横にある設定 ボタンをクリックします。
  5. [Export and Import] タブを選択します。
  6. [Restore from Zip] を選択し、手順に従ってダウンロードした zip ファイルを復元します。

IntentView を使用して、すべてのインテント データを返す

インテントを作成、一覧表示、または取得すると、インテント データが呼び出し元に返されます。デフォルトでは、この返されたデータは省略形です。以下のサンプルではこのデフォルトを使用しています。

すべてのインテント データを取得するには、IntentView パラメータを INTENT_VIEW_FULL に設定する必要があります。詳細については、インテント タイプのメソッドを参照してください。

インテントを作成する

以下のサンプルは、インテントを作成する方法を示しています。詳細については、インテントのリファレンスをご覧ください。

REST

エージェントのインテントを作成するには、intent リソースの create メソッドを呼び出します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID

HTTP メソッドと URL:

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 メソッドと URL:

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 の後のパスセグメントにはインテント 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 メソッドと URL:

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 リファレンス ドキュメントをご覧ください。