Android에서 ML Kit를 사용한 스마트 답장 생성

ML Kit는 온디바이스 모델을 사용하여 메시지에 대한 짧은 답장을 생성할 수 있습니다.

스마트 답장을 생성하려면 ML Kit에 있습니다. ML Kit에서 대화가 영어라고 판단하고 대화에 민감한 주제가 포함되어 있지 않을 수 있으므로 ML Kit는 최대 3개의 응답을 생성하여 사용자에게 제안할 수 있습니다.

<ph type="x-smartling-placeholder">
번들번들로 묶이지 않음
도서관 이름com.google.mlkit:smart-replycom.google.android.gms:play-services-mlkit-smart-reply
구현모델은 빌드 시간에 앱에 정적으로 연결됩니다.모델은 Google Play 서비스를 통해 동적으로 다운로드됩니다.
앱 크기 영향크기가 약 5.7MB 증가합니다.크기가 약 200KB 늘어났습니다.
초기화 시간모델을 즉시 사용할 수 있습니다.처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수 있습니다.

사용해 보기

  • 샘플 앱을 사용하여 이 API의 사용 예를 참조하세요.

시작하기 전에

<ph type="x-smartling-placeholder">
  1. 프로젝트 수준 build.gradle 파일에 Google의 buildscriptallprojects 섹션에 있는 Maven 저장소

  2. ML Kit Android 라이브러리의 종속 항목을 모듈의 앱 수준 gradle 파일(일반적으로 app/build.gradle임) 다음 중 하나를 선택하세요. 필요에 따라 다음 종속 항목을 조정할 수 있습니다.

    • 모델을 앱과 번들로 묶으려면 다음 안내를 따르세요.
    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:smart-reply:17.0.3'
    }
    
    • Google Play 서비스에서 모델을 사용하려면 다음 단계를 따르세요.
    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-smart-reply:16.0.0-beta1'
    }
    

    Google Play 서비스에서 모델을 사용하도록 선택한 경우 모델을 다운로드한 후 모델을 기기에 자동으로 Play 스토어에서 다운로드할 수 있습니다. 다음 선언을 앱의 AndroidManifest.xml 파일:

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="smart_reply" >
          <!-- To use multiple models: android:value="smart_reply,model2,model3" -->
    </application>
    

    또한 모델 가용성을 명시적으로 확인하고 다음을 통해 다운로드를 요청할 수 있습니다. Google Play 서비스 ModuleInstallClient API

    설치 시간 모델 다운로드를 사용 설정하지 않거나 명시적 다운로드를 요청하지 않으면 스마트 답장 생성기를 처음 실행할 때 모델이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 나오지 않습니다.

    1. 대화 기록 객체 만들기

    스마트 답장을 생성하려면 ML Kit에 시간순으로 List을 전달합니다. TextMessage 객체의 첫 번째 객체입니다.

    사용자가 메시지를 보낼 때마다 메시지와 타임스탬프를 대화 기록:

    Kotlin

    conversation.add(TextMessage.createForLocalUser(
            "heading out now", System.currentTimeMillis()))

    자바

    conversation.add(TextMessage.createForLocalUser(
            "heading out now", System.currentTimeMillis()));

    사용자가 메시지를 수신할 때마다 메시지, 타임스탬프, 대화 기록에 추가합니다. 사용자 ID는 대화 내에서 발신자를 고유하게 식별합니다. 사용자 ID는 모든 사용자 데이터에 해당하며 사용자 ID가 일관적일 필요는 없습니다. 호출 사이에 발생하는 오류

    Kotlin

    conversation.add(TextMessage.createForRemoteUser(
            "Are you coming back soon?", System.currentTimeMillis(), userId))

    자바

    conversation.add(TextMessage.createForRemoteUser(
            "Are you coming back soon?", System.currentTimeMillis(), userId));

    대화 기록 객체의 예시는 다음과 같습니다.

    타임스탬프 userID isLocalUser 메시지
    2019년 2월 21일 목요일 13:13:39 PST true 가는 중인가요?
    2019년 2월 21일 목요일 13:15:03 PST FRIEND0 거짓 너무 늦었어요, 죄송합니다!

    ML Kit는 대화 기록의 마지막 메시지에 대한 답장을 제안합니다. 마지막 메시지 로컬에 있지 않은 사용자가 보낸 것이어야 합니다. 위의 예에서는 대화의 마지막 메일이 은 로컬 사용자가 아닌 사용자 FRIEND0에게 있습니다. 이 로그를 통과하는 ML Kit를 사용하면 FRIENDO의 메시지에 대한 답장: "늦었어, 죄송합니다!"

    2. 메시지 답장 받기

    메시지에 대한 스마트 답장을 생성하려면 SmartReplyGenerator의 인스턴스를 가져옵니다. 대화 기록을 suggestReplies() 메서드에 전달합니다.

    Kotlin

    val smartReplyGenerator = SmartReply.getClient()
    smartReply.suggestReplies(conversation)
            .addOnSuccessListener { result ->
                if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
                    // The conversation's language isn't supported, so
                    // the result doesn't contain any suggestions.
                } else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
                    // Task completed successfully
                    // ...
                }
            }
            .addOnFailureListener {
                // Task failed with an exception
                // ...
            }

    자바

    SmartReplyGenerator smartReply = SmartReply.getClient();
    smartReply.suggestReplies(conversation)
            .addOnSuccessListener(new OnSuccessListener() {
                @Override
                public void onSuccess(SmartReplySuggestionResult result) {
                    if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
                        // The conversation's language isn't supported, so
                        // the result doesn't contain any suggestions.
                    } else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
                        // Task completed successfully
                        // ...
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Task failed with an exception
                    // ...
                }
            });

    작업이 성공하면 SmartReplySuggestionResult 객체가 성공 핸들러가 있어야 합니다. 이 객체에는 제안된 답장이 최대 3개까지 포함된 목록이 포함됩니다. 사용자에게 제시할 수 있습니다.

    Kotlin

    for (suggestion in result.suggestions) {
        val replyText = suggestion.text
    }

    자바

    for (SmartReplySuggestion suggestion : result.getSuggestions()) {
        String replyText = suggestion.getText();
    }

    모델이 확신할 수 없는 경우 ML Kit가 결과를 반환하지 않을 수 있습니다. 추천 답변의 관련성, 입력 대화가 없는 경우 영어 또는 모델이 민감한 주제를 감지하는 경우