constai=genkit({plugins:[googleAI()],model:gemini15Flash,});constjokeTeller=ai.defineFlow({name:"jokeTeller",inputSchema:z.string().nullable(),outputSchema:z.string(),streamSchema:z.string(),},async(jokeType="knock-knock",{sendChunk})=>{constprompt=`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.forawait(constchunkofstream){sendChunk(chunk.text);}// Return the full generative AI response// to clients that may not support streaming.return(awaitaiResponse).text;},);
exportconstgeneratePoem=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// callconsumeAppCheckToken:true,},generatePoemFlow);
CORS(クロスオリジン リソース シェアリング)を構成する
cors オプションを使用して、関数にアクセスできるオリジンを制御します。
デフォルトでは、すべての送信元からのリクエストを許可するように、呼び出し可能関数には CORS が構成されています。一部のクロスオリジン リクエストを許可する場合は、許可するドメインまたは正規表現のリストを渡します。次に例を示します。
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.constapiKey=defineSecret("GOOGLE_GENAI_API_KEY");constai=genkit({plugins:[googleAI()],model:gemini15Flash,});constjokeTeller=ai.defineFlow({name:"jokeTeller",inputSchema:z.string().nullable(),outputSchema:z.string(),streamSchema:z.string(),},async(jokeType="knock-knock",{sendChunk})=>{constprompt=`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.forawait(constchunkofstream){sendChunk(chunk.text);}// Return the full generative AI response// to clients that may not support streaming.return(awaitaiResponse).text;},);exports.tellJoke=onCallGenkit({// Bind the Gemini API key secret parameter to the function.secrets:[apiKey],},// Pass in the genkit flow.jokeTeller,);
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-08-17 UTC。"],[],[],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"]]