Tạo phản hồi thông minh bằng Bộ công cụ học máy trên Android
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Bộ công cụ học máy có thể tạo tin nhắn trả lời ngắn cho tin nhắn bằng mô hình trên thiết bị.
Để tạo câu trả lời thông minh, bạn truyền cho Bộ công cụ học máy nhật ký các tin nhắn gần đây trong một cuộc trò chuyện. Nếu Bộ công cụ học máy xác định cuộc trò chuyện bằng tiếng Anh và cuộc trò chuyện không có chủ đề có thể nhạy cảm, thì Bộ công cụ học máy sẽ tạo tối đa 3 câu trả lời mà bạn có thể đề xuất cho người dùng.
Mô hình được liên kết tĩnh với ứng dụng của bạn tại thời điểm tạo bản dựng.
Mô hình được tải xuống một cách linh động thông qua Dịch vụ Google Play.
Tác động của kích thước ứng dụng
Tăng kích thước khoảng 5,7 MB.
Tăng kích thước khoảng 200 KB.
Thời gian khởi chạy
Mẫu có sẵn ngay.
Có thể phải đợi mô hình tải xuống trước khi sử dụng lần đầu.
Dùng thử
Hãy thử nghiệm với ứng dụng mẫu để xem ví dụ về cách sử dụng API này.
Trước khi bắt đầu
Trong tệp build.gradle cấp dự án, hãy nhớ thêm kho lưu trữ Maven của Google vào cả mục buildscript và allprojects.
Thêm các phần phụ thuộc cho thư viện Android của Bộ công cụ học máy vào tệp gradle cấp ứng dụng của mô-đun, thường là app/build.gradle. Chọn một trong các phần phụ thuộc sau đây dựa trên nhu cầu của bạn:
Cách gói mô hình với ứng dụng:
dependencies{// ...// Use this dependency to bundle the model with your appimplementation'com.google.mlkit:smart-reply:17.0.4'}
Nếu chọn sử dụng mô hình trong Dịch vụ Google Play, bạn có thể định cấu hình ứng dụng để tự động tải mô hình xuống thiết bị sau khi cài đặt ứng dụng từ Cửa hàng Play. Bằng cách thêm nội dung khai báo sau vào tệp AndroidManifest.xml của ứng dụng:
Bạn cũng có thể kiểm tra rõ ràng tình trạng có sẵn của mô hình và yêu cầu tải xuống thông qua ModuleInstallClient API của Dịch vụ Google Play.
Nếu bạn không bật tính năng tải mô hình xuống tại thời điểm cài đặt hoặc yêu cầu tải xuống rõ ràng, mô hình sẽ được tải xuống trong lần đầu tiên bạn chạy trình tạo câu trả lời thông minh.
Các yêu cầu bạn đưa ra trước khi quá trình tải xuống hoàn tất sẽ không có kết quả.
1. Tạo đối tượng nhật ký cuộc trò chuyện
Để tạo câu trả lời thông minh, bạn truyền cho Bộ công cụ học máy một List
của các đối tượng TextMessage theo thứ tự thời gian, trong đó dấu thời gian sớm nhất sẽ xuất hiện trước tiên.
Bất cứ khi nào người dùng gửi tin nhắn, hãy thêm tin nhắn và dấu thời gian của tin nhắn đó vào bản ghi cuộc trò chuyện:
Kotlin
conversation.add(TextMessage.createForLocalUser("heading out now",System.currentTimeMillis()))
Java
conversation.add(TextMessage.createForLocalUser("heading out now",System.currentTimeMillis()));
Bất cứ khi nào người dùng nhận được tin nhắn, hãy thêm tin nhắn, dấu thời gian và mã nhận dạng người dùng của người gửi vào nhật ký trò chuyện. Mã nhận dạng người dùng có thể là bất kỳ chuỗi nào xác định duy nhất người gửi trong cuộc trò chuyện. Mã nhận dạng người dùng không cần tương ứng với bất kỳ dữ liệu người dùng nào và mã nhận dạng người dùng không cần nhất quán giữa cuộc trò chuyện hoặc lệnh gọi của trình tạo câu trả lời thông minh.
Kotlin
conversation.add(TextMessage.createForRemoteUser("Are you coming back soon?",System.currentTimeMillis(),userId))
Java
conversation.add(TextMessage.createForRemoteUser("Are you coming back soon?",System.currentTimeMillis(),userId));
Đối tượng nhật ký trò chuyện có dạng như ví dụ sau:
Dấu thời gian
userID
isLocalUser
Thông điệp
21/2/2019 13:13:39 (giờ PST)
true
bạn đang trên đường đến đó phải không?
21/2/2019 13:15:03 (giờ PST)
FRIEND0
false
Tôi sẽ đến muộn, xin lỗi!
Bộ công cụ học máy đề xuất nội dung trả lời cho tin nhắn gần đây nhất trong nhật ký trò chuyện. Thông báo gần đây nhất phải là của một người dùng không phải người địa phương. Trong ví dụ trên, tin nhắn cuối cùng trong cuộc trò chuyện là của người dùng không phải người dùng cục bộ FRIEND0. Khi bạn sử dụng tính năng truyền nhật ký này cho Bộ công cụ học máy, tính năng này sẽ đề xuất nội dung trả lời cho tin nhắn của FRIENDO: "Tôi đến muộn, xin lỗi!"
2. Nhận thư trả lời
Để tạo câu trả lời thông minh cho một tin nhắn, hãy lấy một thực thể của SmartReplyGenerator và truyền nhật ký trò chuyện vào phương thức suggestReplies() của thực thể đó:
Kotlin
valsmartReplyGenerator=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.}elseif(result.getStatus()==SmartReplySuggestionResult.STATUS_SUCCESS){// Task completed successfully// ...}}.addOnFailureListener{// Task failed with an exception// ...}
Java
SmartReplyGeneratorsmartReply=SmartReply.getClient();smartReply.suggestReplies(conversation).addOnSuccessListener(newOnSuccessListener(){@OverridepublicvoidonSuccess(SmartReplySuggestionResultresult){if(result.getStatus()==SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE){// The conversation's language isn't supported, so// the result doesn't contain any suggestions.}elseif(result.getStatus()==SmartReplySuggestionResult.STATUS_SUCCESS){// Task completed successfully// ...}}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){// Task failed with an exception// ...}});
Nếu thao tác thành công, đối tượng SmartReplySuggestionResult sẽ được truyền đến trình xử lý thành công. Đối tượng này chứa danh sách tối đa 3 câu trả lời được đề xuất mà bạn có thể hiển thị cho người dùng:
Xin lưu ý rằng Bộ công cụ học máy có thể không trả về kết quả nếu mô hình không chắc chắn về mức độ liên quan của các câu trả lời được đề xuất, cuộc trò chuyện đầu vào không bằng tiếng Anh hoặc nếu mô hình phát hiện thấy chủ đề nhạy cảm.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-08-17 UTC."],[[["\u003cp\u003eML Kit's Smart Reply API generates up to three relevant reply suggestions for English conversations using an on-device model.\u003c/p\u003e\n"],["\u003cp\u003eYou can integrate Smart Reply by either bundling the model with your app (larger size) or dynamically downloading it (smaller size, requires Google Play Services).\u003c/p\u003e\n"],["\u003cp\u003eTo use the API, provide a conversation history as input, and ML Kit will suggest replies to the last message if it's from a non-local user.\u003c/p\u003e\n"],["\u003cp\u003eThe suggested replies are returned only if the conversation is in English, does not contain sensitive content, and the model is confident in their relevance.\u003c/p\u003e\n"]]],["ML Kit generates up to three smart replies to messages in English conversations, excluding sensitive content. This is done by passing a chronologically ordered list of `TextMessage` objects to the `suggestReplies()` method. The API can use a bundled model (5.7 MB increase) or an unbundled model (200 KB increase) via Google Play Services. The unbundled model may have a delay before the first use, and may not include any results. Implementation requires adding the appropriate library dependency and building the conversation history.\n"],null,["# Generate smart replies with ML Kit on Android\n\nML Kit can generate short replies to messages using an on-device model.\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\n| This API is available using either an unbundled library that must be downloaded before use or a bundled library that increases your app size. See [this guide](/ml-kit/tips/installation-paths) for more information on the differences between the two installation options.\n\n| | Bundled | Unbundled |\n|-------------------------|-------------------------------------------------------|------------------------------------------------------------|\n| **Library name** | `com.google.mlkit:smart-reply` | `com.google.android.gms:play-services-mlkit-smart-reply` |\n| **Implementation** | Model is statically linked to your app at build time. | Model is dynamically downloaded via Google Play Services. |\n| **App size impact** | About 5.7 MB size increase. | About 200 KB size increase. |\n| **Initialization time** | Model is available immediately. | Might have to wait for model to download before first use. |\n\n| **Note:** The unbundled version of Smart Reply is currently offered in beta, which means it might be changed in backward-incompatible ways and is not subject to any SLA or deprecation policy.\n\nTry it out\n----------\n\n- Play around with [the sample app](https://github.com/googlesamples/mlkit/tree/master/android/smartreply) to see an example usage of this API.\n\nBefore you begin\n----------------\n\n| This API requires Android API level 21 or above. Make sure that your app's build file uses a `minSdkVersion` value of 21 or higher.\n\n1. In your project-level `build.gradle` file, make sure to include Google's\n Maven repository in both your `buildscript` and `allprojects` sections.\n\n2. Add the dependencies for the ML Kit Android libraries to your module's\n app-level gradle file, which is usually `app/build.gradle`. Choose one of\n the following dependencies based on your needs:\n\n - To bundle the model with your app:\n\n dependencies {\n // ...\n // Use this dependency to bundle the model with your app\n implementation 'com.google.mlkit:smart-reply:17.0.4'\n }\n\n - To use the model in Google Play Services:\n\n dependencies {\n // ...\n // Use this dependency to use the dynamically downloaded model in Google Play Services\n implementation 'com.google.android.gms:play-services-mlkit-smart-reply:16.0.0-beta1'\n }\n\n If you choose to use the model in Google Play Services, you can configure\n your app to automatically download the model to the device after your app is\n installed from the Play Store. By adding the following declaration to your\n app's `AndroidManifest.xml` file: \n\n \u003capplication ...\u003e\n ...\n \u003cmeta-data\n android:name=\"com.google.mlkit.vision.DEPENDENCIES\"\n android:value=\"smart_reply\" \u003e\n \u003c!-- To use multiple models: android:value=\"smart_reply,model2,model3\" --\u003e\n \u003c/application\u003e\n\n You can also explicitly check the model availability and request download through\n Google Play services [ModuleInstallClient API](https://developers.google.com/android/guides/module-install-apis).\n\n If you don't enable install-time model downloads or request explicit download,\n the model is downloaded the first time you run the smart reply generator.\n Requests you make before the download has completed produce no results.\n\n\n 1. Create a conversation history object\n ---------------------------------------\n\n To generate smart replies, you pass ML Kit a chronologically-ordered `List`\n of `TextMessage` objects, with the earliest timestamp first.\n\n Whenever the user sends a message, add the message and its timestamp to the\n conversation history: \n\n ### Kotlin\n\n ```kotlin\n conversation.add(TextMessage.createForLocalUser(\n \"heading out now\", System.currentTimeMillis()))\n ```\n\n ### Java\n\n ```java\n conversation.add(TextMessage.createForLocalUser(\n \"heading out now\", System.currentTimeMillis()));\n ```\n\n Whenever the user receives a message, add the message, its timestamp, and the\n sender's user ID to the conversation history. The user ID can be any string that\n uniquely identifies the sender within the conversation. The user ID doesn't need\n to correspond to any user data, and the user ID doesn't need to be consistent\n between conversation or invocations of the smart reply generator. \n\n ### Kotlin\n\n ```kotlin\n conversation.add(TextMessage.createForRemoteUser(\n \"Are you coming back soon?\", System.currentTimeMillis(), userId))\n ```\n\n ### Java\n\n ```java\n conversation.add(TextMessage.createForRemoteUser(\n \"Are you coming back soon?\", System.currentTimeMillis(), userId));\n ```\n\n A conversation history object looks like the following example:\n\n | Timestamp | userID | isLocalUser | 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\n ML Kit suggests replies to the last message in a conversation history. The last message\n should be from a non-local user. In the example above, the last message in the conversation\n is from the non-local user FRIEND0. When you use pass ML Kit this log, it suggests\n replies to FRIENDO's message: \"Running late, sorry!\"\n\n 2. Get message replies\n ----------------------\n\n To generate smart replies to a message, get an instance of `SmartReplyGenerator`\n and pass the conversation history to its `suggestReplies()` method: \n\n ### Kotlin\n\n ```kotlin\n val smartReplyGenerator = SmartReply.getClient()\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\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 ```\n\n ### Java\n\n ```java\n SmartReplyGenerator smartReply = SmartReply.getClient();\n smartReply.suggestReplies(conversation)\n .addOnSuccessListener(new OnSuccessListener() {\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\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\n If the operation succeeds, a `SmartReplySuggestionResult` object is passed to\n the success handler. This object contains a list of up to three suggested replies,\n which you can present to your user: \n\n ### Kotlin\n\n ```kotlin\n for (suggestion in result.suggestions) {\n val replyText = suggestion.text\n }\n ```\n\n ### Java\n\n ```java\n for (SmartReplySuggestion suggestion : result.getSuggestions()) {\n String replyText = suggestion.getText();\n }\n ```\n\n Note that ML Kit might not return results if the model isn't confident in\n the relevance of the suggested replies, the input conversation isn't in\n English, or if the model detects sensitive subject matter."]]