Android에서 ML Kit를 통한 스마트 답장 생성
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
ML Kit를 통해 기기별 모델을 사용하여 메시지 답장을 생성할 수 있습니다.
스마트 답장을 생성하려면 ML Kit에 대화의 최근 메시지 로그를 전달합니다. 대화 언어가 영어이고 민감한 주제가 포함되었을 가능성이 없다고 판단되면 ML Kit는 사용자에게 추천할 수 있는 답장을 최대 3개 생성합니다.
시작하기 전에
- 먼저 Android 프로젝트에 Firebase를 추가합니다.
- 모듈(앱 수준) Gradle 파일(일반적으로
app/build.gradle
)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다.apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
dependencies {
// ...
implementation 'com.google.firebase:firebase-ml-natural-language:22.0.0'
implementation 'com.google.firebase:firebase-ml-natural-language-smart-reply-model:20.0.7'
}
- 또한 앱 수준의
build.gradle
파일에서 tflite
파일의 압축을 사용하지 않도록 설정합니다.android {
// ...
aaptOptions {
noCompress "tflite"
}
}
1. 대화 기록 객체 만들기
스마트 답장을 생성하려면 ML Kit에 시간순으로 정렬된 FirebaseTextMessage
객체의 List
를 전달합니다. 가장 오래된 타임스탬프가 먼저 나와야 합니다.
사용자가 메시지를 전송할 때마다 메시지와 타임스탬프를 대화 기록에 추가합니다.
자바
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()));
Kotlin
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()))
사용자가 메시지를 수신할 때마다 메시지, 타임스탬프, 발신자의 사용자 ID를 대화 기록에 추가합니다. 사용자 ID는 대화 내에서 발신자를 식별하는 문자열이면 무엇이든 사용할 수 있습니다. 사용자 ID는 사용자 데이터와 일치할 필요는 없으며, 스마트 답장 생성기의 호출 또는 대화 간에 사용자 ID의 일관성이 없어도 됩니다.
자바
conversation.add(FirebaseTextMessage.createForRemoteUser(
"Are you coming back soon?", System.currentTimeMillis(), userId));
Kotlin
conversation.add(FirebaseTextMessage.createForRemoteUser(
"Are you coming back soon?", System.currentTimeMillis(), userId))
대화 기록 객체의 예시는 다음과 같습니다.
타임스탬프 |
사용자 ID |
로컬 사용자 여부 |
메시지 |
Thu Feb 21 13:13:39 PST 2019 |
|
참 |
are you on your way? |
Thu Feb 21 13:15:03 PST 2019 |
FRIEND0 |
거짓 |
Running late, sorry! |
위의 예시에서 가장 최근 메시지는 로컬 사용자가 보낸 것이 아닙니다. 이 점이 중요한 이유는 ML Kit는 앱 사용자, 즉 로컬 사용자가 보낼 답장을 추천하기 때문입니다. ML Kit에 전달하는 대화 로그가 사용자가 답장을 보내려고 하는 메시지로 끝나는지 확인해야 합니다.
2. 메시지 답장 가져오기
메시지에 대한 스마트 답장을 생성하려면 FirebaseSmartReply
의 인스턴스를 가져와 suggestReplies()
메서드에 대화 기록을 전달합니다.
자바
FirebaseSmartReply smartReply = FirebaseNaturalLanguage.getInstance().getSmartReply();
smartReply.suggestReplies(conversation)
.addOnSuccessListener(new OnSuccessListener<SmartReplySuggestionResult>() {
@Override
public void onSuccess(SmartReplySuggestionResult result) {
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so the
// 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
// ...
}
});
Kotlin
val smartReply = FirebaseNaturalLanguage.getInstance().smartReply
smartReply.suggestReplies(conversation)
.addOnSuccessListener { result ->
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so the
// the result doesn't contain any suggestions.
} else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
// Task completed successfully
// ...
}
}
.addOnFailureListener {
// Task failed with an exception
// ...
}
작업이 성공할 경우 SmartReplySuggestionResult
객체가 성공 핸들러에 전달됩니다. 이 객체에 사용자에게 표시할 수 있는 최대 3개의 추천 답장 목록이 포함됩니다.
자바
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
}
Kotlin
for (suggestion in result.suggestions) {
val replyText = suggestion.text
}
모델이 추천 답장의 관련성을 확신할 수 없거나, 입력 대화가 영어가 아니거나, 모델이 민감한 주제를 감지할 경우 ML Kit가 결과를 반환하지 않을 수 있습니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-16(UTC)
[null,null,["최종 업데이트: 2025-08-16(UTC)"],[],[],null,["# Generate Smart Replies with ML Kit on Android\n\nYou can use ML Kit to generate message replies using an on-device\nmodel.\n\nTo generate smart replies, you pass ML Kit a log of recent messages in a\nconversation. If ML Kit determines the conversation is in English, and that\nthe conversation doesn't have potentially sensitive subject matter, ML Kit\ngenerates up to three replies, which you can suggest to your user.\n\n\u003cbr /\u003e\n\nBefore you begin\n----------------\n\n1. If you haven't already, [add Firebase to your Android project](/docs/android/setup).\n2. Add the dependencies for the ML Kit Android libraries to your module (app-level) Gradle file (usually `app/build.gradle`): \n\n ```carbon\n apply plugin: 'com.android.application'\n apply plugin: 'com.google.gms.google-services'\n\n dependencies {\n // ...\n implementation 'com.google.firebase:firebase-ml-natural-language:22.0.0'\n implementation 'com.google.firebase:firebase-ml-natural-language-smart-reply-model:20.0.7'\n }\n ```\n3. Also in your app-level `build.gradle` file, disable compression of `tflite` files: \n\n ```text\n android {\n // ...\n aaptOptions {\n noCompress \"tflite\"\n }\n }\n ```\n\n1. Create a conversation history object\n---------------------------------------\n\nTo generate smart replies, you pass ML Kit a chronologically-ordered `List`\nof `FirebaseTextMessage` objects, with the earliest timestamp first.\n\nWhenever the user sends a message, add the message and its timestamp to the\nconversation history: \n\n### Java\n\n conversation.add(FirebaseTextMessage.createForLocalUser(\n \"heading out now\", System.currentTimeMillis()));\n\n### Kotlin\n\n conversation.add(FirebaseTextMessage.createForLocalUser(\n \"heading out now\", System.currentTimeMillis()))\n\nWhenever the user receives a message, add the message, its timestamp, and the\nsender's user ID to the conversation history. The user ID can be any string that\nuniquely identifies the sender within the conversation. The user ID doesn't need\nto correspond to any user data, and the user ID doesn't need to be consistent\nbetween conversation or invocations of the smart reply generator. \n\n### Java\n\n conversation.add(FirebaseTextMessage.createForRemoteUser(\n \"Are you coming back soon?\", System.currentTimeMillis(), userId));\n\n### Kotlin\n\n conversation.add(FirebaseTextMessage.createForRemoteUser(\n \"Are you coming back soon?\", System.currentTimeMillis(), userId))\n\nA conversation history object looks like the following example:\n\n| Timestamp | User ID | Local User? | Message |\n|------------------------------|---------|-------------|----------------------|\n| Thu Feb 21 13:13:39 PST 2019 | | true | are you on your way? |\n| Thu Feb 21 13:15:03 PST 2019 | FRIEND0 | false | Running late, sorry! |\n\nNote that the most recent message in the example above is from a non-local\nuser. This is important because ML Kit suggests replies intended to be sent\nby the user of your app: the local user. You should be sure you're passing\nML Kit a conversation log that ends with a message to which your user might\nwant to reply.\n\n2. Get message replies\n----------------------\n\nTo generate smart replies to a message, get an instance of `FirebaseSmartReply`\nand pass the conversation history to its `suggestReplies()` method: \n\n### Java\n\n FirebaseSmartReply smartReply = FirebaseNaturalLanguage.getInstance().getSmartReply();\n smartReply.suggestReplies(conversation)\n .addOnSuccessListener(new OnSuccessListener\u003cSmartReplySuggestionResult\u003e() {\n @Override\n public void onSuccess(SmartReplySuggestionResult result) {\n if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {\n // The conversation's language isn't supported, so the\n // the result doesn't contain any suggestions.\n } else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {\n // Task completed successfully\n // ...\n }\n }\n })\n .addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n // Task failed with an exception\n // ...\n }\n });\n\n### Kotlin\n\n val smartReply = FirebaseNaturalLanguage.getInstance().smartReply\n smartReply.suggestReplies(conversation)\n .addOnSuccessListener { result -\u003e\n if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {\n // The conversation's language isn't supported, so the\n // the result doesn't contain any suggestions.\n } else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {\n // Task completed successfully\n // ...\n }\n }\n .addOnFailureListener {\n // Task failed with an exception\n // ...\n }\n\nIf the operation succeeds, a `SmartReplySuggestionResult` object is passed to\nthe success handler. This object contains a list of up to 3 suggested replies,\nwhich you can present to your user: \n\n### Java\n\n for (SmartReplySuggestion suggestion : result.getSuggestions()) {\n String replyText = suggestion.getText();\n }\n\n### Kotlin\n\n for (suggestion in result.suggestions) {\n val replyText = suggestion.text\n }\n\nNote that ML Kit might not return results if the model isn't confident in\nthe relevance of the suggested replies, the input conversation isn't in\nEnglish, or if the model detects sensitive subject matter."]]