Tạo câu trả lời thông minh bằng Bộ công cụ học máy trên iOS
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 câu trả lời ngắn cho tin nhắn bằng mô hình trên thiết bị.
Để tạo các 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 vào 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 là bằng tiếng Anh và
cuộc trò chuyện không có vấn đề có thể nhạy cảm, Bộ công cụ học máy
tạo tối đa ba câu trả lời để bạn có thể đề xuất cho người dùng của mình.
Dùng thử
Dùng thử ứng dụng mẫu để
xem ví dụ về cách sử dụng API này.
Trước khi bắt đầu
Đưa các nhóm Bộ công cụ học máy sau đây vào Podfile của bạn:
pod 'GoogleMLKit/SmartReply', '8.0.0'
Sau khi bạn cài đặt hoặc cập nhật Nhóm của dự án, hãy mở dự án Xcode của bạn bằng cách sử dụng
.xcworkspace. Bộ công cụ học máy được hỗ trợ trong Xcode phiên bản 12.4 trở lên.
1. Tạo một đối tượng nhật ký 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 mảng
TextMessage đối tượng, trong đó dấu thời gian sớm nhất xuất hiện đầu tiên. Bất cứ khi nào người dùng
gửi hoặc nhận tin nhắn, thêm tin nhắn, dấu thời gian và nội dung tin nhắn
mã nhận dạng người dùng của người gửi vào lịch sử cuộc trò chuyện.
User ID 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 phải 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 phải nhất quán giữa các cuộc trò chuyện hoặc
các lệnh gọi của trình tạo phản hồi thông minh.
Nếu thư được gửi bởi người dùng mà bạn muốn đề xuất trả lời, hãy đặt
isLocalUser thành true.
Swift
varconversation:[TextMessage]=[]// Then, for each message sent and received:letmessage=TextMessage(text:"How are you?",timestamp:Date().timeIntervalSince1970,userID:"userId",isLocalUser:false)conversation.append(message)
Objective-C
NSMutableArray*conversation=[NSMutableArrayarray];// Then, for each message sent and received:MLKTextMessage*message=[[MLKTextMessagealloc]initWithText:@"How are you?"timestamp:[NSDatedate].timeIntervalSince1970userID:userIdisLocalUser:NO];[conversationaddObject:message];
Đối tượng nhật ký trò chuyện sẽ có dạng như trong ví dụ sau:
Dấu thời gian
userID
isLocalUser
Thông điệp
Thứ Năm, ngày 21 tháng 2 13:13:39 theo giờ PST 2019
đúng
bạn đang trên đường đi chưa?
Thứ Năm, ngày 21 tháng 2 13:15:03 theo giờ PST 2019
BẠN BÈ
false
Xin lỗi bạn vì muộn giờ!
Bộ công cụ học máy đề xuất câu 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 đến từ một người dùng không phải người dùng bản địa. Trong ví dụ trên, thư cuối cùng trong cuộc trò chuyện
là từ người dùng không bản địa FRIEND0. Khi bạn sử dụng thẻ và vé của Bộ công cụ học máy, nhật ký này sẽ đề xuất
trả lời tin nhắn của FRIENDO: "Rất tiếc vì lỡ cơ hội!"
2. Nhận tin nhắn trả lời
Để tạo câu trả lời thông minh cho một tin nhắn, hãy lấy thực thể của SmartReply và truyền
lịch sử cuộc trò chuyện vào phương thức suggestReplies(for:completion:):
Swift
SmartReply.smartReply().suggestReplies(for:conversation){result,erroringuarderror==nil,letresult=resultelse{return}if(result.status==.notSupportedLanguage){// The conversation's language isn't supported, so// the result doesn't contain any suggestions.}elseif(result.status==.success){// Successfully suggested smart replies.// ...}}
Objective-C
MLKSmartReply*smartReply=[MLKSmartReplysmartReply];[smartReplysuggestRepliesForMessages:inputTextcompletion:^(MLKSmartReplySuggestionResult*_Nullableresult,NSError*_Nullableerror){if(error||!result){return;}if(result.status==MLKSmartReplyResultStatusNotSupportedLanguage){// The conversation's language isn't supported, so// the result doesn't contain any suggestions.}elseif(result.status==MLKSmartReplyResultStatusSuccess){// Successfully suggested smart replies.// ...}}];
Nếu thao tác thành công, đối tượng SmartReplySuggestionResult sẽ được truyền đến
trình xử lý hoàn thành. Đối tượng này chứa danh sách tối đa 3 đề xuất
mà bạn có thể hiển thị cho người dùng của mình:
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 tin tưởng vào
mức độ liên quan của các câu trả lời được đề xuất, cuộc hội thoại đầu vào không nằm trong
tiếng Anh hoặc nếu mô hình phát hiện thấy vấn đề 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-09-04 UTC."],[[["\u003cp\u003eML Kit provides an on-device model to generate smart replies for messages in English conversations, enhancing user experience and engagement.\u003c/p\u003e\n"],["\u003cp\u003eBy passing a conversation history to ML Kit, developers can receive up to three suggested replies for the latest message, which can then be displayed to the user.\u003c/p\u003e\n"],["\u003cp\u003eBefore utilizing the API, ensure the device is 64-bit and include the necessary ML Kit pods in your project.\u003c/p\u003e\n"],["\u003cp\u003eThe smart reply feature is optimized for non-sensitive conversations, and may not generate results if the language is unsupported or sensitive topics are detected.\u003c/p\u003e\n"]]],[],null,["ML 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| **Note:** ML Kit iOS APIs only run on 64-bit devices. If you build your app with 32-bit support, check the device's architecture before using this API.\n\nTry it out\n\n- Play around with [the sample app](https://github.com/googlesamples/mlkit/tree/master/ios/quickstarts/smartreply) to see an example usage of this API.\n\nBefore you begin\n\n1. Include the following ML Kit pods in your Podfile: \n\n ```\n pod 'GoogleMLKit/SmartReply', '8.0.0'\n ```\n2. After you install or update your project's Pods, open your Xcode project using its `.xcworkspace`. ML Kit is supported in Xcode version 12.4 or greater.\n\n1. Create a conversation history object\n\nTo generate smart replies, you pass ML Kit a chronologically-ordered array of\n`TextMessage` objects, with the earliest timestamp first. Whenever the user\nsends or receives a message, add the message, its timestamp, and the message\nsender's user ID to the conversation history.\n\nThe user ID can be any string that uniquely identifies the sender within the\nconversation. The user ID doesn't need to correspond to any user data,\nand the user ID doesn't need to be consistent between conversations or\ninvocations of the smart reply generator.\n\nIf the message was sent by the user you want to suggest replies to, set\n`isLocalUser` to true. \n\nSwift \n\n```swift\nvar conversation: [TextMessage] = []\n\n// Then, for each message sent and received:\nlet message = TextMessage(\n text: \"How are you?\",\n timestamp: Date().timeIntervalSince1970,\n userID: \"userId\",\n isLocalUser: false)\nconversation.append(message)\n```\n\nObjective-C \n\n```objective-c\nNSMutableArray *conversation = [NSMutableArray array];\n\n// Then, for each message sent and received:\nMLKTextMessage *message = [[MLKTextMessage alloc]\n initWithText:@\"How are you?\"\n timestamp:[NSDate date].timeIntervalSince1970\n userID:userId\n isLocalUser:NO];\n[conversation addObject:message];\n```\n\nA 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\nML Kit suggests replies to the last message in a conversation history. The last message\nshould be from a non-local user. In the example above, the last message in the conversation\nis from the non-local user FRIEND0. When you use pass ML Kit this log, it suggests\nreplies to FRIENDO's message: \"Running late, sorry!\"\n\n2. Get message replies\n\nTo generate smart replies to a message, get an instance of `SmartReply` and pass\nthe conversation history to its `suggestReplies(for:completion:)` method: \n\nSwift \n\n```swift\nSmartReply.smartReply().suggestReplies(for: conversation) { result, error in\n guard error == nil, let result = result else {\n return\n }\n if (result.status == .notSupportedLanguage) {\n // The conversation's language isn't supported, so\n // the result doesn't contain any suggestions.\n } else if (result.status == .success) {\n // Successfully suggested smart replies.\n // ...\n }\n}\n```\n\nObjective-C \n\n```objective-c\nMLKSmartReply *smartReply = [MLKSmartReply smartReply];\n[smartReply suggestRepliesForMessages:inputText\n completion:^(MLKSmartReplySuggestionResult * _Nullable result,\n NSError * _Nullable error) {\n if (error || !result) {\n return;\n }\n if (result.status == MLKSmartReplyResultStatusNotSupportedLanguage) {\n // The conversation's language isn't supported, so\n // the result doesn't contain any suggestions.\n } else if (result.status == MLKSmartReplyResultStatusSuccess) {\n // Successfully suggested smart replies.\n // ...\n }\n}];\n```\n\nIf the operation succeeds, a `SmartReplySuggestionResult` object is passed to\nthe completion handler. This object contains a list of up to three suggested\nreplies, which you can present to your user: \n\nSwift \n\n```swift\nfor suggestion in result.suggestions {\n print(\"Suggested reply: \\(suggestion.text)\")\n}\n```\n\nObjective-C \n\n```objective-c\nfor (MLKSmartReplySuggestion *suggestion in result.suggestions) {\n NSLog(@\"Suggested reply: %@\", suggestion.text);\n}\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."]]