Cloud Functions for Firebase یک متد onCallGenkit دارد که به شما امکان میدهد یک تابع قابل فراخوانی با یک اکشن Genkit (یک جریان) ایجاد کنید. این توابع را میتوان با genkit/beta/client یا یک Cloud Functions for Firebase Client SDK فراخوانی کرد که به طور خودکار اطلاعات احراز هویت را اضافه میکند.
قبل از اینکه شروع کنی
- You should be familiar with the concept of Genkit flows , and how to write them. The instructions on this page assume that you already have defined some flows that you want to deploy.
- It's helpful, but not required, if you've used Cloud Functions for Firebase before.
راهاندازی یک پروژه فایربیس
Create a new Firebase project using the Firebase console , or choose an existing one.
Upgrade the project to the pay-as-you-go Blaze pricing plan , which is required for Cloud Functions production deployment.
Install the Firebase CLI .
Log into the Firebase CLI:
firebase loginfirebase login --reauth # alternative, if necessaryfirebase login --no-localhost # if running in a remote shellCreate a new project directory:
export PROJECT_ROOT=~/tmp/genkit-firebase-project1mkdir -p $PROJECT_ROOTInitialize a Firebase project in the directory:
cd $PROJECT_ROOTfirebase init functions
The rest of this page assumes that you've chosen to write your functions in JavaScript.
Wrap the flow in onCallGenkit
پس از اینکه یک پروژه Firebase راهاندازی کردید و Cloud Functions در آن مقداردهی اولیه کردید، میتوانید تعاریف جریان را در دایرکتوری functions پروژه کپی یا بنویسید. در اینجا یک مثال از جریان برای نشان دادن این موضوع آورده شده است:
const ai = genkit({ plugins: [googleAI()], model: gemini15Flash, }); const jokeTeller = ai.defineFlow({ name: "jokeTeller", inputSchema: z.string().nullable(), outputSchema: z.string(), streamSchema: z.string(), }, async (jokeType = "knock-knock", {sendChunk}) => { const prompt = `Tell me a ${jokeType} joke.`; // Call the `generateStream()` method to // receive the `stream` async iterable. const {stream, response: aiResponse} = ai.generateStream(prompt); // Send new words of the generative AI response // to the client as they are generated. for await (const chunk of stream) { sendChunk(chunk.text); } // Return the full generative AI response // to clients that may not support streaming. return (await aiResponse).text; }, );
برای استقرار جریانی مانند این، آن را با onCallGenkit که در firebase-functions/https موجود است، پوشش دهید. این متد کمکی تمام ویژگیهای توابع قابل فراخوانی را دارد و به طور خودکار از هر دو نوع پاسخهای استریمینگ و JSON پشتیبانی میکند.
const {onCallGenkit} = require("firebase-functions/https");
exports.tellJoke = onCallGenkit({ // Bind the Gemini API key secret parameter to the function. secrets: [apiKey], }, // Pass in the genkit flow. jokeTeller, );
Make API credentials available to deployed flows
Once deployed, your flows need a way to authenticate with any remote services they rely on. At a minimum, most flows need credentials for accessing the model API service they use.
For this example, do one of the following, depending on the model provider you chose:
Gemini (Google AI)
Generate an API key for the Gemini Developer API using Google AI Studio .
Store your API key in Google Cloud Secret Manager :
firebase functions:secrets:set GOOGLE_GENAI_API_KEYThis step is important to prevent accidentally leaking your API key, which grants access to a potentially metered service.
See Store and access sensitive configuration information for more information on managing secrets.
Edit
src/index.jsand add the following after the existing imports:const {defineSecret} = require("firebase-functions/params");
// Store the Gemini API key in Cloud Secret Manager. const apiKey = defineSecret("GOOGLE_GENAI_API_KEY");
Then, in the callable function definition, declare that the function needs access to this secret value:
// Bind the Gemini API key secret parameter to the function. secrets: [apiKey],
Now, when you deploy this function, your API key will be stored in Google Cloud Secret Manager , and available from the Cloud Functions environment.
Gemini (Vertex AI)
In the Google Cloud console, enable the Vertex AI API for your Firebase project.
On the IAM page , make sure that the Default compute service account is granted the Vertex AI User role.
The only secret you need to set up for this tutorial is for the model provider, but in general, you must do something similar for each service your flow uses.
(Optional) Add Firebase App Check enforcement
Firebase App Check uses native attestation to verify that our API is only being called by your application. The onCallGenkit method supports App Check enforcement declaratively.
export const generatePoem = onCallGenkit({
enforceAppCheck: true,
// Optional. Makes App Check tokens only usable once. This adds extra security
// at the expense of slowing down your app to generate a token for every API
// call
consumeAppCheckToken: true,
}, generatePoemFlow);
پیکربندی CORS (اشتراکگذاری منابع بین مبدا)
از گزینه cors برای کنترل اینکه کدام ریشهها میتوانند به تابع شما دسترسی داشته باشند، استفاده کنید.
به طور پیشفرض، توابع قابل فراخوانی CORS را طوری پیکربندی کردهاند که درخواستها را از همه مبدأها مجاز بدانند. برای مجاز کردن برخی از درخواستهای بین مبدأیی، اما نه همه آنها، لیستی از دامنههای خاص یا عبارات منظم را که باید مجاز باشند، ارسال کنید. به عنوان مثال:
export const tellJoke = onCallGenkit({
cors: 'mydomain.com',
}, jokeTeller);
مثال کامل
After you've made all of the changes described in this guide, your deployable flow will look something like the following example:
const {onCallGenkit} = require("firebase-functions/https"); const {defineSecret} = require("firebase-functions/params"); // Dependencies for Genkit. const {gemini15Flash, googleAI} = require("@genkit-ai/googleai"); const {genkit, z} = require("genkit"); // Store the Gemini API key in Cloud Secret Manager. const apiKey = defineSecret("GOOGLE_GENAI_API_KEY"); const ai = genkit({ plugins: [googleAI()], model: gemini15Flash, }); const jokeTeller = ai.defineFlow({ name: "jokeTeller", inputSchema: z.string().nullable(), outputSchema: z.string(), streamSchema: z.string(), }, async (jokeType = "knock-knock", {sendChunk}) => { const prompt = `Tell me a ${jokeType} joke.`; // Call the `generateStream()` method to // receive the `stream` async iterable. const {stream, response: aiResponse} = ai.generateStream(prompt); // Send new words of the generative AI response // to the client as they are generated. for await (const chunk of stream) { sendChunk(chunk.text); } // Return the full generative AI response // to clients that may not support streaming. return (await aiResponse).text; }, ); exports.tellJoke = onCallGenkit({ // Bind the Gemini API key secret parameter to the function. secrets: [apiKey], }, // Pass in the genkit flow. jokeTeller, );
Deploy flows to Firebase
After you've defined flows using onCallGenkit , you can deploy them as you would deploy other functions:
cd $PROJECT_ROOTfirebase deploy --only functions