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][1] 用戶端,檢查必要的裝置端模型功能是否可用 (並視需要下載),將輸入文字準備為要求,執行重寫程序以取得建議,然後釋出資源。

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][2]。輸入內容不得超過 256 個權杖。

特定功能設定 (由 RewriterOptions 指定) 的可用性可能因特定裝置的設定,以及已下載至裝置的型號而異。

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

常見設定問題

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 failed with error type 1-DOWNLOAD_ERROR and error code 0-UNKNOWN: Feature ... failed with failure status 0 and error esz: UNAVAILABLE: Unable to resolve host ... 保持網路連線,稍待幾分鐘後再試一次。

程式碼範例