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 配额使用情况,必要时升级计划。