API로 인텐트 관리

인텐트는 이해되는 사용자 요청과 수행할 작업을 판단합니다. 대부분의 경우 Dialogflow ES 콘솔을 사용하여 인텐트를 관리합니다. 고급 시나리오에서는 API를 사용하여 인텐트를 관리할 수 있습니다. 이 페이지에서는 API를 사용하여 인텐트를 생성, 나열, 삭제하는 방법을 설명합니다.

시작하기 전에

이 가이드를 읽기 전에 다음을 수행해야 합니다.

  1. Dialogflow 기본사항 읽기
  2. 설정 단계 수행

에이전트 만들기

아직 에이전트를 만들지 않은 경우 지금 만듭니다.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 로그인 메시지가 표시되면 Dialogflow 콘솔에 로그인합니다. 자세한 내용은 Dialogflow 콘솔 개요를 참조하세요.
  3. 왼쪽 사이드바 메뉴에서 에이전트 만들기를 클릭합니다. 이미 다른 에이전트가 있는 경우 에이전트 이름을 클릭하고 아래로 스크롤하여 새 에이전트 만들기를 클릭합니다.
  4. 에이전트 이름, 기본 언어, 기본 시간대를 입력합니다.
  5. 프로젝트를 이미 만든 경우 해당 프로젝트를 입력합니다. Dialogflow 콘솔이 프로젝트를 만들 수 있게 하려면 새 Google 프로젝트 만들기를 선택하세요.
  6. 만들기 버튼을 클릭합니다.

에이전트로 예시 파일 가져오기

이 가이드의 단계에서는 에이전트가 있다고 가정하므로 이 가이드를 위해 준비된 에이전트를 가져와야 합니다. 이 단계에서는 가져올 때 모든 에이전트 설정, 인텐트, 항목을 덮어쓰는 restore 옵션을 사용합니다.

파일을 가져오려면 다음 단계를 따르세요.

  1. room-booking-agent.zip 파일을 다운로드합니다.
  2. Dialogflow ES 콘솔로 이동합니다.
  3. 에이전트를 선택합니다.
  4. 에이전트 이름 옆에 있는 설정 버튼을 클릭합니다.
  5. 내보내기 및 가져오기 탭을 선택합니다.
  6. 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 참조 문서를 참조하세요.