您可以使用混合推理构建 AI 赋能的 Android 应用和功能,使用 Firebase AI Logic。混合推理支持在设备端模型可用时使用该模型运行推理,否则无缝回退到云端托管模型(反之亦然)。
本页面介绍了如何 开始使用客户端 SDK, 并展示了 其他配置选项和功能, 例如温度。
请注意,Firebase AI Logic 支持通过 Firebase AI Logic SDK v17.10.0+ (BoM v34.10.0+) 在特定设备上运行的 Android 应用进行设备端推理。它受 机器学习套件条款以及 机器学习套件的生成式 AI 方面特定条款的约束。
推荐的用例和支持的功能
推荐的用例
使用设备端模型进行推理 可提供:
- 增强的隐私保护
- 本地环境
- 免费推理
- 离线功能
使用混合 功能可提供:
- 通过适应设备端模型的可用性和互联网连接来覆盖更多受众群体
设备端推理支持的功能
设备端推理仅支持单轮文本生成(而非聊天),并提供流式或非流式输出。它支持以下文本生成功能:
请务必查看本页底部 尚未提供设备端推理功能 的列表。
准备工作
请注意以下事项:
支持的 API:
云端推理使用您选择的 Gemini API 提供方( Gemini Developer API 或 Agent Platform Gemini API (formerly Vertex AI))。
设备端推理使用机器学习套件中的 Prompt API, 该 API 处于 Beta 版阶段,仅在 特定设备上提供。
本页面介绍了如何开始使用 。
完成此标准设置后,请查看 其他配置选项和功能 (例如设置温度)。
支持的 Android 设备及其设备端模型
对于设备端推理(使用机器学习套件中的 Prompt API),您 可以在 机器学习套件文档中找到支持的设备及其设备端模型的列表 。
开始使用
这些“开始使用”步骤介绍了您要发送的任何受支持的提示请求所需的一般设置。
第 1 步:设置 Firebase 项目并将应用连接到 Firebase
登录 Firebase 控制台, 然后选择您的 Firebase 项目。
在 Firebase 控制台中,依次前往 AI 服务 > AI Logic。
点击开始使用 ,启动引导式工作流,帮助您为项目设置 所需的 API 和资源。
如果系统提示您,请按照屏幕上的说明注册应用并将 Firebase 配置添加到应用。
当系统要求您选择“Gemini API 提供方”时,我们建议您选择 Gemini Developer API,这样您就可以快速免费开始使用。
您以后随时可以 设置 Agent Platform Gemini API (formerly Vertex AI) (及其结算要求)。
继续执行工作流,为所需的 API 和关联服务设置 Firebase AI Logic。
从 2026 年 7 月初开始,工作流的此阶段会自动 强制执行 Firebase App Check,以保护 AI Logic, 这是一项 至关重要 的服务,有助于在直接从应用访问 Gemini API 时保护该 API。在开始使用(请参阅本指南后面的步骤) 过程中,您需要在强制执行 App Check 时为本地开发配置 App Check 调试提供方 。
继续执行本指南中的下一步,将所需的 SDK 添加到应用。
第 2 步:添加所需的 SDK
The Firebase AI Logic SDK for Android
(firebase-aifirebase-ai-ondevice
在模块(应用级)Gradle 文件
(例如 <project>/<app-module>/build.gradle.kts)中,为 Android 添加
Firebase AI Logic和 App Check库的依赖项:
Kotlin
dependencies { // ... other androidx dependencies // Add the dependencies for the Firebase AI Logic and App Check libraries // Note that the on-device SDK is not yet included in the Firebase Android BoM implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta05") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Java
对于 Java,您需要添加两个额外的库。
dependencies { // ... other androidx dependencies // Add the dependencies for the Firebase AI Logic and App Check libraries // Note that the on-device SDK is not yet included in the Firebase Android BoM implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta05") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
第 3 步:为本地开发配置 App Check 调试提供程序
从 2026 年 7 月初开始,在控制台中为 AI Logic 提供的引导式设置工作流中,系统会自动强制执行 Firebase App Check 以保护 Gemini API。对于本地开发,您需要配置 App Check 调试提供程序 以绕过证明,同时仍保持 的强制执行App Check。
在调试 build 中,将 App Check 配置为使用调试提供方 工厂:
Kotlin
Firebase.initialize(context = this) Firebase.appCheck.installAppCheckProviderFactory( DebugAppCheckProviderFactory.getInstance(), )Java
FirebaseApp.initializeApp(/*context=*/ this); FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance(); firebaseAppCheck.installAppCheckProviderFactory( DebugAppCheckProviderFactory.getInstance());获取调试令牌:
在模拟器中或在测试设备上运行应用。
在日志中查找 App Check 调试令牌。例如:
D DebugAppCheckProvider: Enter this debug secret into the allow list in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678复制令牌(例如
123a4567-b89c-12d3-e456-789012345678)。
向 App Check 注册调试令牌:
在 Firebase 控制台中,依次前往 安全性 > App Check > 应用 标签页。
找到您的应用,点击溢出菜单 (),然后选择 管理调试令牌。
按照屏幕上的说明注册调试令牌。
如需详细了解调试提供方(包括如何获取新的调试令牌), 请查看 官方 App Check 文档。
第 4 步:检查设备端模型是否可用
使用
FirebaseAIOnDevice,
检查设备端模型是否可用,如果不可用,则下载该
模型。
下载后,AICore 会自动使模型保持最新状态。如需详细了解 AICore 和管理设备端模型下载,请查看代码段后面的备注。
Kotlin
val status = FirebaseAIOnDevice.checkStatus()
when (status) {
OnDeviceModelStatus.UNAVAILABLE -> {
Log.w(TAG, "On-device model is unavailable")
}
OnDeviceModelStatus.DOWNLOADABLE -> {
FirebaseAIOnDevice.download().collect { status ->
when (status) {
is DownloadStatus.DownloadStarted ->
Log.w(TAG, "Starting download - ${status.bytesToDownload}")
is DownloadStatus.DownloadInProgress ->
Log.w(TAG, "Download in progress ${status.totalBytesDownloaded} bytes downloaded")
is DownloadStatus.DownloadCompleted ->
Log.w(TAG, "On-device model download complete")
is DownloadStatus.DownloadFailed ->
Log.e(TAG, "Download failed ${status}")
}
}
}
OnDeviceModelStatus.DOWNLOADING -> {
Log.w(TAG, "On-device model is being downloaded")
}
OnDeviceModelStatus.AVAILABLE -> {
Log.w(TAG, "On-device model is available")
}
}
Java
Checking for and downloading the model is not yet available for Java.
However, all other APIs and interactions in this guide are available for Java.
请注意以下有关下载设备端模型的事项:
下载设备端模型所需的时间取决于许多因素,包括您的网络。
如果您的代码使用设备端模型进行主要或回退推理,请确保在应用生命周期的早期下载该模型,以便在最终用户在应用中遇到该代码之前,设备端模型可用。
如果在发出设备端推理请求时设备端模型 不可用 ,SDK 将 不会自动 触发设备端模型的下载。SDK 将回退到云端托管模型或 抛出异常(如需详细了解 推理模式的行为,请参阅相关内容)。
AICore (一项 Android 系统服务)会为您管理下载的模型和版本、使模型保持最新状态等。请注意,设备只会下载一个模型,因此,如果设备上的另一个应用之前已成功下载设备端模型,则此检查将返回该模型可用。
延迟时间优化
如需针对首次推理调用进行优化,您可以让应用调用
warmup()。
这会将设备端模型加载到内存中并初始化运行时组件。
第 5 步:初始化服务并创建模型实例
|
点击您的 Gemini API 提供方,以查看此页面上特定于提供方的内容 和代码。 |
在向模型发送提示请求之前,请进行以下设置。
为您选择的 API 提供方初始化服务。
创建
GenerativeModel实例,并将mode设置为以下值之一。此处的说明非常概括,但您可以在 设置推理模式中详细了解这些模式的行为。PREFER_ON_DEVICE:尝试使用设备端模型;否则, 回退到云端托管模型 。ONLY_ON_DEVICE:尝试使用设备端模型;否则, 抛出异常 。PREFER_IN_CLOUD:尝试使用云端托管模型;否则, 回退到设备端模型 。ONLY_IN_CLOUD:尝试使用云端托管模型;否则, 抛出异常 。
Kotlin
// Using this SDK to access on-device inference is an Experimental release and requires opt-in
@OptIn(PublicPreviewAPI::class)
// ...
// Initialize the Gemini Developer API backend service
// Create a GenerativeModel instance with a model that supports your use case
// Set the inference mode (like PREFER_ON_DEVICE to use the on-device model if available)
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "MODEL_NAME",
onDeviceConfig = OnDeviceConfig(mode = InferenceMode.PREFER_ON_DEVICE)
)
Java
// Initialize the Gemini Developer API backend service
// Create a GenerativeModel instance with a model that supports your use case
// Set the inference mode (like PREFER_ON_DEVICE to use the on-device model if available)
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
"MODEL_NAME",
new OnDeviceConfig(InferenceMode.PREFER_ON_DEVICE)
);
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
第 6 步:向模型发送提示请求
本部分介绍了如何发送各种类型的输入以生成不同类型的输出,包括:
根据纯文本输入生成文本
| 在试用此示例之前,请确保您已完成本指南的 “开始使用”部分。 |
您可以使用
generateContent()
根据包含文本的提示生成文本:
Kotlin
// Imports + initialization of Gemini API backend service + creation of model instance
// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
val response = model.generateContent(prompt)
print(response.text)
Java
// Imports + initialization of Gemini API backend service + creation of model instance
// Provide a prompt that contains text
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
// To generate text output, call generateContent with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
请注意,Firebase AI Logic 还支持使用
generateContentStream
(而不是 generateContent)流式传输文本响应。
根据文本和图片(多模态)输入生成文本
| 在试用此示例之前,请确保您已完成本指南的 “开始使用”部分。 |
您可以使用
generateContent()
根据包含文本和 最多 一个 图片文件
(仅限位图) 的提示生成文本,并提供每个输入文件的 mimeType 和文件本身。
Kotlin
// Imports + initialization of Gemini API backend service + creation of model instance
// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
// Provide a prompt that includes the image specified above and text
val prompt = content {
image(bitmap)
text("What developer tool is this mascot from?")
}
// To generate text output, call generateContent with the prompt
val response = model.generateContent(prompt)
print(response.text)
Java
// Imports + initialization of Gemini API backend service + creation of model instance
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
// Provide a prompt that includes the image specified above and text
Content content = new Content.Builder()
.addImage(bitmap)
.addText("What developer tool is this mascot from?")
.build();
// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
请注意,Firebase AI Logic 还支持使用
generateContentStream
(而不是 generateContent)流式传输文本响应。
你还可以做些什么?
您可以为混合体验使用各种其他配置选项和功能:
尚未提供设备端推理功能
作为实验性版本,并非所有云端模型的功能都可用于 设备端 推理。
本部分列出的功能 尚未提供设备端推理功能 。如果您想使用其中任何功能,建议您使用 ONLY_IN_CLOUD 推理模式,以获得更一致的体验。
生成结构化输出(例如 JSON 或枚举)
根据位图(加载到内存中的图片)以外的图片文件输入类型生成文本
根据多个图片文件生成文本
根据音频、视频和文档(例如 PDF)输入生成文本
使用 Gemini 或 Imagen 模型生成图片
在多模态请求中使用网址提供文件。您必须以内嵌数据的形式向设备端模型提供文件
发送超过 4,000 个令牌(或大约 3,000 个英语单词)的请求。
多轮对话
向模型提供 工具 以帮助其生成响应 (例如函数调用、代码执行、网址上下文、 使用
Google Search 进行 Grounding 和使用Google Maps 进行 Grounding)
Firebase 控制台中的 AI 监控 不 会显示任何 设备端推理数据(包括设备端日志)。不过,任何使用 云端托管模型的推理都可以像其他通过 Firebase AI Logic进行的推理一样受到监控。
其他限制
除了上述限制之外,设备端 推理还有以下 限制 (如需了解详情,请参阅 机器学习套件文档):
您的应用的最终用户必须使用 支持设备 端推理的设备。
您的应用只能在前台运行时运行设备端推理。
设备端推理仅验证了英语和韩语。
整个设备端推理请求的令牌上限为 4,000 个令牌。如果您的请求可能会超出此限制,请务必配置可以使用云端托管模型的推理模式。
我们建议避免使用需要长输出(超过 256 个令牌)的设备端推理用例。
AICore (一项用于管理设备端模型的 Android 系统服务)会针对 每个应用强制执行推理配额。如果在短时间内发出过多 API 请求, 将导致
ErrorCode.BUSY响应。如果您收到此错误,请考虑使用指数退避算法重试请求。此外,如果应用超出长时间配额(例如每日配额),则可能会返回ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED。
提供反馈 有关您的使用体验Firebase AI Logic