빠른 시작: API와의 상호작용

통합을 사용하지 않는 경우 최종 사용자와 상호작용하기 위해 코드를 작성해야 합니다. 대화 차례마다 코드는 Dialogflow API를 호출하여 에이전트를 쿼리합니다. 이 가이드에서는 명령줄에서 REST API를 사용하고 클라이언트 라이브러리를 사용하여 에이전트와 상호작용하는 방법을 설명합니다.

시작하기 전에

API를 사용할 계획이 없다면 이 빠른 시작을 생략해도 됩니다.

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

  1. Dialogflow 기본사항 이해
  2. 설정 단계 수행
  3. 에이전트 빌드 빠른 시작 가이드의 단계를 수행합니다. 아래 단계는 해당 가이드에서 시작한 에이전트에서 계속 수행됩니다. 해당 에이전트가 더 이상 없다면 build-agent-quickstart.zip을 다운로드하고 파일을 가져오기할 수 있습니다.

세션

세션은 Dialogflow 에이전트와 최종 사용자 간의 대화를 나타냅니다. 대화를 시작할 때 세션을 만들고 대화 차례마다 이 세션을 사용합니다. 대화가 종료되면 세션 사용을 중단합니다.

여러 최종 사용자와 동시에 진행되는 대화에서 동일한 세션을 사용하면 안 됩니다. Dialogflow는 각 활성 세션에 현재 활성인 컨텍스트를 유지합니다. Dialogflow는 20분 동안 세션 데이터를 저장합니다.

각 세션은 시스템에서 생성되는 세션 ID로 고유하게 구분됩니다. 인텐트 감지 요청에 새 세션 ID를 제공하여 새 세션을 만듭니다. 세션 ID는 최대 36바이트 크기의 문자열입니다. 시스템은 고유한 세션 ID를 생성합니다. 세션 ID는 랜덤 숫자, 해싱된 최종 사용자 식별자 또는 사용자가 생성하기 편리한 기타 값일 수 있습니다.

인텐트 감지

상호작용에 API를 사용하면 서비스는 최종 사용자와 직접 상호작용합니다. 각 대화 차례에서 서비스는 Sessions 유형의 detectIntent 또는 streamingDetectIntent 메서드를 호출하여 Dialogflow에 최종 사용자 표현을 전송합니다. Dialogflow는 일치하는 인텐트, 작업, 매개변수, 인텐트에 정의된 응답에 대한 정보로 응답합니다. 서비스는 필요에 따라 작업을 수행하고(예: 데이터베이스 쿼리 또는 외부 API 호출) 최종 사용자에게 메시지를 전송합니다. 이 프로세스는 대화가 종료될 때까지 계속됩니다.

다음 샘플은 인텐트를 감지하는 방법을 보여줍니다. 각 샘플은 다음 입력의 하위 집합을 받습니다.

  • 프로젝트 ID: 설정 단계에서 생성한 프로젝트의 프로젝트 ID를 사용합니다.
  • 세션 ID: 에이전트 테스트를 위해 무엇이든 사용할 수 있습니다. 예를 들어 '123456789'는 샘플에 자주 사용됩니다.
  • 텍스트: 하나의 최종 사용자 표현 또는 최종 사용자 표현 목록입니다. 여러 표현이 제공되는 경우 샘플 코드는 각 표현에 대해 인텐트 감지를 호출합니다. 'I know french'를 입력해 보세요.
  • 언어 코드: 최종 사용자 표현의 언어 코드입니다. 이 예시 에이전트에서는 'en-US'를 사용합니다.

REST

인텐트를 감지하려면 Sessions 리소스에서 detectIntent 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID
  • SESSION_ID: 세션 ID

HTTP 메서드 및 URL:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

JSON 요청 본문:

{
  "query_input": {
    "text": {
      "text": "I know french",
      "language_code": "en-US"
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "responseId": "856510ca-f617-4e25-b0bb-a26c0a59e030-19db3199",
  "queryResult": {
    "queryText": "I know french",
    "parameters": {
      "language": "French",
      "language-programming": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Wow! I didn't know you knew French. How long have you known French?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Wow! I didn't know you knew French. How long have you known French?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/123456789/contexts/set-language-followup",
        "lifespanCount": 2,
        "parameters": {
          "language": "French",
          "language.original": "french",
          "language-programming": "",
          "language-programming.original": ""
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/fe45022f-e58a-484f-96e8-1cbd6628f648",
      "displayName": "set-language"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  }
}

응답에서 다음 사항에 유의하세요.

  • queryResult.intent 필드에는 일치된 인텐트가 포함됩니다.
  • queryResult.fulfillmentMessages 필드의 값에는 인텐트 응답이 포함됩니다. 이는 시스템에서 최종 사용자에게 전달해야 하는 응답입니다.
  • queryResult.parameters 필드의 값에는 최종 사용자 표현에서 추출된 매개변수가 포함됩니다.
  • queryResult.outputContext 필드에는 활성 컨텍스트가 포함됩니다.

Go

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

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
	ctx := context.Background()

	sessionClient, err := dialogflow.NewSessionsClient(ctx)
	if err != nil {
		return "", err
	}
	defer sessionClient.Close()

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

	sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
	textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
	queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
	queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
	request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

	response, err := sessionClient.DetectIntent(ctx, &request)
	if err != nil {
		return "", err
	}

	queryResult := response.GetQueryResult()
	fulfillmentText := queryResult.GetFulfillmentText()
	return fulfillmentText, nil
}

Java

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


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntentTexts {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntentTexts(
      String projectId, List<String> texts, String sessionId, String languageCode)
      throws IOException, ApiException {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of(projectId, sessionId);
      System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input
      for (String text : texts) {
        // Set the text (hello) and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

        // Display the query result
        QueryResult queryResult = response.getQueryResult();

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format(
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format(
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");

        queryResults.put(text, queryResult);
      }
    }
    return queryResults;
  }
}

Node.js

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


/**
 * TODO(developer): UPDATE these variables before running the sample.
 */
// projectId: ID of the GCP project where Dialogflow agent is deployed
// const projectId = 'PROJECT_ID';
// sessionId: String representing a random number or hashed user identifier
// const sessionId = '123456';
// queries: A set of sequential queries to be send to Dialogflow agent for Intent Detection
// const queries = [
//   'Reserve a meeting room in Toronto office, there will be 5 of us',
//   'Next monday at 3pm for 1 hour, please', // Tell the bot when the meeting is taking place
//   'B'  // Rooms are defined on the Dialogflow agent, default options are A, B, or C
// ]
// languageCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

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

// Instantiates a session client
const sessionClient = new dialogflow.SessionsClient();

async function detectIntent(
  projectId,
  sessionId,
  query,
  contexts,
  languageCode
) {
  // The path to identify the agent that owns the created intent.
  const sessionPath = sessionClient.projectAgentSessionPath(
    projectId,
    sessionId
  );

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (contexts && contexts.length > 0) {
    request.queryParams = {
      contexts: contexts,
    };
  }

  const responses = await sessionClient.detectIntent(request);
  return responses[0];
}

async function executeQueries(projectId, sessionId, queries, languageCode) {
  // Keeping the context across queries let's us simulate an ongoing conversation with the bot
  let context;
  let intentResponse;
  for (const query of queries) {
    try {
      console.log(`Sending Query: ${query}`);
      intentResponse = await detectIntent(
        projectId,
        sessionId,
        query,
        context,
        languageCode
      );
      console.log('Detected intent');
      console.log(
        `Fulfillment Text: ${intentResponse.queryResult.fulfillmentText}`
      );
      // Use the context from this response for next queries
      context = intentResponse.queryResult.outputContexts;
    } catch (error) {
      console.log(error);
    }
  }
}
executeQueries(projectId, sessionId, queries, languageCode);

Python

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

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    for text in texts:
        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"session": session, "query_input": query_input}
        )

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Dialogflow 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Dialogflow 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Dialogflow 참조 문서를 참조하세요.

생산화

프로덕션에서 에이전트를 실행하기 전에 생산화 권장사항을 구현해야 합니다.