使用 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] (建立新 Google 專案)
  6. 按一下 [Create] (建立) 按鈕。

將範例檔案匯入代理程式

本指南中的步驟會假設您的代理程式符合某些條件,因此您需要匯入為本指南準備的代理程式。匯入時,這些步驟會使用「還原」選項,覆寫所有介面設定、意圖和實體。

如要匯入檔案,請按照下列步驟操作:

  1. 下載 room-booking-agent.zip 檔案。
  2. 前往 Dialogflow ES 主控台
  3. 選取所需的代理程式。
  4. 按一下代理程式名稱旁邊的「設定」 按鈕。
  5. 選取「Export and Import」分頁標籤。
  6. 選取「Restore From Zip」,然後按照操作說明還原下載的 ZIP 檔案。

使用 IntentView 傳回所有意圖資料

建立、列出或取得意圖時,系統會將意圖資料傳回給呼叫端。根據預設,系統會傳回經過簡化的資料。以下範例使用這個預設值。

如要擷取所有意圖資料,您必須將 IntentView 參數設為 INTENT_VIEW_FULL。詳情請參閱 Intents 類型的相關方法。

建立意圖

下列範例說明如何建立意圖。詳情請參閱意圖參考資料

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 fmt.Errorf("intentmgmt.CreateIntent 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 之後的路徑區段包含了您的意圖 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, fmt.Errorf("intentmgmt.ListIntents 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 fmt.Errorf("intentmgmt.DeleteIntent 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 參考文件