GenAI Rewriting API

您可以使用 ML Kit 的 GenAI Rewriting API,自動協助使用者以不同風格或語氣重寫即時通訊訊息或短篇內容。

在下列情況下,使用者可能會覺得,提供如何重寫內容的建議會很有幫助:

  • 重新調整訊息結構,讓與利害關係人溝通時更專業
  • 縮短訊息,以便在社群媒體平台上發布
  • 為非母語人士重述訊息,讓他們瞭解傳達訊息的其他方式

主要功能

ML Kit 的 GenAI Rewriting API 可使用下列其中一種風格重寫短篇內容:

  • 詳述:使用更多詳細資訊和描述性語言來擴充輸入文字。
  • Emojify:在輸入文字中加入相關表情符號,讓文字更具表達力和趣味。
  • 精簡:將輸入的文字濃縮為較短的版本,但仍保留核心訊息。
  • 親切:使用對話語氣,將輸入的文字改寫成更輕鬆、親切的內容。
  • 專業:使用尊重語氣,將輸入的文字改寫成更正式、更像商務內容的內容。
  • 改寫:使用不同的字詞和句子結構重寫輸入的文字,同時保留原始意義。

要求會傳回至少一個建議。如果系統傳回多項建議,結果會依信心程度由高至低排序。

搜尋結果範例

輸入功率 重寫樣式 輸出內容
你想約時間進一步討論嗎? 專業 您是否有興趣再次與我們會面,進一步討論這個問題?
我希望您能參加我即將在本週六晚間於家中舉辦的輕鬆聚會 精簡 你想在本週六晚上到我家參加輕鬆的聚會嗎?
事件已成功執行 詳述 這項活動大獲成功,超越了我們的預期,也證明瞭這項活動的成功。
我們不久後一起喝杯咖啡吧 轉換表情符號 我們不久後再一起喝杯咖啡吧 ☕ 👋。
在當天結束前提供報表 友誼賽 請在今天結束前提供報表。
嗨,我需要盡快取得那個東西 專業 請盡快提供要求的文件。
專案進度落後 改寫 專案時間表需要調整,才能符合原先的期限

開始使用

如要開始使用 GenAI Rewriting API,請將這個依附元件新增至專案的建構檔案。

implementation("com.google.mlkit:genai-rewriting:1.0.0-beta1")

接著,請使用必要選項將 Rewriter 用戶端例項化,檢查是否可使用所需的裝置端模型功能 (並視需要下載),準備輸入文字做為要求,執行重寫程序以取得建議,然後釋出資源。

Kotlin

val textToRewrite = "The event was successful"

// Define task with selected input and output format
val rewriterOptions = RewriterOptions.builder(context)
    // OutputType can be one of the following: ELABORATE, EMOJIFY, SHORTEN,
    // FRIENDLY, PROFESSIONAL, REPHRASE
    .setOutputType(RewriterOptions.OutputType.ELABORATE)
    // Refer to RewriterOptions.Language for available languages
    .setLanguage(RewriterOptions.Language.ENGLISH)
    .build()
val rewriter = Rewriting.getClient(rewriterOptions)

suspend fun prepareAndStartRewrite() {
    // Check feature availability, status will be one of the following:
    // UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    val featureStatus = rewriter.checkFeatureStatus().await()

    if (featureStatus == FeatureStatus.DOWNLOADABLE) {
        // Download feature if necessary.
        // If downloadFeature is not called, the first inference request will
        // also trigger the feature to be downloaded if it's not already
        // downloaded.
        rewriter.downloadFeature(object : DownloadCallback {
            override fun onDownloadStarted(bytesToDownload: Long) { }

            override fun onDownloadFailed(e: GenAiException) { }

            override fun onDownloadProgress(totalBytesDownloaded: Long) {}

            override fun onDownloadCompleted() {
                startRewritingRequest(textToRewrite, rewriter)
            }
        })
    } else if (featureStatus == FeatureStatus.DOWNLOADING) {
        // Inference request will automatically run once feature is
        // downloaded.
        // If Gemini Nano is already downloaded on the device, the
        // feature-specific LoRA adapter model will be downloaded
        // quickly. However, if Gemini Nano is not already downloaded,
        // the download process may take longer.
        startRewritingRequest(textToRewrite, rewriter)
    } else if (featureStatus == FeatureStatus.AVAILABLE) {
        startRewritingRequest(textToRewrite, rewriter)
    }
}

suspend fun startRewritingRequest(text: String, rewriter: Rewriter) {
    // Create task request
    val rewritingRequest = RewritingRequest.builder(text).build()

    // Start rewriting request with non-streaming response
    // More than 1 result may be returned. If multiple suggestions are
    // returned, results will be sorted by descending confidence.
    val rewriteResults =
        rewriter.runInference(rewritingRequest).await().results

    // You can also start a streaming request
    // rewriter.runInference(rewritingRequest) { newText ->
    //    // Show new text in UI
    // }
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
rewriter.close()

Java

String textToRewrite = "The event was successful";

// Define task with required input and output format
RewriterOptions rewriterOptions =
    RewriterOptions.builder(context)
        // OutputType can be one of the following: ELABORATE,
        // EMOJIFY, SHORTEN, FRIENDLY, PROFESSIONAL, REPHRASE
        .setOutputType(RewriterOptions.OutputType.ELABORATE)
        // Refer to RewriterOptions.Language for available
        // languages
        .setLanguage(RewriterOptions.Language.ENGLISH)
        .build();
Rewriter rewriter = Rewriting.getClient(rewriterOptions);

void prepareAndStartRewrite()
    throws ExecutionException, InterruptedException {
    // Check feature availability, status will be one of the
    // following: UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    try {
        int featureStatus = rewriter.checkFeatureStatus().get();
        if (featureStatus == FeatureStatus.DOWNLOADABLE) {
            // Download feature if necessary.
            // If downloadFeature is not called, the first inference
            // request will also trigger the feature to be downloaded
            // if it's not already downloaded.
            rewriter.downloadFeature(
                new DownloadCallback() {
                    @Override
                    public void onDownloadCompleted() {
                        startRewritingRequest(textToRewrite, rewriter);
                    }

                    @Override
                    public void onDownloadFailed(GenAIException e) {}

                    @Override
                    public void onDownloadProgress(
                        long totalBytesDownloaded) {}

                    @Override
                    public void onDownloadStarted(long bytesDownloaded) {}
                });
        } else if (featureStatus == FeatureStatus.DOWNLOADING) {
            // Inference request will automatically run once feature is
            // downloaded.
            // If Gemini Nano is already downloaded on the device, the
            // feature-specific LoRA adapter model will be downloaded
            // quickly. However, if Gemini Nano is not already downloaded,
            // the download process may take longer.
            startRewritingRequest(textToRewrite, rewriter);
        } else if (featureStatus == FeatureStatus.AVAILABLE) {
            startRewritingRequest(textToRewrite, rewriter);
        }
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

void startRewritingRequest(String text, Rewriter rewriter) {
    // Create task request
    RewritingRequest rewritingRequest =
        RewritingRequest.builder(text).build();

    try {
        // Start rewriting request with non-streaming response
        // More than 1 result may be returned. If multiple
        // suggestions are returned, results will be sorted by
        // descending confidence.
        rewriter.runInference(rewritingRequest).get().getResults();

        // You can also start a streaming request
        // rewriter.runInference(rewritingRequest, newText -> {
        //     // Show new text in UI
        // });
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

// Be sure to release the resource when no longer needed
// For example, on viewModel.onCleared() or activity.onDestroy()
rewriter.close();

支援的功能和限制

GenAI Rewriting API 支援以下語言:英文、日文、法文、德文、義大利文、西班牙文和韓文,這些語言已在 RewriterOptions.Language 中定義。輸入內容不得超過 256 個符記。

特定功能設定 (由 RewriterOptions 指定) 的適用情況可能會因特定裝置的設定和已下載至裝置的模型而異。

開發人員如要確保裝置支援指定 API 功能,並提供所要求的 RewriterOptions,最可靠的方法就是呼叫 checkFeatureStatus() 方法。這個方法會在執行階段提供裝置上功能可用性的確切狀態。

常見的設定問題

ML Kit GenAI API 需要透過 Android AICore 應用程式存取 Gemini Nano。裝置剛設定完畢 (包括重設),或 AICore 應用程式剛重設 (例如清除資料、解除安裝再重新安裝),AICore 應用程式可能沒有足夠的時間完成初始化程序 (包括從伺服器下載最新設定)。因此,ML Kit GenAI API 可能無法正常運作。以下是您可能會看到的常見設定錯誤訊息,以及如何處理:

錯誤訊息示例 如何處理
AICore 發生錯誤,錯誤類型為 4-CONNECTION_ERROR,錯誤代碼為 601-BINDING_FAILURE:AICore 服務繫結失敗。 當您在裝置設定完成後立即使用 ML Kit GenAI API 安裝應用程式,或是在應用程式安裝完成後解除安裝 AICore 時,就可能發生這種情況。更新 AICore 應用程式,然後重新安裝應用程式,應該就能解決問題。
AICore 失敗,錯誤類型為 3-PREPARATION_ERROR,錯誤代碼為 606-FEATURE_NOT_FOUND:無法使用功能...。 當 AICore 尚未完成下載最新設定時,就可能發生這種情況。保持網路連線,並等待幾分鐘到幾小時。

請注意,如果裝置的系統啟動載入程式已解鎖,您也會看到這則錯誤訊息,因為這個 API 不支援裝置的系統啟動載入程式已解鎖。
AICore 失敗,錯誤類型為 1-DOWNLOAD_ERROR,錯誤代碼為 0-UNKNOWN:功能 ... 失敗,失敗狀態為 0,錯誤 esz:UNAVAILABLE:無法解析主機 ... 保持網路連線,稍待幾分鐘後再重試。