firebase-ai-logic-basics

作者: firebase

用于将Firebase AI Logic(Gemini API)集成到Web应用程序中的官方技能。涵盖设置、多模态推理、结构化输出和安全性。

npx skills add https://github.com/firebase/agent-skills --skill firebase-ai-logic-basics

Firebase AI Logic Basics

Overview

Firebase AI Logic is a product of Firebase that allows developers to add gen AI to their mobile and web apps using client-side SDKs. The app can directly call Gemini models via Firebase AI Logic without the developer needing to manage a dedicated backend. Firebase AI Logic was previously known as "Vertex AI for Firebase".

It supports the two Gemini API providers:

  • Gemini Developer API: It has a free tier ideal for prototyping, and pay-as-you-go for production
  • Agent Platform Gemini API (formerly branded Vertex AI): Ideal for scale with enterprise-grade production readiness, requires Blaze pricing plan

Use the Gemini Developer API as a default, and only Agent Platform Gemini API (formerly branded Vertex AI) if the application requires it.


Setup & initialization

Prerequisites

  • Identify the platform the user is interested in building on prior to starting: Android, iOS, Web, or Flutter.
  • If their platform is unsupported, Direct the user to Firebase Docs to learn how to set up AI Logic for their application (share this link with the user https://firebase.google.com/docs/ai-logic/get-started)
  • The Firebase CLI commands below run through npx on every platform, so they need Node.js 20+ and npm. Use the firebase-basics skill to check for them and to log in to the Firebase CLI. If Node.js is missing or older than version 20, ask the user to install it as that skill describes. Don't install system packages yourself, for example with sudo apt-get, because that changes the user's machine without their consent.

1. Provision Firebase AI Logic (ALL platforms)

Use the Firebase CLI to provision Firebase AI Logic for the Firebase Project:

  1. Make sure that you're in a firebase directory (with a firebase.json).

  2. Verify that you're running Firebase CLI commands against the intended Firebase Project. When you run this command, the active project is marked with "current":

    npx -y firebase-tools@latest projects:list
    
  3. Make sure there's at least one Firebase App for the target platform registered with the current Firebase Project:

    npx -y firebase-tools@latest apps:list
    
  4. Provision Firebase AI Logic for the Firebase Project:

    npx -y firebase-tools@latest init ailogic
    

    This command will enable the Gemini Developer API in the Firebase project.

[!WARNING] CRITICAL: Provisioning Firebase AI Logic is Required For all platforms (Android, iOS, Web, or Flutter), even if the app already uses Firebase, you MUST run npx -y firebase-tools@latest init ailogic to provision the service. The configuration files of GoogleService-Info.plist, google-services.json, and firebase_options.dart ONLY handle client configuration and do NOT enable the Firebase AI Logic service, leading to PERMISSION_DENIED errors.

If you can't run init ailogic yourself (for example because Node.js is missing or the Firebase CLI isn't logged in) do NOT skip it. The app's requests to Gemini models will fail until the Firebase AI Logic service is provisioned. Tell the user to run this command in their project directory, and include it in your final summary:

npx -y firebase-tools@latest init ailogic

2. Add the SDK and initialize the service in the app

Adding the SDK dependency and initializing the service are platform-specific. Before writing code, read the reference for the target platform listed under Initialization Code References.

More info in Firebase AI Logic Getting Started


Core Capabilities

[!WARNING] CRITICAL: Use current model names: Always check the Firebase AI Logic Models documentation for the currently supported model names. Do NOT use any Gemini 1.x or Gemini 2.x models (such as gemini-1.5-flash, gemini-1.5-pro, gemini-2.0-flash, gemini-2.0-pro, gemini-2.5-flash, gemini-2.5-flash-lite, or gemini-2.5-pro), as older models are deprecated or shut down. Always use a currently supported Gemini 3+ model; if URL access is blocked in your environment, proceed directly without searching local files.

Text-Only Generation

Multimodal (Text + Images/Audio/Video/PDF input)

Firebase AI Logic allows Gemini models to analyze image files directly from your app. This enables features like creating captions, answering questions about images, detecting objects, and categorizing images. Beyond images, Gemini can analyze other media types like audio, video, and PDFs by passing them as inline data with their MIME type. For files larger than 20 megabytes (which can cause HTTP 413 errors as inline data), store them in Cloud Storage for Firebase and pass their URLs to the Gemini Developer API.

Chat Session (Multi-turn)

Maintain history automatically using startChat.

Streaming Responses

To improve the user experience by showing partial results as they arrive (like a typing effect), use generateContentStream instead of generateContent for faster display of results.

Text-to-Speech (TTS) Generation

Generate spoken audio directly on client devices without a custom speech backend. Firebase AI Logic supports speech synthesis using dedicated Gemini TTS models:

  • Supported Models: gemini-3.1-flash-tts-preview
  • Capabilities:
    • Single-speaker voice persona selection (voiceName) and multi-speaker dialogues (up to 2 distinct speakers) via SpeechConfig / MultiSpeakerVoiceConfig
    • Direct audio responses by setting responseModalities to audio
    • Streaming speech responses with generateContentStream for low-latency playback
    • Audio directives ([Audio Profile: ...], [Scene: ...], [Director's Note: ...]) and emotional tags ([whispers], [laughs], [slowly])
    • Client-side decoding and playback of 24 kHz 16-bit linear PCM (audio/l16) or WAV container format (audio/x-wav)

See the Text-to-Speech (TTS) Generation Guide for full implementation details, streaming patterns, and copy-paste code snippets for iOS (Swift), Android (Kotlin), and Web.

Generate Images with Nano Banana

[!WARNING] Use current Image model names: Always check the Firebase AI Logic Models documentation for the currently supported image generation (Nano Banana) model names.

  • Requires an upgraded Blaze pay-as-you-go billing plan.

Search Grounding with the built in googleSearch tool


Supported Platforms and Frameworks

Supported Platforms and Frameworks include Kotlin and Java for Android, Swift for iOS, JavaScript for web apps, Dart for Flutter, and C Sharp for Unity.

Advanced Features

Structured Output (JSON)

Enforce a specific JSON schema for the response.

On-Device AI (Hybrid)

Hybrid inference runs prompts with an on-device model when one is available and falls back to a cloud-hosted model otherwise (or vice versa). Availability and setup steps differ by platform, more info in the hybrid and on-device documentation, which links to each platform's guide.


Security & Production

Firebase App Check

[!WARNING] Critical Safety Requirement: In order to use AI Logic safely, you MUST set up App Check on your app. This prevents unauthorized clients from using your API quota and accessing your backend resources.

See App Check for Firebase AI Logic for setup instructions. Each platform uses its own attestation provider, so follow the instructions for the target platform.

App Check Debug Tokens for Local Development & CI/CD

Because App Check attestation providers (like Play Integrity or DeviceCheck) reject emulators, simulators, or CI environments, you must use App Check Debug Tokens during development and testing to bypass standard attestation.

[!WARNING] CRITICAL: Never Hardcode or Commit Debug Tokens App Check debug tokens allow clients to bypass attestation and access backend resources without a genuine device. Treat them as private secrets. Never commit debug tokens to version control or hardcode raw token strings in client code (Web, Android, iOS, or Flutter). Always inject them through local environment variables, gitignored local configurations, or CI secrets. If a token is compromised, revoke it immediately in the Firebase Console.

Local Development (Auto-Generated)
  1. Configure your code's App Check provider to use the debug factory. The API is platform-specific; see the App Check section of the platform reference or the App Check documentation linked above.
  2. Run your app in the emulator/localhost.
  3. Look at your runtime debugger console / Logcat logs for the generated UUID:
    • Example: AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678"
  4. Register this token in the Firebase Console under Security > App Check > Apps > Manage debug tokens.

💡 Tip (Prevent Debug Token Churn): Simulator or emulator resets, fresh installs, and clearing browser data can make the SDK generate a new debug token that you must register again. To keep a stable debug token without hardcoding it, see the App Check section of the platform reference.

CI/CD Pipelines (Pre-Provisioned)
  1. Generate and register a new debug token in the Firebase Console under Security > App Check > Apps > Manage debug tokens.
  2. Add this token string as an encrypted secret in your CI system (e.g. APP_CHECK_DEBUG_TOKEN).
  3. Configure your build to pass this secret as an environment variable to the SDK during test execution.

Firebase Remote Config

Consider that you do not need to hardcode model names (e.g., a specific model version string). Use Firebase Remote Config to update model versions dynamically without deploying new client code. See Changing model names remotely


Initialization Code References

[!WARNING] CRITICAL: Use current model names: Always check the Firebase AI Logic Models documentation for the currently supported model names. Do NOT use any Gemini 1.x or Gemini 2.x models (such as gemini-1.5-flash, gemini-2.0-flash, gemini-2.5-flash, or gemini-2.5-flash-lite), as older models are deprecated or shut down.

References

Android (Kotlin) SDK usage patterns iOS SDK code examples and usage patterns Web SDK setup, code examples, and usage patterns

Flutter SDK code examples and usage patterns Client-side Text-to-Speech (TTS) generation

来自 firebase 的更多技能

developing-genkit-dart
firebase
面向 Dart 的统一 AI SDK,支持代码生成、结构化输出、工具、流程和智能体。提供核心 API,涵盖生成、工具定义、流程编排、嵌入和流式处理,采用统一接口。包含 8 个以上插件,支持 LLM 提供商(Google Gemini、Anthropic Claude、OpenAI GPT)、Firebase AI、模型上下文协议、Chrome 浏览器集成,以及通过 Shelf 托管 HTTP 服务器。内置 CLI 和本地开发 UI,用于流程执行、追踪、模型实验等。
developing-genkit-js
firebase
使用Genkit流程、工具和多模型支持,构建AI驱动的Node.js/TypeScript应用程序。Genkit与提供商无关;通过插件支持Google AI、OpenAI、Anthropic、Ollama及其他LLM提供商。使用Zod定义类型安全的模式流程,执行生成请求,并在TypeScript中组合多步骤AI工作流。需要Genkit CLI v1.29.0及以上版本;近期主要API变更意味着您必须查阅genkit文档:read和common-errors.md以获取当前模式,而非依赖先前知识...
extension-to-functions-codebase
firebase
用于将已安装的Firebase Extension(或扩展源代码)转换为独立的Cloud Functions for Firebase代码库或可发布的npm包技能,…
firebase-ai-logic
firebase
客户端Gemini集成,适用于网页应用,支持多模态推理、流式传输及设备端混合执行。支持纯文本和多模态输入(图像、音频、视频、PDF);超过20MB的文件通过Cloud Storage路由。包含自动历史记录的聊天会话、用于实时显示的流式响应,以及结构化JSON输出强制。通过Chrome中的Gemini Nano提供混合设备端推理,并自动回退到云端执行。生产环境需启用App Check...
firebase-app-hosting-basics
firebase
使用Firebase App Hosting部署和管理基于Next.js、Angular及其他支持框架的全栈Web应用。需使用Blaze定价计划的Firebase项目;支持服务端渲染(SSR)和增量静态再生(ISR)工作流。通过firebase.json配置部署,可选apphosting.yaml进行后端设置,或通过GitHub集成启用自动化"git push部署"。包含通过CLI命令进行密钥管理,以安全访问敏感密钥...
firebase-auth-basics
firebase
配置 Firebase Authentication,集成多种身份提供商并设置安全的数据访问规则。支持邮箱/密码、手机号、匿名登录、联合身份提供商(Google、Facebook、Twitter、GitHub、Microsoft、Apple)以及自定义身份认证集成。每个经过身份验证的用户会获得唯一 ID 和基于 JWT 的令牌(短期 ID 令牌和长期刷新令牌),用于访问 Firebase 服务。通过 CLI 启用 Google 登录、匿名登录和邮箱/密码提供商;使用 Firebase 控制台...
firebase-basics
firebase
Firebase项目设置及AI代理集成的CLI工作流程。需先完成firebase-local-env-setup技能及Firebase CLI安装。核心流程涵盖通过firebase login进行身份验证、使用唯一ID创建项目、以及通过交互式firebase init命令初始化服务。设置过程中支持功能选择,包括Firestore、Functions和Hosting,并自动生成配置文件。CLI自带文档功能,可通过--help标志查看...
firebase-crashlytics
firebase
Firebase Crashlytics 的全面指南,包括配置和 SDK 使用。当用户需要帮助设置 Crashlytics、添加……时,使用此技能。