IT/AI

Dialogflow - 8. Node.js 클라이언트

루벤초이 2021. 4. 21. 23:30

Dialogflow 웹앱 시리즈입니다.

★Sample Code


지금까지 클라이언트 사이드에서 텍스트 기반 웹앱과 챗봇을 살펴봤어요.

이제 오디오 입력을 받아 처리하는 React App만 남았는데요, React App 같은 웹앱은 Dialogflow와 직접 통신할 수 없습니다.

Dialogflow API를 사용하려면 사용자 인증 과정을 거쳐야 하는데 이때 사용되는 인증용 .json 파일은 (과금과 연관된) 중요한 파일이기 대문에 웹앱과 함께 배포하기보다는 Node 앱이나 서버에서 보호하는 것이 바람직합니다.

 

따라서 구조는 다음과 같이 React App과 Dialogflow 사이에 Node App이 추가됩니다.

React 웹앱 연동을 위한 시스템 구조

 

React App에서 Node App으로 음성 데이터를 전달하는 방법에 대해서는 다음 편에서 다루고

오늘은 먼저 Node App에서 Node.js Client용 Dialogflow API를 이용하여 Dialogflow를 사용하는 부분을 구현해 보겠습니다. 

 

사용자 인증

사용자 인증을 위해 먼저 Google Cloud Project(GCP) 콘솔에서 인증 json 파일을 받습니다. 자세한 내용은 Google Cloud Platform & Firebase 편 中 <앱에서 GCP 사용을 위한 사용자 인증>편을 참고하세요.

 

이제 .json 파일을 export 해줍니다.

  • export GOOGLE_APPLICATION_CREDENTIALS='/home/ruben/credential.json'

리눅스의 경우 보통 ~/.bashrc 에 추가해서 부팅 때마다 글로벌하게 설정되도록 하고 윈도우에서는 시스템 환경변수에 추가합니다. 글로벌하게 설정하지 않고 프로그램이 실행될 때만 일시적으로 export하고 싶은 경우에는 Node 앱의 package.json "scripts"에 다음과 같이 추가합니다. (현재 .json 파일이 동 디렉토리에 있는 경우)

"scripts": {
    "start": "GOOGLE_APPLICATION_CREDENTIALS='./rubenchoi-gcp.json' node index.js",
},

 

코드 작성

공식 홈페이지에 나와있는 예제에서 projectId와 sessionId 부분을 수정합니다.

/*
 * Modification: only detectTextIntent() is used 
 *
 * Original Code: https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/detect.js
 * Reference : https://cloud.google.com/dialogflow/es/docs/how/detect-intent-audio?hl=ko
 */

// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

function detectTextIntent(projectId, sessionId, queries, languageCode) {
    // [START dialogflow_detect_intent_text]

    /**
     * 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);
    // [END dialogflow_detect_intent_text]
}


const uuid = require('uuid');

detectTextIntent(
    'newagent-tdyh',
    uuid.v4(),
    ['오늘 날씨 어때'],
    'ko-KR'
)

라인 350 이하는 삭제하고 detectTextIntent 호출부로 변경합니다. 실행해 봅시다.

  • npm install @google-cloud/dialogflow  uuid
  • npm start

결과 화면

오늘은 Dialogflow API를 사용하는 텍스트 기반의 Node App을 만들어봤습니다. 다음 편에서 React App과 Node App을 음성으로 연동해 보겠습니다.

728x90
반응형

'IT > AI' 카테고리의 다른 글

Dialogflow Advanced 01. 기상청 날씨 API 연동  (5) 2021.04.29
Dialogflow - 9. React 클라이언트  (0) 2021.04.22
Dialogflow - 7. 챗봇 클라이언트  (0) 2021.04.21
Dialogflow - 6. 클라이언트  (0) 2021.04.20
Dialogflow - 5. Webhook  (0) 2021.04.19