本指南說明如何開始使用第 2 代Cloud Functions伺服器端 Remote Config,從伺服器端呼叫 Vertex AI Gemini API。
在本教學課程中,您將在類似聊天機器人的函式中新增 Remote Config,該函式會使用 Gemini 模型回答使用者問題。Remote Config 會管理 Gemini API 輸入內容 (包括您在傳入的使用者查詢中預先加入的提示),您也可以透過 Firebase 控制台隨時更新這些輸入內容。您也會使用 Firebase Local Emulator Suite 測試及偵錯函式,確認函式可正常運作後,再將函式部署至 Google Cloud 並進行測試。
事前準備
本指南假設您熟悉使用 JavaScript 開發應用程式。
設定 Firebase 專案
如果您還沒有 Firebase 專案:
登入 Firebase 控制台。
按一下「建立專案」,然後使用下列任一選項:
- 選項 1:在「建立專案」工作流程的第一個步驟中輸入新專案名稱,即可建立新的 Firebase 專案 (以及底層的Google Cloud專案)。
- 選項 2:在「建立專案」工作流程的第一個步驟中,從下拉式選單選取 Google Cloud 專案名稱,即可將 Firebase「新增至」現有 Google Cloud 專案。
系統提示時,不需要設定 Google Analytics 即可使用這項解決方案。
繼續按照畫面上的指示建立專案。
如果您已有 Firebase 專案:
請繼續設定開發環境。
設定開發環境
您需要 Node.js 環境來編寫函式,並使用 Firebase CLI 將函式部署至 Cloud Functions 執行階段。
-
如要安裝 Node.js 和 npm,建議使用 Node Version Manager。
使用偏好的方法安裝 Firebase CLI。舉例來說,如要使用 npm 安裝 CLI,請執行下列指令:
npm install -g firebase-tools@latest
這項指令會安裝全域可用的
firebase
指令。如果這個指令失敗,你可能需要變更 npm 權限。如要更新至最新版的
firebase-tools
,請重新執行相同指令。安裝
firebase-functions
和firebase-admin
,並使用--save
將這些檔案儲存到package.json
:npm install firebase-functions@latest firebase-admin@latest --save
您現在可以開始導入這項解決方案。
導入作業
請按照下列步驟,使用 Remote Config 和 Vertex AI 建立、測試及部署第 2 代 Cloud Functions:
- 在 Google Cloud控制台中啟用 Vertex AI 個建議的 API。
- 初始化專案並安裝 Node 依附元件。
- 為 Admin SDK 服務帳戶設定 IAM 權限,並儲存金鑰。
- 建立函式。
- 建立伺服器專屬的 Remote Config 範本。
- 部署函式,並在 Firebase Local Emulator Suite 中測試。
- 將函式部署至 Google Cloud。
步驟 1:在 Google Cloud控制台中啟用Vertex AI建議的 API
- 開啟 Google Cloud 控制台,並在系統提示時選取專案。
- 在控制台頂端的「搜尋」欄位中,輸入 Vertex AI,然後等待 Vertex AI 出現在搜尋結果中。
- 選取「Vertex AI」。系統會顯示 Vertex AI 資訊主頁。
點選「啟用所有建議的 API」。
API 啟用作業可能需要一些時間才能完成。請保持頁面開啟,直到啟用完成。
如果尚未啟用帳單功能,系統會提示您新增或連結 Cloud Billing 帳戶。啟用帳單帳戶後,請返回 Vertex AI 資訊主頁,確認所有建議的 API 都已啟用。
步驟 2:初始化專案並安裝 Node 依附元件
- 在電腦上開啟終端機,然後前往要建立函式的目錄。
登入 Firebase:
firebase login
執行下列指令來初始化 Cloud Functions for Firebase:
firebase init functions
選取「使用現有專案」,並指定專案 ID。
系統提示選取要使用的語言時,請選擇 JavaScript,然後按下 Enter 鍵。
其他選項請選取預設值。
目前目錄中會建立
functions
目錄。其中包含index.js
檔案 (用於建構函式)、node_modules
目錄 (內含函式的依附元件),以及package.json
檔案 (內含套件依附元件)。執行下列指令,使用
--save
確保套件儲存至package.json
檔案,新增 Admin SDK 和 Vertex AI 套件:cd functions npm install firebase-admin@latest @google-cloud/vertexai --save
您的 functions/package.json
檔案現在應如下所示,並指定最新版本:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "20"
},
"main": "index.js",
"dependencies": {
"@google-cloud/vertexai": "^1.1.0",
"firebase-admin": "^12.1.0",
"firebase-functions": "^5.0.0"
},
"devDependencies": {
"firebase-functions-test": "^3.1.0"
},
"private": true
}
請注意,如果您使用 ESLint,會看到包含該項目的詩節。此外,請確認節點引擎版本與您安裝的 Node.js 版本,以及最終在 Google Cloud 上執行的版本相符。舉例來說,如果 package.json
中的 package.json
節已設定為 Node.js 18 版,但您使用的是 Node.js 20 版,請更新檔案以使用 20 版:engines
"engines": {
"node": "20"
},
步驟 3:為 Admin SDK 服務帳戶設定 IAM 權限,並儲存金鑰
在本解決方案中,您會使用 Firebase Admin SDK 服務帳戶執行函式。
- 在 Google Cloud 控制台中,開啟「IAM 與管理」頁面,然後找出 Admin SDK 服務帳戶 (名為
firebase-adminsdk
)。 - 選取帳戶,然後按一下「編輯主體」。「編輯存取權」頁面隨即顯示。
- 按一下「Add another role」(新增其他角色),然後選取「Remote Config 檢視者」。
- 按一下「新增其他角色」,然後選取「AI Platform 開發人員」。
- 按一下「Add another role」(新增其他角色),然後選取 Vertex AI 使用者。
- 按一下「新增其他角色」,然後選取「Cloud Run Invoker」。
- 按一下 [儲存]。
接著,匯出 Admin SDK 服務帳戶的憑證,並儲存在 GOOGLE_APPLICATION_CREDENTIALS
環境變數中。
- 在 Google Cloud 控制台中,開啟「憑證」頁面。
- 按一下 Admin SDK 服務帳戶,開啟「詳細資料」頁面。
- 點選「金鑰」。
- 依序按一下「新增金鑰」 >「建立新的金鑰」。
- 確認已選取「JSON」做為「金鑰類型」,然後按一下「建立」。
- 將金鑰下載到電腦上的安全位置。
從終端機將金鑰匯出為環境變數:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
步驟 4:建立函式
在這個步驟中,您將建構可處理使用者輸入內容並生成 AI 輔助回覆的函式。您將結合多個程式碼片段,建構可初始化 Admin SDK 和 Vertex AI Gemini API、使用 Remote Config 設定預設參數、擷取最新 Remote Config 參數、處理使用者輸入內容,以及將回應串流傳回給使用者的完整函式。
- 在程式碼庫中,使用文字編輯器或 IDE 開啟
functions/index.js
。 刪除現有內容,然後新增 Admin SDK、Remote Config 和 Vertex AI SDK,並將下列程式碼貼到檔案中,初始化應用程式:
const { onRequest } = require("firebase-functions/v2/https"); const logger = require("firebase-functions/logger"); const { initializeApp } = require("firebase-admin/app"); const { VertexAI } = require('@google-cloud/vertexai'); const { getRemoteConfig } = require("firebase-admin/remote-config"); // Set and check environment variables. const project = process.env.GCLOUD_PROJECT; // Initialize Firebase. const app = initializeApp();
設定函式無法連線至 Remote Config 伺服器時使用的預設值。這個解決方案會將
textModel
、generationConfig
、safetySettings
、textPrompt
和location
設定為 Remote Config 參數,對應於本指南稍後會設定的 Remote Config 參數。如要進一步瞭解這些參數,請參閱 Vertex AI Node.js 用戶端。您也可以選擇設定參數,控管是否要存取 Vertex AI Gemini API (在本例中,參數稱為
vertex_enabled
)。這項設定在測試函式時非常實用。在下列程式碼片段中,這個值設為false
,在測試基本函式部署作業時,會略過使用 Vertex AI。設為true
會叫用 Vertex AI Gemini API。// Define default (fallback) parameter values for Remote Config. const defaultConfig = { // Default values for Vertex AI. model_name: "gemini-1.5-flash-002", generation_config: [{ "stopSequences": [], "temperature": 0.7, "maxOutputTokens": 64, "topP": 0.1, "topK": 20 }], prompt: "I'm a developer who wants to learn about Firebase and you are a \ helpful assistant who knows everything there is to know about Firebase!", safety_settings: [{ "category": "HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE" }], location: 'us-central1', // Disable Vertex AI Gemini API access for testing. vertex_enabled: false };
建立函式並設定伺服器端 Remote Config:
// Export the function. exports.generateWithVertex = onRequest(async (request, response) => { try { // Set up Remote Config. const rc = getRemoteConfig(app); // Get the Remote Config template and assign default values. const template = await rc.getServerTemplate({ defaultConfig: defaultConfig }); // Add the template evaluation to a constant. const config = template.evaluate(); // Obtain values from Remote Config. const textModel = config.getString("model_name") || defaultConfig.model_name; const textPrompt = config.getString("prompt") || defaultConfig.prompt; const generationConfig = config.getString("generation_config") || defaultConfig.generation_config; const safetySettings = config.getString("safety_settings") || defaultConfig.safety_settings; const location = config.getString("location") || defaultConfig.location; const vertexEnabled = config.getBoolean("is_vertex_enabled") || defaultConfig.vertex_enabled;
設定 Vertex AI,並新增對話和回覆邏輯:
// Allow user input. const userInput = request.query.prompt || ''; // Instantiate Vertex AI. const vertex_ai = new VertexAI({ project: project, location: location }); const generativeModel = vertex_ai.getGenerativeModel({ model: textModel, safety_settings: safetySettings, generation_config: generationConfig, }); // Combine prompt from Remote Config with optional user input. const chatInput = textPrompt + " " + userInput; if (!chatInput) { return res.status(400).send('Missing text prompt'); } // If vertexEnabled isn't true, do not send queries to Vertex AI. if (vertexEnabled !== true) { response.status(200).send({ message: "Vertex AI call skipped. Vertex is not enabled." }); return; } logger.log("\nRunning with model ", textModel, ", prompt: ", textPrompt, ", generationConfig: ", generationConfig, ", safetySettings: ", safetySettings, " in ", location, "\n"); const result = await generativeModel.generateContentStream(chatInput); response.writeHead(200, { 'Content-Type': 'text/plain' }); for await (const item of result.stream) { const chunk = item.candidates[0].content.parts[0].text; logger.log("Received chunk:", chunk); response.write(chunk); } response.end(); } catch (error) { logger.error(error); response.status(500).send('Internal server error'); } });
儲存並關閉檔案。
步驟 5:建立伺服器專屬的 Remote Config 範本
接著,建立伺服器端 Remote Config 範本,並設定要在函式中使用的參數和值。如要建立伺服器專屬範本,請按照下列步驟操作:Remote Config
- 開啟 Firebase 控制台,然後在導覽選單中展開「執行」,並選取 Remote Config。
在頁面頂端的「Client/Server」(用戶端/伺服器) 選取器中,選取「Server」(伺服器)。Remote Config
- 如果這是您首次使用 Remote Config 或伺服器範本,請按一下「建立設定」。「建立第一個伺服器端參數」窗格隨即顯示。
- 如果不是第一次使用 Remote Config 伺服器範本,請按一下「新增參數」。
定義下列 Remote Config 參數:
參數名稱 說明 類型 預設值 model_name
模型名稱
如要查看可在程式碼中使用的最新模型名稱清單,請參閱「模型版本和生命週期」 或「可用模型名稱」。字串 gemini-2.0-flash
prompt
要加在使用者查詢內容開頭的提示。 字串 I'm a developer who wants to learn about Firebase and you are a helpful assistant who knows everything there is to know about Firebase!
generation_config
要傳送至模型的參數。 JSON [{"stopSequences": ["I hope this helps"],"temperature": 0.7,"maxOutputTokens": 512, "topP": 0.1,"topK": 20}]
safety_settings
Vertex AI的安全設定。 JSON [{"category": "HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "HarmBlockThreshold.BLOCK_LOW_AND_ABOVE"}]
location
執行 Vertex AI 服務和模型的位置。 字串 us-central1
is_vertex_enabled
選用參數,可控制是否要將查詢傳送至 Vertex AI。 布林值 true
新增完畢後,請仔細檢查參數和資料型別是否正確,然後按一下「發布變更」。
步驟 6:部署函式並在 Firebase Local Emulator Suite 中測試
現在您可以使用 Firebase Local Emulator Suite 在本機部署及測試函式。
請確認您已按照「步驟 3:為服務帳戶設定 IAM 權限並儲存金鑰」一文的說明,將
GOOGLE_APPLICATION_CREDENTIALS
設為環境變數。Admin SDK接著,從functions
目錄的父項目錄,將函式部署至 Firebase 模擬器:firebase emulators:start --project PROJECT_ID --only functions
開啟模擬器的記錄頁面。這應該會顯示函式已載入。
執行下列指令來存取函式,其中 PROJECT_ID 是專案 ID,LOCATION 則是您部署函式的區域 (例如
us-central1
):curl http://localhost:5001/PROJECT_ID/LOCATION/generateWithVertex
等待回覆,然後返回 Firebase Emulator 記錄頁面或控制台,檢查是否有任何錯誤或警告。
嘗試傳送一些使用者輸入內容,請注意,由於
is_vertex_enabled
是在 Remote Config 伺服器範本中設定,因此這應該會透過 Vertex AI Gemini API 存取 Gemini 模型,且可能會產生費用:curl http://localhost:5001/PROJECT_ID/LOCATION/generateWithVertex?prompt=Tell%20me%20everything%20you%20know%20about%20cats
在 Firebase 控制台上變更 Remote Config 伺服器範本,然後重新存取函式,觀察變更。
步驟 7:將函式部署至 Google Cloud
測試及驗證函式後,即可部署至 Google Cloud 並測試上線的函式。
部署函式
使用 Firebase CLI 部署函式:
firebase deploy --only functions
禁止未經驗證的函式存取權
使用 Firebase 部署函式時,如果機構政策未加以限制,系統預設會允許未經驗證的呼叫。在測試期間和使用 App Check 保護之前,建議您封鎖未經驗證的存取權。
如要封鎖未經驗證的函式存取權,請按照下列步驟操作:
設定使用者帳戶,以使用 Admin SDK 服務帳戶憑證
由於 Admin SDK 服務帳戶具備執行函式及與 Remote Config 和 Vertex AI Gemini API 互動的所有必要角色和權限,因此您會想使用這個帳戶執行函式。如要執行這項操作,您必須能從使用者帳戶為該帳戶建立權杖。
下列步驟說明如何設定使用者帳戶和函式,以 Admin SDK 服務帳戶權限執行。
- 在 Google Cloud 控制台中,啟用 IAM Service Account Credentials API。
- 為使用者帳戶授予「服務帳戶憑證建立者」角色:在 Google Cloud 控制台中,依序開啟「IAM & Admin」(IAM 與管理) >「IAM」,選取使用者帳戶,然後按一下「Edit principal」(編輯主體) >「Add another role」(新增其他角色)。
選取「服務帳戶憑證建立者」,然後按一下「儲存」。
如要進一步瞭解服務帳戶模擬功能,請參閱 Google Cloud 說明文件中的「服務帳戶模擬」一文。
開啟 Google Cloud 控制台 Cloud Functions 頁面,然後按一下「Functions」清單中的 generateWithVertex 函式。
依序選取「觸發條件」>「編輯」,然後展開「執行階段、建構作業、連線和安全性設定」。
在「執行階段」分頁中,將「執行階段服務帳戶」變更為「Admin SDK 帳戶」。
依序點選「下一步」和「部署」。
設定 gcloud CLI
如要從指令列安全地執行及測試函式,您必須向 Cloud Functions 服務進行驗證,並取得有效的驗證權杖。
如要啟用權杖產生功能,請安裝及設定 gcloud CLI:
如果電腦尚未安裝 gcloud CLI,請按照「安裝 gcloud CLI」一文的說明進行安裝。
取得 Google Cloud 帳戶的存取憑證:
gcloud auth login
在 gcloud 中設定專案 ID:
gcloud config set project PROJECT_ID
測試函式
您現在可以在 Google Cloud 中測試函式。如要測試函式,請執行下列指令:
curl -X POST https://LOCATION-PROJECT_ID.cloudfunctions.net/generateWithVertex \
-H "Authorization: bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json"
使用使用者提供的資料再試一次:
curl -X POST https://LOCATION-PROJECT_ID.cloudfunctions.net/generateWithVertex?prompt=Tell%20me%20everything%20you%20know%20about%20dogs \
-H "Authorization: bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json"
您現在可以變更 Remote Config 伺服器範本、發布變更,以及測試不同選項。
後續步驟
- Firebase 建議使用 App Check 保護 Cloud Functions。如要進一步瞭解如何使用 App Check 保護函式,請參閱「為 Cloud Functions 啟用 App Check 強制執行」。
- 使用伺服器端 Remote Config 和 App Check 試用可呼叫函式範例,方法是使用 Remote Config 和 App Check 呼叫 Vertex AI Gemini API。
- 進一步瞭解 Cloud Functions for Firebase。
- 進一步瞭解如何在伺服器環境中使用 Remote Config。