GenAI 校对 API

借助 ML Kit 的 GenAI 校对 API,您可以帮助用户检查短文本中的语法和拼写。

主要功能

  • 校对通过键盘或语音输入的文字
  • 请求将返回至少一个建议。如果返回多个建议,结果将按置信度降序排序。

示例结果

输入

输入类型

输出

这是一条简短的消息

键盘

这是一条简短消息

项目已接近完成,但需要审核

键盘

项目即将完成,但需要审核

Please meat me at the bear,

语音

请在酒吧与我碰面。

使用入门

如需开始使用 GenAI 校对 API,请将此依赖项添加到项目的 build 文件中。

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

然后,配置并获取具有特定语言和输入类型设置的 Proofreader 客户端。检查并确保必要的设备端模型功能可用(如果需要,则触发下载)。以 ProofreadingRequest 格式提交要分析的文本,执行校对推理,最后处理返回的建议以更正文本。

Kotlin

val textToProofread = "The praject is compleet but needs too be reviewd"

// Define task with required input and output format
val options = ProofreaderOptions.builder(context)
    // InputType can be KEYBOARD or VOICE. VOICE indicates that
    // the user generated text based on audio input.
    .setInputType(ProofreaderOptions.InputType.KEYBOARD)
    // Refer to ProofreaderOptions.Language for available
    // languages
    .setLanguage(ProofreaderOptions.Language.ENGLISH)
    .build()
val proofreader = Proofreading.getClient(options)

suspend fun prepareAndStartProofread() {
    // Check feature availability, status will be one of the
    // following: UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    val featureStatus = proofreader.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.
        proofreader.downloadFeature(object : DownloadCallback {
            override fun onDownloadStarted(bytesToDownload: Long) { }

            override fun onDownloadFailed(e: GenAiException) { }

            override fun onDownloadProgress(
                totalBytesDownloaded: Long
            ) {}

            override fun onDownloadCompleted() {
                startProofreadingRequest(textToProofread, proofreader)
            }
        })
    } 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
        // very quickly. However, if Gemini Nano is not already
        // downloaded, the download process may take longer.
        startProofreadingRequest(textToProofread, proofreader)
    } else if (featureStatus == FeatureStatus.AVAILABLE) {
        startProofreadingRequest(textToProofread, proofreader)
    }
}

suspend fun startProofreadingRequest(
    text: String, proofreader: Proofreader
) {
    // Create task request
    val proofreadingRequest =
        ProofreadingRequest.builder(text).build()

    // Start proofreading 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 proofreadingResults =
        proofreader.runInference(proofreadingRequest).await().results

    // You can also start a streaming request
    // proofreader.runInference(proofreadingRequest) { newText ->
    //     // show new text in UI
    // }
}

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

Java

String textToProofread = "The praject is compleet but needs too be reviewd";

// Define task with required input and output format
ProofreaderOptions proofreaderOptions = 
    ProofreaderOptions
        .builder(context)
        // InputType can be KEYBOARD or VOICE. VOICE indicates that the
        // user generated text based on audio input.
        .setInputType(ProofreaderOptions.InputType.KEYBOARD)
        // Refer to ProofreaderOptions.Language for available languages
        .setLanguage(ProofreaderOptions.Language.ENGLISH)
        .build();
Proofreader proofreader = Proofreading.getClient(proofreaderOptions);

void prepareAndStartProofread(Context context) throws ExecutionException,
        InterruptedException {
    // Check feature availability, status will be one of the following:
    // UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE
    try {
        int featureStatus = proofreader.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.
            proofreader.downloadFeature(new DownloadCallback() {
                @Override
                public void onDownloadCompleted() {
                    startProofreadingRequest(textToProofread, proofreader);
                }

                @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
            // very quickly. However, if Gemini Nano is not already
            // downloaded, the download process may take longer.
            startProofreadingRequest(textToProofread, proofreader);
        } else if (featureStatus == FeatureStatus.AVAILABLE) {
            startProofreadingRequest(textToProofread, proofreader);
        }
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
}

void startProofreadingRequest(String text, Proofreader proofreader) {
    // Create task request
    ProofreadingRequest proofreadingRequest = ProofreadingRequest
            .builder(text).build();

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

        // You can also start a streaming request
        // proofreader.runInference(proofreadingRequest, 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()
proofreader.close();

模型如何处理不同的输入类型

当模型更了解用户输入文本的方式(键盘或语音)时,就能更好地预测可能出现的错误类型。键盘输入的文字更容易因按错附近的键而拼写错误,而语音输入的文字更容易因发音相同而拼写错误。

支持的功能和限制

校对功能支持以下语言:英语、日语、法语、德语、意大利语、西班牙语和韩语,这些语言在 ProofreaderOptions.Language 中定义。输入应少于 256 个 token。

特定功能配置(由 ProofreaderOptions 指定)的可用性可能因特定设备的配置和已下载到设备的模型而异。

对于开发者而言,确保设备支持具有所请求 ProofreaderOptions 的预期 API 功能的最可靠方法是调用 checkFeatureStatus() 方法。此方法可在运行时提供设备上功能可用性的确定状态。

常见设置问题

机器学习套件生成式 AI 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:无法解析主机 ... 保持网络连接,等待几分钟,然后重试。