您可以使用 ML Kit 使用裝置上的模型產生訊息回覆。
要產生智慧回复,您可以向 ML Kit 傳遞對話中最近訊息的日誌。如果 ML Kit 確定對話是英語,且對話沒有潛在的敏感主題,ML Kit 會產生最多三個回复,您可以向用戶建議這些回复。
在你開始之前
- 如果您尚未將 Firebase 新增至您的應用程式中,請按照入門指南中的步驟進行操作。
- 在 Podfile 中包含 ML Kit 函式庫:
pod 'Firebase/MLCommon', '6.25.0' pod 'Firebase/MLNLSmartReply', '6.25.0'
安裝或更新專案的 Pod 後,請務必使用其.xcworkspace
開啟 Xcode 專案。 - 在您的應用程式中,導入 Firebase:
迅速
import Firebase
Objective-C
@import Firebase;
1. 建立對話歷史對象
要產生智慧回复,您可以向 ML Kit 傳遞一個按時間順序排列的TextMessage
物件數組,其中最早的時間戳在前。每當使用者傳送或接收訊息時,都會將訊息、其時間戳記和訊息傳送者的使用者 ID 新增至對話記錄中。
使用者 ID 可以是對話中唯一標識寄件者的任何字串。用戶ID不需要對應到任何用戶數據,且用戶ID不需要在智慧回復生成器的對話或呼叫之間保持一致。
如果訊息是由您想要建議回覆的使用者發送的,請將isLocalUser
設定為 true。
迅速
var conversation: [TextMessage] = []
// Then, for each message sent and received:
let message = TextMessage(
text: "How are you?",
timestamp: Date().timeIntervalSince1970,
userID: "userId",
isLocalUser: false)
conversation.append(message)
Objective-C
NSMutableArray *conversation = [NSMutableArray array];
// Then, for each message sent and received:
FIRTextMessage *message = [[FIRTextMessage alloc]
initWithText:@"How are you?"
timestamp:[NSDate date].timeIntervalSince1970
userID:userId
isLocalUser:NO];
[conversation addObject:message];
對話歷史記錄物件如下例所示:
時間戳 | 使用者身分 | 本地用戶? | 訊息 |
---|---|---|---|
2019 年 2 月 21 日星期四 13:13:39(太平洋標準時間) | 真的 | 你在路上嗎? | |
2019 年 2 月 21 日星期四 13:15:03(太平洋標準時間) | 朋友0 | 錯誤的 | 遲到了,抱歉! |
請注意,上例中的最新消息來自非本地用戶。這很重要,因為 ML Kit 建議由應用程式的使用者(本機使用者)發送的回應。您應該確保向 ML Kit 傳遞一個對話日誌,該日誌以用戶可能想要回复的訊息結尾。
2. 獲取訊息回复
要產生對訊息的智慧回复,請取得SmartReply
的實例並將對話歷史記錄傳遞給其suggestReplies(for:completion:)
方法:
迅速
let naturalLanguage = NaturalLanguage.naturalLanguage()
naturalLanguage.smartReply().suggestReplies(for: conversation) { result, error in
guard error == nil, let result = result else {
return
}
if (result.status == .notSupportedLanguage) {
// The conversation's language isn't supported, so the
// the result doesn't contain any suggestions.
} else if (result.status == .success) {
// Successfully suggested smart replies.
// ...
}
}
Objective-C
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRSmartReply *smartReply = [naturalLanguage smartReply];
[smartReply suggestRepliesForMessages:inputText
completion:^(FIRSmartReplySuggestionResult * _Nullable result,
NSError * _Nullable error) {
if (error || !result) {
return;
}
if (result.status == FIRSmartReplyResultStatusNotSupportedLanguage) {
// The conversation's language isn't supported, so the
// the result doesn't contain any suggestions.
} else if (result.status == FIRSmartReplyResultStatusSuccess) {
// Successfully suggested smart replies.
// ...
}
}];
]
如果操作成功, SmartReplySuggestionResult
物件將傳遞至完成處理程序。此物件包含最多 3 個建議回應的列表,您可以將其呈現給使用者:
迅速
for suggestion in result.suggestions {
print("Suggested reply: \(suggestion.text)")
}
Objective-C
for (FIRSmartReplySuggestion *suggestion in result.suggestions) {
NSLog(@"Suggested reply: %@", suggestion.text);
}
請注意,如果模型對建議回應的相關性沒有信心、輸入對話不是英語或模型偵測到敏感主題,ML Kit 可能不會傳回結果。