在 Android 上使用 ML Kit 產生智慧回覆
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
你可以使用 ML Kit 在裝置上生成訊息回覆
模型
如要產生智慧回覆,請將 ML Kit 近期訊息記錄傳送至
對話。如果 ML Kit 判斷對話是以英文表示對話,
就沒有敏感主題的 ML Kit
最多產生 3 則回覆,您可當做建議使用者參考。
事前準備
- 如果還沒試過
將 Firebase 新增至您的 Android 專案。
- 將 ML Kit Android 程式庫的依附元件新增至模組
(應用程式層級) Gradle 檔案 (通常是
app/build.gradle
):
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 按照時間排序的List
的 FirebaseTextMessage
物件,並採用最早的時間戳記。
每當使用者傳送訊息時,請將訊息和時間戳記新增至
對話記錄:
Java
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()));
Kotlin
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()))
每當使用者收到訊息時,請新增訊息、訊息時間戳記和
並將傳送者的使用者 ID 加入對話記錄中。使用者 ID 可以是任何
可明確識別會話群組中的寄件者。User-ID 不需要
對應至任何使用者資料,而且 User-ID 不需要保持一致
。
Java
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 |
本機使用者? |
訊息 |
2019 年 2 月 21 日星期四 13:13:39 (太平洋標準時間) |
|
是 |
你正在路上嗎? |
2019 年 2 月 21 日星期四 13:15:03 (太平洋標準時間) |
朋友 |
false |
抱歉,我遲到了! |
請注意,上述範例中最新的訊息並非來自本機
內容。這很重要,因為 ML Kit 建議要傳送的回覆
也就是本機使用者確定自己能順利通過
ML Kit 對話記錄,此記錄的結尾是使用者可能前往的訊息
也就是您要回覆的對象。
2. 接收訊息回覆
如要產生訊息的智慧回覆,請取得 FirebaseSmartReply
的執行個體
並將對話記錄傳遞至其 suggestReplies()
方法:
Java
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 個建議的回覆清單
可用來向使用者顯示:
Java
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
}
Kotlin
for (suggestion in result.suggestions) {
val replyText = suggestion.text
}
請注意,如果模型對模型缺乏信心,ML Kit 可能不會傳回結果
建議回覆的關聯性,但輸入對話不在
指定語言,或模型偵測到敏感主題。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間:2025-08-16 (世界標準時間)。"],[],[],null,["You 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\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\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\nJava \n\n conversation.add(FirebaseTextMessage.createForLocalUser(\n \"heading out now\", System.currentTimeMillis()));\n\nKotlin \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\nJava \n\n conversation.add(FirebaseTextMessage.createForRemoteUser(\n \"Are you coming back soon?\", System.currentTimeMillis(), userId));\n\nKotlin \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\nTo generate smart replies to a message, get an instance of `FirebaseSmartReply`\nand pass the conversation history to its `suggestReplies()` method: \n\nJava \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\nKotlin \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\nJava \n\n for (SmartReplySuggestion suggestion : result.getSuggestions()) {\n String replyText = suggestion.getText();\n }\n\nKotlin \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."]]