Community生产力与协作github.com

firebase/firebase-ai-logic

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

firebase-ai-logic 是什么?

该技能是 Firebase AI Logic(基于 Gemini API)的官方集成技能,专为 Web 应用开发者设计。它提供了一套完整的指南,帮助开发者快速上手,包括项目初始化、API 密钥配置、服务端 SDK 集成等步骤。技能详细说明了如何利用 Gemini 的多模态能力(如文本、图像、音频输入)进行推理,以及如何通过结构化输出(如 JSON Schema)将结果直接集成到业务逻辑中。此外,它还涵盖了安全最佳实践,如使用 Firebase App Check 和身份验证来保护 API 端点。此技能适用于 Firebase 生态系统的 Web 项目,支持在 Node.js 环境中运行,并能与 Cloud Functions、Firestore 等服务无缝协作。通过清晰的分步说明和代码示例,开发者可以快速实现智能对话、内容生成、数据提取等 AI 功能,同时确保安全性。

兼容平台~Claude Code~Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/firebase/agent-skills/tree/main/skills/firebase-ai-logic

Installed? Explore more 生产力与协作 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

firebase-ai-logic 是做什么的?

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

概述

该技能帮助开发者将 Firebase AI Logic(基于 Gemini API)集成到 Web 应用中。它提供了从项目初始化到生产部署的完整指南,包括 API 配置、多模态推理(文本、图像、音频)、结构化输出生成以及安全防护。

支持平台

  • Web 应用(JavaScript/TypeScript)
  • Node.js 运行时(包括 Cloud Functions)

前提条件

  • 一个 Firebase 项目(Firebase 控制台)
  • 启用了 Gemini API(通过 Google AI Studio 或 Vertex AI)
  • Node.js 18+ 和 npm

快速开始

1. 安装 Firebase SDK

npm install firebase

2. 初始化 Firebase

import { initializeApp } from 'firebase/app';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID"
};

const app = initializeApp(firebaseConfig);

3. 使用 Gemini API

import { GoogleGenerativeAI } from '@google/generative-ai';

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });

async function generateText(prompt) {
  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  return text;
}

多模态推理

支持文本、图像和音频输入:

import { GoogleGenerativeAI } from '@google/generative-ai';

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro-vision" });

async function analyzeImage(imageBase64, prompt) {
  const image = {
    inlineData: {
      data: imageBase64,
      mimeType: "image/png"
    }
  };

  const result = await model.generateContent([prompt, image]);
  return result.response.text();
}

结构化输出

使用 JSON Schema 定义输出格式:

const schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer" },
    interests: { type: "array", items: { type: "string" } }
  },
  required: ["name", "age"]
};

const result = await model.generateContent({
  contents: [{ role: "user", parts: [{ text: "从文本中提取用户信息" }] }],
  generationConfig: {
    responseMimeType: "application/json",
    responseSchema: schema
  }
});

const parsed = JSON.parse(result.response.text());

安全性

使用 Firebase App Check 保护 API

import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';

const appCheck = initializeAppCheck(app, {
  provider: new ReCaptchaV3Provider('YOUR_RECAPTCHA_SITE_KEY'),
  isTokenAutoRefreshEnabled: true
});

使用 Firebase Authentication 进行访问控制

import { getAuth, onAuthStateChanged } from 'firebase/auth';

const auth = getAuth(app);
onAuthStateChanged(auth, (user) => {
  if (user) {
    // 用户已登录,允许访问 AI 功能
  } else {
    // 用户未登录,限制访问
  }
});

在 Cloud Functions 中使用

import * as functions from 'firebase-functions';
import { GoogleGenerativeAI } from '@google/generative-ai';

export const generateAiResponse = functions.https.onCall(async (data, context) => {
  // 检查认证
  if (!context.auth) {
    throw new functions.https.HttpsError('unauthenticated', '用户未登录');
  }

  const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
  const model = genAI.getGenerativeModel({ model: "gemini-pro" });
  
  const result = await model.generateContent(data.prompt);
  return { response: result.response.text() };
});

最佳实践

  • API 密钥管理:不要在前端代码中硬编码 API 密钥,使用环境变量或 Cloud Functions 代理请求。
  • 错误处理:始终为 API 调用添加错误处理,包括重试逻辑。
  • 速率限制:注意 Gemini API 的配额限制,实现指数退避策略。
  • 数据隐私:避免将敏感数据发送到 Gemini API,或确保在安全环境中处理。
  • 缓存:对频繁的请求结果进行缓存以减少 API 调用次数。

故障排除

  • API 密钥无效:检查密钥是否正确,并确保在 Google Cloud 控制台中启用了 Gemini API。
  • CORS 错误:确保在 Firebase Hosting 或你的服务器上正确配置 CORS 头。
  • 请求超时:增加网络请求的超时时间,或检查网络连接。
  • 配额耗尽:检查 API 配额使用情况,必要时升级计划。

参考资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

firebase/developing-genkit-dart

Generates code and provides documentation for the Genkit Dart SDK. Use when the user asks to build AI agents in Dart, use Genkit flows, or integrate LLMs into Dart/Flutter applications.

firebase/developing-genkit-go

Develop AI-powered applications using Genkit in Go. Use when the user asks to build AI features, agents, flows, or tools in Go using Genkit, or when working with Genkit Go code involving generation, prompts, streaming, tool calling, or model providers.

firebase/developing-genkit-js

Develop AI-powered applications using Genkit in Node.js/TypeScript. Use when the user asks about Genkit, AI agents, flows, or tools in JavaScript/TypeScript, or when encountering Genkit errors, validation issues, type errors, or API problems.

firebase/developing-genkit-python

Develop AI-powered applications using Genkit in Python. Use when the user asks about Genkit, AI agents, flows, or tools in Python, or when encountering Genkit errors, import issues, or API problems.

firebase/firebase-ai-logic-basics

Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.

firebase/firebase-app-hosting-basics

Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends.

firebase/firebase-auth-basics

Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.

firebase/firebase-basics

Provides foundational setup, authentication, and project management workflows for Firebase using the Firebase CLI. Use when checking Firebase CLI version (must use 'npx -y firebase-tools@latest --version'), initializing a Firebase environment, authenticating, setting active projects, or setting up `google-services.json` or `GoogleService-Info.plist` files.

firebase/firebase-crashlytics

Comprehensive guide for Firebase Crashlytics, including provisioning and SDK usage. Use this skill when the user needs help setting up Crashlytics, adding crash reporting, or using the Crashlytics SDK in their application.

firebase/firebase-data-connect

Builds and deploys Firebase SQL Connect (aka Firebase Data Connect) backends with PostgreSQL securely. Use when designing schemas with tables and relations, writing authorized queries and mutations, configuring real-time data updates, or generating type-safe SDKs. Use when you need a relational database with Firebase, or when the user mentions SQL Connect or Data Connect.

firebase/firebase-firestore

Sets up, manages, and executes queries against Cloud Firestore database instances, including advanced native full-text search and relational joins using pipelines. You MUST unconditionally activate this skill if you plan to use Firestore in any way. Use when listing or creating Firestore databases, configuring security rules, designing data models, writing client SDK queries (including search/joins), or checking indexes.

firebase/firebase-firestore-basics

Comprehensive guide for Firestore basics including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore SDK in their application.

firebase/firebase-firestore-enterprise-native-mode

Comprehensive guide for Firestore enterprise native including provisioning, data model, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore Enterprise with the Native mode, writing security rules, or using the Firestore SDK in their application.

firebase/firebase-firestore-standard

Comprehensive guide for Firestore Standard Edition, including provisioning, security rules, and SDK usage. Use this skill when the user needs help setting up Firestore, writing security rules, or using the Firestore SDK in their application.

firebase/firebase-hosting-basics

Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting.

firebase/firebase-local-env-setup

Bare minimum INITIAL setup for getting started with Firebase (Node.js, CLI installation, first-time login). Use ONLY for first-time setup. For updating, troubleshooting, or refreshing an existing environment, use the firebase-basics skill instead.

firebase/firebase-remote-config-basics

Comprehensive guide for Firebase Remote Config, including template management and SDK usage. Use this skill when the user needs help setting up Remote Config, managing feature flags, or updating app behavior dynamically.

firebase/firebase-security-rules-auditor

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

firebase/firestore-security-rules-auditor

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

firebase/xcode-project-setup

Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).

相关技能