從應用程式叫用 Genkit 流程
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
Cloud Functions for Firebase 具有 onCallGenkit
方法,可讓您使用 Genkit 動作 (Flow) 建立可呼叫函式。您可以使用 genkit/beta/client
或 Cloud Functions 用戶端 SDK 呼叫這些函式,系統會自動新增驗證資訊。
事前準備
- 您應熟悉 Genkit 的流程概念,以及如何編寫流程。本頁的說明假設您已定義要部署的流程。
- 如果您曾使用 Cloud Functions for Firebase,會很有幫助,但並非必要。
設定 Firebase 專案
使用 Firebase 控制台建立新的 Firebase 專案,或選擇現有專案。
將專案升級至 Blaze 方案,這是 Cloud Functions 實際工作環境部署作業的必要條件。
安裝 Firebase CLI。
使用 Firebase CLI 登入:
firebase login
firebase login --reauth # alternative, if necessary
firebase login --no-localhost # if running in a remote shell
建立新的專案目錄:
export PROJECT_ROOT=~/tmp/genkit-firebase-project1
mkdir -p $PROJECT_ROOT
在目錄中初始化 Firebase 專案:
cd $PROJECT_ROOT
firebase init functions
本頁其餘部分假設您已選擇以 JavaScript 撰寫函式。
將流程包裝在 onCallGenkit
中
使用 Cloud Functions 設定 Firebase 專案後,您可以在專案的 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/v2/https");
exports.tellJoke = onCallGenkit({
// Bind the Gemini API key secret parameter to the function.
secrets: [apiKey],
},
// Pass in the genkit flow.
jokeTeller,
);
讓已部署的流程可使用 API 憑證
部署後,流程需要驗證所依附的任何遠端服務。大多數流程至少需要憑證,才能存取所用的模型 API 服務。
在本範例中,請根據您選擇的模型供應商,執行下列任一操作:
Gemini (Google AI)
確認 Google AI 是否支援你的所在地區。
使用 Google AI Studio 產生 Gemini API 金鑰。
將 API 金鑰儲存在 Cloud Secret Manager 中:
firebase functions:secrets:set GOOGLE_GENAI_API_KEY
這個步驟非常重要,可避免 API 金鑰意外外洩,因為這可能會授予存取計量服務的權限。
如要進一步瞭解如何管理密鑰,請參閱「儲存及存取機密設定資訊」。
編輯 src/index.js
,並在現有匯入內容後新增下列項目:
const {defineSecret} = require("firebase-functions/params");
// Store the Gemini API key in Cloud Secret Manager.
const apiKey = defineSecret("GOOGLE_GENAI_API_KEY");
接著,在可呼叫函式定義中,宣告函式需要存取這個密鑰值:
// Bind the Gemini API key secret parameter to the function.
secrets: [apiKey],
現在部署這項函式時,API 金鑰會儲存在 Cloud Secret Manager 中,並可從 Cloud Functions 環境取得。
Gemini (Vertex AI)
在 Cloud 控制台中,為 Firebase 專案啟用 Vertex AI API。
在「IAM」頁面中,確認「預設運算服務帳戶」已獲派「Vertex AI 使用者」角色。
在本教學課程中,您只需要為模型供應商設定密鑰,但一般來說,您必須為流程使用的每項服務執行類似操作。
(選用) 新增 App Check 強制執行
Firebase App Check 會使用原生認證,確認 API 僅由您的應用程式呼叫。onCallGenkit
支援以宣告方式強制執行 App Check。
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);
完整範例
完成上述所有變更後,可部署的流程會如下列範例所示:
const {onCallGenkit} = require("firebase-functions/v2/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,
);
將流程部署至 Firebase
使用 onCallGenkit
定義流程後,您可以像部署其他函式一樣部署流程:
cd $PROJECT_ROOT
firebase deploy --only functions
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間:2025-08-31 (世界標準時間)。"],[],[],null,["\u003cbr /\u003e\n\nCloud Functions for Firebase has an `onCallGenkit` method that lets you\ncreate a [callable function](/docs/functions/callable?gen=2nd) with a Genkit\naction (a Flow). These functions can be called with `genkit/beta/client` or the\n[Cloud Functions client SDKs](/docs/functions/callable?gen=2nd#call_the_function),\nwhich automatically add auth information.\n\nBefore you begin\n\n- You should be familiar with Genkit's concept of [flows](/docs/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.\n- It's helpful, but not required, if you've used Cloud Functions for Firebase before.\n\nSet up a Firebase project\n\n1. Create a new Firebase project using the [Firebase\n console](https://console.firebase.google.com/), or choose an existing one.\n\n2. Upgrade the project to the Blaze plan, which is required for Cloud\n Functions production deployment.\n\n3. Install the [Firebase CLI](/docs/cli).\n\n4. Log in with the Firebase CLI:\n\n firebase login\n firebase login --reauth # alternative, if necessary\n firebase login --no-localhost # if running in a remote shell\n\n5. Create a new project directory:\n\n export PROJECT_ROOT=~/tmp/genkit-firebase-project1\n mkdir -p $PROJECT_ROOT\n\n6. Initialize a Firebase project in the directory:\n\n cd $PROJECT_ROOT\n firebase init functions\n\nThe rest of this page assumes that you've chosen to write your functions\nin JavaScript.\n\nWrap the flow in `onCallGenkit`\n\nAfter you've set up a Firebase project with Cloud Functions, you can copy or\nwrite flow definitions in the project's `functions` directory. Here is an\nexample flow to demonstrate this: \n\n```javascript\nconst ai = genkit({\n plugins: [googleAI()],\n model: gemini15Flash,\n});\n\nconst jokeTeller = ai.defineFlow({\n name: \"jokeTeller\",\n inputSchema: z.string().nullable(),\n outputSchema: z.string(),\n streamSchema: z.string(),\n}, async (jokeType = \"knock-knock\", {sendChunk}) =\u003e {\n const prompt = `Tell me a ${jokeType} joke.`;\n\n // Call the `generateStream()` method to\n // receive the `stream` async iterable.\n const {stream, response: aiResponse} = ai.generateStream(prompt);\n\n // Send new words of the generative AI response\n // to the client as they are generated.\n for await (const chunk of stream) {\n sendChunk(chunk.text);\n }\n\n // Return the full generative AI response\n // to clients that may not support streaming.\n return (await aiResponse).text;\n},\n);https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/genkit-helloworld/functions/index.js#L39-L66\n```\n\nTo deploy a flow like this one, wrap it with `onCallGenkit`, available in\n`firebase-functions/https`. This helper method has all the features of [callable\nfunctions](/docs/functions/callable), and it automatically supports both\nstreaming and JSON responses. \n\n```javascript\nconst {onCallGenkit} = require(\"firebase-functions/v2/https\");\n``` \n\n```javascript\nexports.tellJoke = onCallGenkit({\n // Bind the Gemini API key secret parameter to the function.\n secrets: [apiKey],\n},\n// Pass in the genkit flow.\njokeTeller,\n);https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/genkit-helloworld/functions/index.js#L70-L78\n```\n\nMake API credentials available to deployed flows\n\nOnce deployed, your flows need a way to authenticate with any remote services\nthey rely on. At a minimum, most flows need credentials for accessing the\nmodel API service they use.\n\nFor this example, do one of the following, depending on the model provider you\nchose: \n\nGemini (Google AI)\n\n1. Make sure Google AI is [available in your\n region](https://ai.google.dev/available_regions).\n\n2. [Generate an API key](https://aistudio.google.com/app/apikey) for the\n Gemini API using Google AI Studio.\n\n3. Store your API key in Cloud Secret Manager:\n\n firebase functions:secrets:set GOOGLE_GENAI_API_KEY\n\n This step is important to prevent accidentally leaking your API key, which\n grants access to a potentially metered service.\n\n See [Store and access sensitive configuration information](/docs/functions/config-env?gen=2nd#secret-manager)\n for more information on managing secrets.\n4. Edit `src/index.js` and add the following after the existing imports:\n\n \u003cbr /\u003e\n\n ```javascript\n const {defineSecret} = require(\"firebase-functions/params\");\n ``` \n\n ```javascript\n // Store the Gemini API key in Cloud Secret Manager.\n const apiKey = defineSecret(\"GOOGLE_GENAI_API_KEY\");https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/genkit-helloworld/functions/index.js#L34-L35\n ```\n\n \u003cbr /\u003e\n\n Then, in the callable function definition, declare that the function needs access\n to this secret value: \n\n ```javascript\n // Bind the Gemini API key secret parameter to the function.\n secrets: [apiKey],https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/genkit-helloworld/functions/index.js#L72-L73\n ```\n\nNow, when you deploy this function, your API key will be stored in Cloud\nSecret Manager, and available from the Cloud Functions environment.\n\nGemini (Vertex AI)\n\n1. In the Cloud console, [Enable the Vertex AI\n API](https://console.cloud.google.com/apis/library/aiplatform.googleapis.com?project=_)\n for your Firebase project.\n\n2. On the [IAM](https://console.cloud.google.com/iam-admin/iam?project=_)\n page, ensure that the **Default compute service account** is granted the\n **Vertex AI User** role.\n\nThe only secret you need to set up for this tutorial is for the model provider,\nbut in general, you must do something similar for each service your flow uses.\n\n(Optional) Add App Check enforcement\n\n[Firebase App Check](/docs/app-check) uses native\nattestation to verify that your API is only being called by your application.\n`onCallGenkit` supports App Check enforcement declaratively. \n\n export const generatePoem = onCallGenkit({\n enforceAppCheck: true,\n // Optional. Makes App Check tokens only usable once. This adds extra security\n // at the expense of slowing down your app to generate a token for every API\n // call\n consumeAppCheckToken: true,\n }, generatePoemFlow);\n\nConfigure CORS (Cross-Origin Resource Sharing)\n\nUse the `cors` option to control which origins can access your function.\n\nBy default, callable functions have CORS configured to allow requests from all\norigins. To allow some cross-origin requests, but not all, pass a list of\nspecific domains or regular expressions that should be allowed. For example: \n\n export const tellJoke = onCallGenkit({\n cors: 'mydomain.com',\n }, jokeTeller);\n\nComplete example\n\nAfter you've made all of the changes described above, your deployable flow will\nlook something like the following example: \n\n```javascript\nconst {onCallGenkit} = require(\"firebase-functions/v2/https\");\nconst {defineSecret} = require(\"firebase-functions/params\");\n\n// Dependencies for Genkit.\nconst {gemini15Flash, googleAI} = require(\"@genkit-ai/googleai\");\nconst {genkit, z} = require(\"genkit\");\n\n// Store the Gemini API key in Cloud Secret Manager.\nconst apiKey = defineSecret(\"GOOGLE_GENAI_API_KEY\");\n\nconst ai = genkit({\n plugins: [googleAI()],\n model: gemini15Flash,\n});\n\nconst jokeTeller = ai.defineFlow({\n name: \"jokeTeller\",\n inputSchema: z.string().nullable(),\n outputSchema: z.string(),\n streamSchema: z.string(),\n}, async (jokeType = \"knock-knock\", {sendChunk}) =\u003e {\n const prompt = `Tell me a ${jokeType} joke.`;\n\n // Call the `generateStream()` method to\n // receive the `stream` async iterable.\n const {stream, response: aiResponse} = ai.generateStream(prompt);\n\n // Send new words of the generative AI response\n // to the client as they are generated.\n for await (const chunk of stream) {\n sendChunk(chunk.text);\n }\n\n // Return the full generative AI response\n // to clients that may not support streaming.\n return (await aiResponse).text;\n},\n);\n\nexports.tellJoke = onCallGenkit({\n // Bind the Gemini API key secret parameter to the function.\n secrets: [apiKey],\n},\n// Pass in the genkit flow.\njokeTeller,\n);https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/genkit-helloworld/functions/index.js#L18-L79\n```\n\nDeploy flows to Firebase\n\nAfter you've defined flows using `onCallGenkit`, you can deploy them as you would\ndeploy other functions: \n\n cd $PROJECT_ROOT\n firebase deploy --only functions"]]