대화에서 데이터 저장 (Dialogflow)

Dialogflow에서 탐색

계속을 클릭하여 Dialogflow에 데이터 저장 샘플을 가져옵니다. 그런 다음 아래 단계에 따라 샘플을 배포하고 테스트합니다.

  1. 에이전트 이름을 입력하고 샘플의 새 Dialogflow 에이전트를 만듭니다.
  2. 에이전트 가져오기가 완료되면 Go to agent(에이전트로 이동)를 클릭합니다.
  3. 기본 탐색 메뉴에서 Fulfillment로 이동합니다.
  4. 인라인 편집기를 사용 설정한 다음 배포를 클릭합니다. 편집기에 샘플 코드가 포함되어 있습니다.
  5. 기본 탐색 메뉴에서 통합으로 이동한 다음 Google 어시스턴트를 클릭합니다.
  6. 표시되는 모달 창에서 Auto-preview changes를 사용 설정하고 Test를 클릭하여 작업 시뮬레이터를 엽니다.
  7. 시뮬레이터에서 Talk to my test app를 입력하여 샘플을 테스트합니다.
계속

우수한 사용자 환경을 제공하는 방법 중 하나는 대화 다음 시점 사이에 또는 사용자와의 여러 대화를 나누는 사이에 데이터를 절약할 수 있다는 것입니다. 이 기능은 단일 대화에서 유용한 메시지를 다시 표시하거나, 여러 세션에 걸쳐 게임 점수를 저장하거나, 사용자를 위한 작은 정보를 기억하는 경우에 유용합니다.

요구사항은 대화 중에 또는 대화 간에 데이터를 저장해야 하는지 여부에 따라 약간 다릅니다. 대화에 데이터를 저장하려면 AppResponse 객체의 conversationToken 필드를 사용하면 됩니다.

대화에서 데이터를 저장하려면 다음 단계를 따르세요.

  1. 사용자가 인증되었는지 게스트인지 확인합니다.
  2. AppResponse 객체의 userStorage 필드를 사용하여 사용자 데이터를 저장하거나 액세스합니다.

대화 다음 단계 사이에 데이터 저장

conversationToken 필드는 대화가 이어질 때마다 작업으로 재순환되는 불투명한 토큰이 포함된 문자열입니다. 예를 들어 대화의 첫 번째 차례에 대해 AppResponse에서 값을 "count=1"로 설정하면 대화의 두 번째 차례에서 작업에서 수신한 AppRequestconversationToken"count=1"가 포함됩니다.

토큰은 항상 대화 시작 시 빈 문자열로 초기화됩니다. Actions on Google Node.js 클라이언트 라이브러리를 사용하는 경우 conv.data를 사용하여 대화 토큰과 JSON 객체로 상호작용할 수 있습니다. 여기서 convConversation의 인스턴스입니다.

다음 샘플은 AppResponseconversationToken 필드에 카운터를 저장하는 방법을 보여줍니다.

Node.js

conv.data.firstNum = firstNum;
conv.ask(`Got it, the first number is ${firstNum}.`);
conv.ask(`What's the second number?`);

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder.getConversationData().put("firstNum", firstNum);
responseBuilder.add("Got it, the first number is " + firstNum + ".");
responseBuilder.add("What's the second number?");
return responseBuilder.build();

JSON

아래 JSON은 conversationToken 대신 outputContexts를 사용하는 웹훅 응답을 설명합니다.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Got it, the first number is 23."
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "What's the second number?"
            }
          }
        ]
      }
    }
  },
  "outputContexts": [
    {
      "name": "projects/save-data-df-js/agent/sessions/ABwppHGfFkWJdHKPpBEYiGkhdoakWmYj_2sZa4o8pbGG9nj4q5_GfDTtNEXOY34mLX8G4o_d7oZdUW9bnBZC/contexts/_actions_on_google",
      "lifespanCount": 99,
      "parameters": {
        "data": "{\"firstNum\":23}"
      }
    }
  ]
}

JSON

아래의 JSON은 웹훅 응답을 설명합니다.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TEXT"
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Got it, the first number is 23."
              }
            },
            {
              "simpleResponse": {
                "textToSpeech": "What's the second number?"
              }
            }
          ]
        }
      }
    }
  ],
  "conversationToken": "{\"data\":{\"firstNum\":23}}"
}

실제 사용 예는 유용한 다시 메시지를 표시하고 단계적 실패 권장사항 가이드를 참고하세요.

대화 간의 데이터 저장

AppResponse 객체의 userStorage 필드는 작업에서 제공하는 불투명 토큰이 포함된 문자열입니다. 이 토큰은 특정 사용자의 여러 대화에 저장됩니다. 예를 들어 게임은 userStorage에 사용자의 가장 높은 점수를 저장하고 사용자가 새 대화를 시작할 때마다 환영 메시지에 그 값을 사용할 수 있습니다.

사용자 확인 상태 확인 및 처리

사용자의 확인 상태 값은 GUEST 또는 VERIFIED입니다. 각 대화를 시작할 때 Actions on Google은 대화가 시작될 때 다양한 지표를 기반으로 사용자의 확인 상태를 설정합니다. 예를 들어 휴대기기에서 Google 어시스턴트에 로그인한 사용자의 인증 상태는 VERIFIED입니다.

사용자의 인증 상태가 GUEST인 이유는 다음과 같습니다.

  • 사용자가 개인 검색결과를 사용 중지했습니다.
  • 사용자가 웹 및 앱 활동을 사용 중지했습니다. 이 설정이 도메인 수준에서 사용 중지되는 사용자도 있을 수 있습니다.
  • 기기에 Voice Match가 사용 설정되어 있고 일치에 실패하거나 사용자가 음성을 사용하지 않고 어시스턴트를 호출하는 경우 (예: Google Home 길게 누르기)
  • 사용자가 로그인하지 않았습니다.

게스트 사용자가 실패할 수 있는 기능과 상호작용하지 못하도록 userStorage를 사용하여 데이터를 저장하거나 계정 연결 흐름을 시작하기 전에 항상 사용자의 확인 상태를 확인합니다.

Node.js용 Actions On Google 클라이언트 라이브러리를 사용하는 경우 conv.user.storage를 사용하여 사용자 스토리지를 JSON 객체로 연결할 수 있습니다. 여기서 convConversation의 인스턴스입니다. 다음 샘플은 AppResponseuserStorage 필드에 카운터를 저장하는 방법을 보여줍니다.

Node.js

app.intent('Save Sum', (conv) => {
  if (conv.user.verification === 'VERIFIED') {
    conv.user.storage.sum = conv.data.sum;
    conv.close(`Alright, I'll store that for next time. See you then.`);
  } else {
    conv.close(`I can't save that right now, but we can add ` +
      `new numbers next time!`);
  }
});

Java

@ForIntent("Save Sum")
public ActionResponse saveSum(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  Integer sum = ((Double) request.getConversationData().get("sum")).intValue();
  String verificationStatus = request.getUser().getUserVerificationStatus();
  if (verificationStatus.equals("VERIFIED")) {
    responseBuilder.getUserStorage().put("sum", sum);
    responseBuilder.add("Alright, I'll store that for next time. See you then.");
  } else {
    responseBuilder.add("I can't save that right now, but we can add new numbers next time!");
  }
  responseBuilder.endConversation();
  return responseBuilder.build();
}

Node.js

if (conv.user.verification === 'VERIFIED') {
  conv.user.storage.sum = conv.data.sum;
  conv.close(`Alright, I'll store that for next time. See you then.`);
} else {
  conv.close(`I can't save that right now, but we can add ` +
    `new numbers next time!`);
}

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
Integer sum = ((Double) request.getConversationData().get("sum")).intValue();
String verificationStatus = request.getUser().getUserVerificationStatus();
if (verificationStatus.equals("VERIFIED")) {
  responseBuilder.getUserStorage().put("sum", sum);
  responseBuilder.add("Alright, I'll store that for next time. See you then.");
} else {
  responseBuilder.add("I can't save that right now, but we can add new numbers next time!");
}
responseBuilder.endConversation();
return responseBuilder.build();

JSON

아래의 JSON은 웹훅 응답을 설명합니다.

{
  "payload": {
    "google": {
      "expectUserResponse": false,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Alright, I'll store that for next time. See you then."
            }
          }
        ]
      },
      "userStorage": "{\"data\":{\"sum\":68}}"
    }
  }
}

JSON

아래의 JSON은 웹훅 응답을 설명합니다.

{
  "expectUserResponse": false,
  "finalResponse": {
    "richResponse": {
      "items": [
        {
          "simpleResponse": {
            "textToSpeech": "Alright, I'll store that for next time. See you then."
          }
        }
      ]
    }
  },
  "conversationToken": "{\"data\":{\"firstNum\":23,\"sum\":68}}",
  "userStorage": "{\"data\":{\"sum\":68}}"
}

실제 사용 예는 사용자 환경설정으로 대화 맞춤설정 권장사항 가이드를 참고하세요.

법적 참고사항: userStorage에 액세스하기 전에 동의를 얻어야 합니다. 일부 국가에는 개발자가 userStorage에 특정 정보 (예: 개인 정보)에 액세스하거나 이를 저장하기 전에 사용자의 동의를 얻도록 요구하는 규정이 있습니다. 이러한 국가 중 한 곳에서 사업을 하고 userStorage에 이러한 정보를 액세스하거나 저장하고자 하는 경우, 확인 도우미를 사용하여 사용자에게 동의를 요청하고 동의를 얻어야 userStorage에 이러한 정보를 저장할 수 있습니다.

사용자 저장용량 만료

어시스턴트가 ID를 사용자와 일치시킬 수 있는 경우 userStorage의 콘텐츠는 만료되지 않으며 사용자 또는 작업 자체만 콘텐츠를 삭제할 수 있습니다.

어시스턴트가 ID를 사용자와 일치시킬 수 없으면 대화가 끝날 때 userStorage의 콘텐츠가 삭제됩니다. 다음은 어시스턴트가 ID를 사용자와 일치시킬 수 없는 몇 가지 사례입니다.

  • Voice Match가 설정되어 있으며 일치하는 항목이 없습니다.
  • 사용자가 개인 정보를 사용 중지했습니다.

userStorage 필드의 콘텐츠 지우기

AppResponseresetUserStorage 필드를 true로 설정하여 작업의 userStorage 필드 콘텐츠를 삭제할 수 있습니다. userStorage 값을 빈 문자열로 설정하면 다음 대화 차례에서 userStorage 값은 변경되지 않습니다. 이렇게 하면 콘텐츠가 변경되지 않은 상태에서 전체 userStorage를 다시 전송하지 않을 수 있습니다.

Node.js용 Actions On Google 클라이언트 라이브러리를 사용하는 경우 conv.user.storage의 값을 {} (빈 객체)로 설정하기만 하면 됩니다.

Node.js

app.intent('Forget Number', (conv) => {
  conv.user.storage = {};
  conv.ask(`Alright, I forgot your last result.`);
  conv.ask(`Let's add two new numbers. What is the first number?`);
});

Java

@ForIntent("Forget Number")
public ActionResponse forgetNumber(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  responseBuilder.getUserStorage().clear();
  responseBuilder.add("Alright, I forgot your last result.");
  responseBuilder.add("Let's add two new numbers. What is the first number?");
  return responseBuilder.build();
}

Node.js

conv.user.storage = {};
conv.ask(`Alright, I forgot your last result.`);
conv.ask(`Let's add two new numbers. What is the first number?`);

Java

ResponseBuilder responseBuilder = getResponseBuilder(request);
responseBuilder.getUserStorage().clear();
responseBuilder.add("Alright, I forgot your last result.");
responseBuilder.add("Let's add two new numbers. What is the first number?");
return responseBuilder.build();

JSON

아래의 JSON은 웹훅 응답을 설명합니다.

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Alright, I forgot your last result."
            }
          },
          {
            "simpleResponse": {
              "textToSpeech": "Let's add two new numbers. What is the first number?"
            }
          }
        ]
      },
      "userStorage": "{\"data\":{}}"
    }
  }
}

JSON

아래의 JSON은 웹훅 응답을 설명합니다.

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TEXT"
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Alright, I forgot your last result."
              }
            },
            {
              "simpleResponse": {
                "textToSpeech": "Let's add two new numbers. What is the first number?"
              }
            }
          ]
        }
      }
    }
  ],
  "userStorage": "{\"data\":{}}"
}

사용자는 호출한 작업에서 userStorage 필드의 콘텐츠를 볼 수 있습니다. 서비스가 나를 기억하지 않도록 하여 특정 작업에서 저장된 사용자 데이터를 삭제할 수도 있습니다.

  1. 휴대전화에서 어시스턴트 앱을 엽니다.
  2. 창 아이콘을 탭합니다.

  3. 탐색 탭에서 사용자 스토리지를 보거나 삭제하려는 작업을 찾아 탭하여 세부정보 페이지를 엽니다.
  4. 페이지 하단으로 스크롤합니다.
    • userStorage 필드의 내용을 보려면 [저장된 데이터 보기]를 탭합니다.
    • 저장된 사용자 데이터를 삭제하려면 $action이 나를 기억하지 않도록 설정을 탭합니다.