本页面介绍了如何执行以下操作:
- 将项目配置为使用 Prompt API
- 提供纯文本输入并接收回答
- 提供图片输入和相关文本输入,并接收回答
如需详细了解 Prompt API,请参阅 Kotlin (com.google.mlkit.genai.prompt) 和 Java (com.google.mlkit.genai.prompt.java、com.google.mlkit.genai.prompt) 的参考文档。
配置项目
在 build.gradle 配置中将机器学习套件 Prompt API 添加为依赖项:
implementation("com.google.mlkit:genai-prompt:1.0.0-beta4")
如果您需要使用 Structured Output API 以特定格式获取响应,则需要配置 KSP 并添加其他依赖项。如需了解详情,请参阅生成结构化输出。
实现生成模型
如需在项目中实现代码,请按以下步骤操作:
创建
generativeModel对象:Kotlin
// Get a GenerativeModel instance val generativeModel = Generation.getClient()Java
// Get a GenerativeModel instance GenerativeModelFutures generativeModelFutures = GenerativeModelFutures .from(Generation.INSTANCE.getClient());检查 Gemini Nano 是否为
AVAILABLE,、DOWNLOADABLE或UNAVAILABLE。然后,下载该功能(如果可下载):Kotlin
val status = generativeModel.checkStatus() when (status) { FeatureStatus.UNAVAILABLE -> { // Gemini Nano not supported on this device or device hasn't fetched the latest configuration to support it } FeatureStatus.DOWNLOADABLE -> { // Gemini Nano can be downloaded on this device, but is not currently downloaded generativeModel.download().collect { status -> when (status) { is DownloadStatus.DownloadStarted -> Log.d(TAG, "starting download for Gemini Nano") is DownloadStatus.DownloadProgress -> Log.d(TAG, "Nano ${status.totalBytesDownloaded} bytes downloaded") DownloadStatus.DownloadCompleted -> { Log.d(TAG, "Gemini Nano download complete") modelDownloaded = true } is DownloadStatus.DownloadFailed -> { Log.e(TAG, "Nano download failed ${status.e.message}") } } } } FeatureStatus.DOWNLOADING -> { // Gemini Nano currently being downloaded } FeatureStatus.AVAILABLE -> { // Gemini Nano currently downloaded and available to use on this device } }Java
ListenableFuture<Integer> status = generativeModelFutures.checkStatus(); Futures.addCallback(generativeModelFutures.checkStatus(), new FutureCallback<>() { @Override public void onSuccess(Integer featureStatus) { switch (featureStatus) { case FeatureStatus.AVAILABLE - > { // Gemini Nano currently downloaded and available to use on this device } case FeatureStatus.UNAVAILABLE - > { // Gemini Nano not supported on this device or device hasn't fetched the latest configuration to support it } case FeatureStatus.DOWNLOADING - > { // Gemini Nano currently being downloaded } case FeatureStatus.DOWNLOADABLE - > { generativeModelFutures.download(new DownloadCallback() { @Override public void onDownloadStarted(long l) { Log.d(TAG, "starting download for Gemini Nano"); } @Override public void onDownloadProgress(long l) { Log.d(TAG, "Nano " + l + " bytes downloaded"); } @Override public void onDownloadCompleted() { Log.d(TAG, "Gemini Nano download complete"); } @Override public void onDownloadFailed(@NonNull GenAiException e) { Log.e(TAG, "Nano download failed: " + e.getMessage()); } }); } } } @Override public void onFailure(@NonNull Throwable t) { // Failed to check status } }, ContextCompat.getMainExecutor(context));
提供纯文本输入
Kotlin
val response = generativeModel.generateContent("Write a 3 sentence story about a magical dog.")
Java
GenerateContentResponse response = generativeModelFutures.generateContent(
new GenerateContentRequest.Builder(
new TextPart("Write a 3 sentence story about a magical dog."))
.build())
.get();
或者,添加可选参数:
Kotlin
val response = generativeModel.generateContent(
generateContentRequest(
TextPart("Write a 3 sentence story about a magical dog."),
) {
// Optional parameters
temperature = 0.2f
topK = 10
candidateCount = 3
},
)
Java
GenerateContentRequest.Builder requestBuilder =
new GenerateContentRequest.Builder(
new TextPart("Write a 3 sentence story about a magical dog."));
requestBuilder.setTemperature(.2f);
requestBuilder.setTopK(10);
requestBuilder.setCandidateCount(3);
GenerateContentResponse response =
generativeModelFutures.generateContent(requestBuilder.build()).get();
如需详细了解可选参数,请参阅可选配置。
提供多模态(图片和文本)输入
在 generateContentRequest() 函数中将多张图片和文本输入捆绑在一起,其中文本提示词是与图片相关的问题或命令。您可以在同一请求中捆绑最多 10 张图片。
Kotlin
val response = generativeModel.generateContent(
generateContentRequest(ImagePart(bitmap1), ImagePart(bitmap2), TextPart(textPrompt)) {
// optional parameters
...
},
)
Java
GenerateContentResponse response = generativeModelFutures.generateContent(
new GenerateContentRequest.Builder(
new Content.Builder()
.addPart(new ImagePart(bitmap1))
.addPart(new ImagePart(bitmap2))
.addPart(new TextPart("textPrompt"))
.build())
// optional parameters
.build())
.get();
处理推理结果
运行推理并检索结果。对于纯文本提示和多模态提示,您可以选择等待完整结果,也可以选择在生成回答时流式传输回答。
这会使用非流式推理,该推理会先从 AI 模型中检索整个结果,然后再返回结果:
Kotlin
// Call the AI model to generate content and store the complete // in a new variable named 'response' once it's finished val response = generativeModel.generateContent("Write a 3 sentence story about a magical dog")Java
GenerateContentResponse response = generativeModelFutures.generateContent( new GenerateContentRequest.Builder( new TextPart("Write a 3 sentence story about a magical dog.")) .build()) .get();以下代码段是使用流式推理的示例,该推理会在生成结果时分块检索结果:
Kotlin
// Streaming inference var fullResponse = "" generativeModel.generateContentStream("Write a 3 sentence story about a magical dog").collect { chunk -> val newChunkReceived = chunk.candidates[0].text print(newChunkReceived) fullResponse += newChunkReceived }Java
// Streaming inference StringBuilder fullResponse = new StringBuilder(); generativeModelFutures.generateContent(new GenerateContentRequest.Builder( (new TextPart("Write a 3 sentence story about a magical dog"))).build(), chunk -> { Log.d(TAG, chunk); fullResponse.append(chunk); });
如需详细了解流式推理和非流式推理,请参阅流式推理与非流式推理。
延迟时间优化
为了针对首次推理调用进行优化,您的应用可以选择调用 warmup()。这会将 Gemini Nano 加载到内存中并初始化运行时组件。
可选配置
作为每个 GenerateContentRequest 的一部分,您可以设置以下可选参数:
temperature:控制 token 选择的随机程度。seed:可生成稳定且确定的结果。topK:控制结果的随机性和多样性。candidateCount:请求返回的唯一回答的数量。请注意,确切的回答数量可能与candidateCount不同,因为系统会自动移除重复的回答。maxOutputTokens:定义回答中可生成的词元数上限。
如需关于设置可选配置的更多指导,请参阅 GenerateContentRequest。
支持的功能和限制
- 输入内容不得超过 4,000 个 token(或大约 3,000 个英文单词)。如需了解详情,请参阅
countTokens参考文档。 - 应避免需要长输出(超过 4K 个 token)的使用场景。
- AICore 会对每个应用强制执行推理配额。如需了解详情,请参阅每个应用的配额。
常见设置问题
机器学习套件生成式 AI API 依赖于 Android AICore 应用来访问 Gemini Nano。当设备刚设置完毕(包括重置)或 AICore 应用刚重置(例如清除数据、卸载后重新安装)时,AICore 应用可能没有足够的时间完成初始化(包括从服务器下载最新配置)。因此,ML Kit GenAI API 可能无法按预期运行。以下是您可能会看到的常见设置错误消息以及处理方法:
| 错误消息示例 | 如何处理 |
| AICore 失败,错误类型为 4-CONNECTION_ERROR,错误代码为 601-BINDING_FAILURE:AICore 服务未能绑定。 | 如果您在设备设置完成后立即安装使用机器学习套件生成式 AI API 的应用,或者在应用安装后卸载 AICore,就可能会发生这种情况。更新 AICore 应用,然后重新安装您的应用,应该可以解决此问题。 |
| AICore 失败,错误类型为 3-PREPARATION_ERROR,错误代码为 606-FEATURE_NOT_FOUND:功能…不可用。 |
如果 AICore 尚未完成最新配置的下载,就可能会发生这种情况。设备连接到网络后,通常需要几分钟到几小时才能完成更新。重启设备可以加快更新速度。
请注意,如果设备的引导加载程序已解锁,您也会看到此错误,因为此 API 不支持引导加载程序已解锁的设备。 |
| AICore 失败,错误类型为 1-DOWNLOAD_ERROR,错误代码为 0-UNKNOWN:功能…失败,失败状态为 0,错误为 esz: UNAVAILABLE: Unable to resolve host… | 请保持网络连接,等待几分钟,然后重试。 |