在 Android 上使用机器学习套件生成智能回复
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
借助机器学习套件,您可以使用设备端模型来生成消息回复。
如需生成智能回复,您需要向机器学习套件传递会话中最近消息的日志。如果机器学习套件确认会话使用的语言是英语,并且其中没有潜在的敏感主题,则会生成最多三个回复,供您向用户推荐。
准备工作
- 将 Firebase 添加到您的 Android 项目(如果尚未添加)。
- 将 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. 创建会话历史记录对象
如需生成智能回复,您需要向机器学习套件传递按时间排序的 FirebaseTextMessage
对象的 List
,时间戳早的排在前面。
每当用户发送消息时,系统都会将消息及其时间戳添加到会话历史记录中:
Java
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()));
Kotlin
conversation.add(FirebaseTextMessage.createForLocalUser(
"heading out now", System.currentTimeMillis()))
每当用户收到消息时,系统都会将消息、其时间戳和发送者的用户 ID 添加到会话历史记录中。用户 ID 可以是用于在会话中唯一标识发送者的任何字符串。用户 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 |
|
true |
还在路上吗? |
太平洋标准时间 2019 年 2 月 21 日星期四 13:15:03 |
FRIEND0 |
false |
要迟到了,对不起! |
请注意,上述示例中的最新消息来自非本地用户。这很重要,因为机器学习套件推荐拟由您的应用的用户(即本地用户)发送的回复。您应确保向机器学习套件传送的会话日志以用户可能想要回复的消息结束。
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
}
请注意,如果模型对推荐回复的相关性不确定、输入会话使用的语言不是英语,或者模型检测到敏感主题,机器学习套件都可能不会返回结果。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-16。
[null,null,["最后更新时间 (UTC):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."]]