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

대화 차례마다 상호작용이 발생합니다. 상호작용 중에 최종 사용자가 Dialogflow에 입력을 보내고 Dialogflow가 응답을 보냅니다. 시스템을 구현할 때에는 API를 사용하거나 통합을 사용하는 두 가지의 상호작용 처리 옵션이 있습니다.

API를 사용할 때는 시스템에서 다음을 처리해야 합니다.

  • 에이전트 빌드
  • 최종 사용자를 위한 사용자 인터페이스를 제공합니다.
  • 대화 차례마다 Dialogflow API를 호출하여 최종 사용자 입력을 API로 보냅니다.
  • 에이전트 응답이 완전히 정적인 경우(일반적이지 않음)를 제외하고 웹훅 사용 fulfillment를 처리하려면 웹훅 서비스를 호스팅해야 합니다.

통합을 사용하는 경우 시스템에서 다음을 처리하기만 하면 됩니다.

  • 에이전트 빌드
  • 필요한 경우 웹훅 서비스를 구현합니다.

다음 다이어그램은 세션에서 한 개의 대화 차례 동안 진행되는 단계를 보여줍니다.

API 흐름 다이어그램

  1. 최종 사용자가 내용을 입력하거나 말합니다. 이를 최종 사용자 입력이라고 합니다.
  2. 사용자 인터페이스 또는 통합 시스템이 입력을 수신하여 인텐트 인식 요청에서 Dialogflow API로 전달합니다.
  3. Dialogflow API가 인텐트 인식 요청을 수신합니다. 입력을 인텐트 또는 양식 매개변수와 일치시키고, 필요에 따라 매개변수를 설정하며, 세션 상태를 업데이트합니다. 웹훅 사용 fulfillment를 호출해야 하는 경우 웹훅 서비스에 웹훅 요청을 보냅니다. 그 이외의 경우 6단계로 이동합니다.
  4. 웹훅 서비스가 웹훅 요청을 수신합니다. 이 서비스는 외부 API 호출, 데이터베이스 쿼리 또는 업데이트 등 필요한 작업을 수행합니다.
  5. 웹훅 서비스가 응답을 빌드하고 Dialogflow 응답을 다시 Dialogflow로 보냅니다.
  6. Dialogflow가 인텐트 인식 응답을 만듭니다. 웹훅이 호출된 경우 웹훅 응답에 제공된 응답을 사용합니다. 웹훅이 호출되지 않은 경우 에이전트에 정의된 정적 응답을 사용합니다. Dialogflow가 인텐트 인식 응답을 사용자 인터페이스 또는 통합 시스템에 보냅니다.
  7. 사용자 인터페이스 또는 통합 시스템은 인텐트 인식 응답을 수신하고 텍스트 또는 오디오 응답을 최종 사용자에게 전달합니다.
  8. 최종 사용자가 응답을 보거나 듣습니다.

가이드 목적

이 가이드에서는 통합을 사용하지 않는 에이전트의 대화 차례 하나로 API를 호출하는 방법을 보여줍니다(위 다이어그램의 2단계). 이 가이드에서는 최종 사용자의 사용자 인터페이스를 구현하는 방법을 보여주지 않습니다.

시작하기 전에

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

  1. Dialogflow CX 기본사항 읽기
  2. 설정 단계 수행
  3. 새 에이전트를 만들거나 에이전트 빌드에서 만든 에이전트를 계속 사용합니다.

ID 수집

아래 샘플에서는 여러 ID가 입력으로 필요합니다. 프로젝트 ID, 리전 ID, 에이전트 ID를 찾으려면 다음 안내를 따르세요.

  1. Dialogflow CX 콘솔을 엽니다.
  2. Google Cloud 프로젝트를 선택하여 에이전트 선택기를 엽니다.
  3. 목록에서 에이전트의 옵션 메뉴를 클릭합니다.
  4. 이름 복사 버튼을 클릭합니다.
  5. 그러면 에이전트의 전체 식별 이름이 복사되며, 여기에는 프로젝트 ID, 리전 ID, 에이전트 ID가 다음 형식으로 포함됩니다.
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

세션 ID도 필요합니다. 세션은 Dialogflow 에이전트와 최종 사용자 간의 대화를 나타냅니다. 대화를 시작할 때 고유한 세션 ID를 만들고 대화 차례마다 이 세션을 사용합니다. API를 살펴보기 위해 최대 36바이트의 문자열 ID를 사용할 수 있습니다(예: test-session-123).

인텐트 인식 호출

다음 샘플은 Sessions.detectIntent 메서드를 호출합니다.

세션 참조의 프로토콜 및 버전을 선택합니다.

프로토콜 V3 V3beta1
REST 세션 리소스 세션 리소스
RPC 세션 인터페이스 세션 인터페이스
C++ SessionsClient 사용 불가능
C# SessionsClient 사용 불가능
Go SessionsClient 사용 불가능
자바 SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP 사용 불가능 사용 불가능
Python SessionsClient SessionsClient
Ruby 사용 불가능 해당 사항 없음

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 ID
  • AGENT_ID: 에이전트 ID
  • REGION_ID: 리전 ID
  • SESSION_ID: 세션 ID
  • END_USER_INPUT: 최종 사용자 입력

HTTP 메서드 및 URL:

POST https://REGION_ID-dialogflow.googleapis.com/v3/projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID/sessions/SESSION_ID:detectIntent

JSON 요청 본문:

{
  "queryInput": {
    "text": {
      "text": "END_USER_INPUT"
    },
    "languageCode": "en"
  },
  "queryParams": {
    "timeZone": "America/Los_Angeles"
  }
}

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

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

{
  "responseId": "38e8f23d-eed2-445e-a3e7-149b242dd669",
  "queryResult": {
    "text": "I want to buy a shirt",
    "languageCode": "en",
    "responseMessages": [
      {
        "text": {
          "text": [
            "Ok, let's start a new order."
          ]
        }
      },
      {
        "text": {
          "text": [
            "I'd like to collect a bit more information from you."
          ]
        }
      },
      {
        "text": {
          "text": [
            "What color would you like?"
          ]
        }
      },
      {}
    ],
    "currentPage": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/flows/00000000-0000-0000-0000-000000000000/pages/ce0b88c4-9292-455c-9c59-ec153dad94cc",
      "displayName": "New Order"
    },
    "intent": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
      "displayName": "order.new"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": { ... },
    "match": {
      "intent": {
        "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
        "displayName": "order.new"
      },
      "resolvedInput": "I want to buy a shirt",
      "matchType": "INTENT",
      "confidence": 1
    }
  }
}

Java

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


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

public class DetectIntent {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntent(
      String projectId,
      String locationId,
      String agentId,
      String sessionId,
      List<String> texts,
      String languageCode)
      throws IOException, ApiException {
    SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder();
    if (locationId.equals("global")) {
      sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443");
    } else {
      sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443");
    }
    SessionsSettings sessionsSettings = sessionsSettingsBuilder.build();

    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client.

    // Note: close() needs to be called on the SessionsClient object to clean up resources
    // such as threads. In the example below, try-with-resources is used,
    // which automatically calls close().
    try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
      // Set the session name using the projectID (my-project-id), locationID (global), agentID
      // (UUID), and sessionId (UUID).
      SessionName session =
          SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId);

      // TODO : Uncomment if you want to print session path
      // System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input.
      for (String text : texts) {
        // Set the text (hello) for the query.
        TextInput.Builder textInput = TextInput.newBuilder().setText(text);

        // Build the query with the TextInput and language code (en-US).
        QueryInput queryInput =
            QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build();

        // Build the DetectIntentRequest with the SessionName and QueryInput.
        DetectIntentRequest request =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .build();

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

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

        // TODO : Uncomment if you want to print queryResult
        // System.out.println("====================");
        // System.out.format("Query Text: '%s'\n", queryResult.getText());
        // System.out.format(
        //     "Detected Intent: %s (confidence: %f)\n",
        //     queryResult.getIntent().getDisplayName(),
        //         queryResult.getIntentDetectionConfidence());

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

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const location = 'global';
// const agentId = 'my-agent';
// const query = 'Hello';
// const languageCode = 'en'

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const location = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient();

async function detectIntentText() {
  const sessionId = Math.random().toString(36).substring(7);
  const sessionPath = client.projectLocationAgentSessionPath(
    projectId,
    location,
    agentId,
    sessionId
  );
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  for (const message of response.queryResult.responseMessages) {
    if (message.text) {
      console.log(`Agent Response: ${message.text.text}`);
    }
  }
  if (response.queryResult.match.intent) {
    console.log(
      `Matched Intent: ${response.queryResult.match.intent.displayName}`
    );
  }
  console.log(
    `Current Page: ${response.queryResult.currentPage.displayName}`
  );
}

detectIntentText();

Python

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

def run_sample():
    # TODO(developer): Replace these values when running the function
    project_id = "YOUR-PROJECT-ID"
    # For more information about regionalization see https://cloud.google.com/dialogflow/cx/docs/how/region
    location_id = "YOUR-LOCATION-ID"
    # For more info on agents see https://cloud.google.com/dialogflow/cx/docs/concept/agent
    agent_id = "YOUR-AGENT-ID"
    agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
    # For more information on sessions see https://cloud.google.com/dialogflow/cx/docs/concept/session
    session_id = uuid.uuid4()
    texts = ["Hello"]
    # For more supported languages see https://cloud.google.com/dialogflow/es/docs/reference/language
    language_code = "en-us"

    detect_intent_texts(agent, session_id, texts, language_code)

def detect_intent_texts(agent, 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."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    for text in texts:
        text_input = session.TextInput(text=text)
        query_input = session.QueryInput(text=text_input, language_code=language_code)
        request = session.DetectIntentRequest(
            session=session_path, query_input=query_input
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print(f"Query text: {response.query_result.text}")
        response_messages = [
            " ".join(msg.text.text) for msg in response.query_result.response_messages
        ]
        print(f"Response text: {' '.join(response_messages)}\n")

생산화

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