在 iOS 上使用 ML Kit 產生智慧回覆

機器學習套件可透過裝置端模型產生訊息的簡短回覆。

如要產生智慧回覆,請將對話中最近的訊息記錄傳送給 ML Kit。如果機器學習套件判定對話內容為英文,而且對話可能沒有敏感的主旨,則機器學習套件會產生最多三則回覆,您可以向使用者建議。

立即體驗

事前準備

  1. 在 Podfile 中加入下列機器學習套件 Pod:
    pod 'GoogleMLKit/SmartReply', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,使用 .xcworkspace 開啟 Xcode 專案。Xcode 12.4 以上版本支援機器學習套件。

1. 建立對話記錄物件

如要產生智慧回覆,您必須按照時間先後順序排列的 TextMessage 物件,將機器學習套件按順序排列至最早時間戳記。每當使用者收發訊息時,請將訊息、時間戳記和訊息傳送者的使用者 ID 新增至對話記錄。

使用者 ID 可以是對話中唯一識別傳送者的字串。使用者 ID 不需要對應到任何使用者資料,且智慧回覆產生器的對話或叫用之間不需要使用者 ID。

如果訊息是由您建議回覆的使用者傳送,請將 isLocalUser 設為 true。

Swift

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:
MLKTextMessage *message = [[MLKTextMessage alloc]
        initWithText:@"How are you?"
        timestamp:[NSDate date].timeIntervalSince1970
        userID:userId
        isLocalUser:NO];
[conversation addObject:message];

對話記錄物件如下列範例所示:

時間戳記 使用者 ID isLocalUser 訊息
2019 年 2 月 21 日星期四 13:13:39 PST true 您正在路上嗎?
2019 年 2 月 21 日星期四 13:15:03 PST 好友 0 太晚了,很抱歉!

ML Kit 會提供對話記錄中的最後一則訊息回覆。最後一則訊息必須來自非本地使用者。在上述範例中,對話中的最後一則訊息是來自非本地使用者 FRIEND0。使用 Pass ML Kit 時,這個建議會提供「FRIENDO」訊息的回覆:「晚點,抱歉!」

2. 接收訊息回覆

如要產生訊息的智慧回覆,請取得 SmartReply 的例項,並將對話記錄傳送至其 suggestReplies(for:completion:) 方法:

Swift

SmartReply.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 result doesn't contain any suggestions.
    } else if (result.status == .success) {
        // Successfully suggested smart replies.
        // ...
    }
}

Objective-C

MLKSmartReply *smartReply = [MLKSmartReply smartReply];
[smartReply suggestRepliesForMessages:inputText
                           completion:^(MLKSmartReplySuggestionResult * _Nullable result,
                                        NSError * _Nullable error) {
  if (error || !result) {
    return;
  }
  if (result.status == MLKSmartReplyResultStatusNotSupportedLanguage) {
      // The conversation's language isn't supported, so
      // the result doesn't contain any suggestions.
  } else if (result.status == MLKSmartReplyResultStatusSuccess) {
      // Successfully suggested smart replies.
      // ...
  }
}];

如果作業成功,系統會將 SmartReplySuggestionResult 物件傳遞至完成處理常式。這個物件含有最多三個建議的回覆,您可提供給使用者:

Swift

for suggestion in result.suggestions {
  print("Suggested reply: \(suggestion.text)")
}

Objective-C

for (MLKSmartReplySuggestion *suggestion in result.suggestions) {
  NSLog(@"Suggested reply: %@", suggestion.text);
}

請注意,如果模型對建議回覆的關聯性、輸入對話內容並非英文,或模型偵測到敏感主題,就不會傳回結果。