GenAI Rewriting API

ML Kit の GenAI Rewriting API を使用すると、チャット メッセージや短いコンテンツのスタイルやトーンを自動的に変更できます。

次のような場合、コンテンツの書き換えに関する提案が役立つことがあります。

  • ステークホルダーとのコミュニケーションで、メッセージをよりプロフェッショナルなものにする
  • ソーシャル メディア プラットフォームへの投稿に適したメッセージにする
  • メッセージを伝える別の方法を探しているネイティブ スピーカー以外の人向けにメッセージを言い換える

主な機能

ML Kit の GenAI Rewriting API は、短いコンテンツを次のいずれかのスタイルで書き換えることができます。

  • より詳しく: 入力テキストを詳細な説明的な 言葉で展開します。
  • Emojify: 入力テキストに関連する絵文字を追加して、表現力と楽しさを高めます。
  • より短く: 入力テキストを短くまとめ、 コア メッセージはそのままにします。
  • フレンドリー: 入力テキストを会話調で、よりカジュアルで親しみやすいものに書き換えます。
  • プロフェッショナル: 入力テキストを敬語で、よりフォーマルで ビジネスライクなものに書き換えます。
  • 言い換える: 元の意味を維持しながら、異なる単語や文 構造を使用して入力テキストを書き換えます。

リクエストは少なくとも 1 つの提案を返します。複数の提案が返された場合、結果は信頼度の降順で並べ替えられます。

検索結果の例

入力 書き換えスタイル 出力
Do you want to meet to talk more? プロフェッショナル Would you be interested in meeting again to discuss this further?
I would like to request the pleasure of your company at a casual get-together at my residence this coming Saturday evening より短く Would you like to join me for a casual get-together at my place this Saturday evening?
The event was successful より詳しく The event was a resounding success, exceeding all of our expectations and proving to be a resounding triumph.
Let's grab coffee sometime soon Emojify Let's grab coffee ☕ sometime soon 👋.
Provide the report by end of day フレンドリー Could you please share the report by the end of the day?
Hey, need that thing ASAP プロフェッショナル Could you please provide the requested document at your earliest convenience?
The project is behind schedule 言い換える The project timeline requires adjustment to meet the original deadline

スタートガイド

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 で指定)の可用性は、特定のデバイスの構成と、デバイスにダウンロードされているモデルによって異なる場合があります。

デベロッパーが、リクエストされた RewriterOptions を使用して、目的の API 機能がデバイスで サポートされていることを確認する最も確実な方法は、 checkFeatureStatus() メソッドを呼び出すことです。このメソッドは、実行時にデバイスで機能が利用可能かどうかを明確に示します。

セットアップに関する一般的な問題

ML Kit GenAI API は、Android AICore アプリを使用して Gemini Nano にアクセスします。デバイスをセットアップしたばかりの場合(リセットを含む)、または AICore アプリをリセットしたばかりの場合(データの消去、アンインストールして再インストールなど)、AICore アプリが初期化を完了する(サーバーから最新の構成をダウンロードするなど)までに十分な時間がかからないことがあります。その結果、ML Kit GenAI API が期待どおりに機能しない可能性があります。表示される可能性のある一般的なセットアップ エラー メッセージとその対処方法を以下に示します。

エラー メッセージの例 対応方法
AICore failed with error type 4-CONNECTION_ERROR and error code 601-BINDING_FAILURE: AICore service failed to bind. デバイスのセットアップ直後に ML Kit GenAI API を使用してアプリをインストールした場合や、アプリのインストール後に AICore がアンインストールされた場合に、この問題が発生することがあります。AICore アプリを更新してからアプリを再インストールすると、この問題が解決します。
AICore failed with error type 3-PREPARATION_ERROR and error code 606-FEATURE_NOT_FOUND: Feature ... is not available. 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 ... ネットワーク接続を維持し、数分待ってから再試行してください。

サンプルコード