將伺服器端遠端設定與 Cloud Functions 和 Vertex AI 搭配使用

本指南說明如何開始使用第 2 代 Cloud Functions,搭配伺服器端 Remote ConfigVertex AI Gemini API 進行伺服器端呼叫。

在本教學課程中,您將在類似聊天機器人的函式中新增 Remote Config,該函式會使用 Gemini 模型來回答使用者的問題。Remote Config 會管理 Gemini API 輸入內容 (包括您會在傳入的使用者查詢前加上提示訊息),您可以視需要透過 Firebase 控制台更新這些輸入內容。您將使用 Firebase Local Emulator Suite 來測試和 對函式進行偵錯,一旦確認運作無誤, 請前往 Google Cloud 測試。

事前準備

本指南假設您熟悉 JavaScript 開發 應用程式。

設定 Firebase 專案

如果您還沒有 Firebase 專案:

  1. 登入 Firebase 控制台

  2. 按一下「建立專案」,然後使用以下任一選項:

    • 選項 1:在「建立專案」工作流程的第一個步驟中輸入新專案名稱,即可建立新的 Firebase 專案 (以及其底層 Google Cloud 專案)。
    • 選項 2:在「建立專案」工作流程的第一個步驟中,從下拉式選單中選取 Google Cloud 專案名稱,即可在現有的 Google Cloud 專案中「新增 Firebase」。
  3. 系統提示時,您不必設定 Google Analytics, 這個解決方案。

  4. 繼續按照畫面上的指示建立專案。

如果您已有 Firebase 專案:

請繼續設定開發環境

設定開發環境

您需要 Node.js 環境才能編寫函式,並且需要 Firebase CLI 才能將函式部署至 Cloud Functions 執行階段。

  1. 安裝 Node.jsnpm

    如要安裝 Node.js 和 npm,建議您使用 Node Version Manager

  2. 使用以下程式碼安裝 Firebase CLI: 舉例來說,如要透過 npm 安裝 CLI,請執行 指令:

    npm install -g firebase-tools@latest
    

    這項指令會安裝全球適用的 firebase 指令。如果這是 指令失敗時 變更 npm 權限

    如要更新至最新版的 firebase-tools,請重新執行相同指令。

  3. 安裝 firebase-functionsfirebase-admin,並使用 --save 將它們儲存至 package.json

    npm install firebase-functions@latest firebase-admin@latest --save
    
,瞭解如何調查及移除這項存取權。

您現在可以開始導入 解決方案

導入作業

請按照下列步驟建立、測試及部署第 2 代 有 Remote ConfigVertex AICloud Functions

  1. Google Cloud 控制台中啟用 Vertex AI 建議的 API
  2. 初始化專案並安裝 Node 依附元件
  3. 設定 Admin SDK 服務帳戶的 IAM 權限 儲存金鑰
  4. 建立函式
  5. 建立特定伺服器的 Remote Config 範本
  6. 部署函式並在 Firebase Local Emulator Suite 中進行測試。
  7. 將函式部署至 Google Cloud

步驟 1:在 Google Cloud 控制台中啟用 Vertex AI 建議的 API

  1. 開啟 Google Cloud 控制台,然後在系統提示時選取專案。
  2. 在控制台頂端的「Search」欄位中,輸入 Vertex AI,然後等待 Vertex AI 出現在結果中。
  3. 選取 Vertex AI。「Vertex AI」資訊主頁會隨即顯示。
  4. 點選「Enable All Recommended APIs」

    API 啟用作業可能需要幾分鐘的時間才能完成。請保持頁面處於活動狀態並保持開啟,直到啟用程序完成為止。

  5. 如果帳單帳戶尚未啟用,系統會提示您新增或連結 Cloud Billing 帳戶。啟用帳單帳戶後,請返回 Vertex AI 資訊主頁,並確認已啟用所有建議的 API。

步驟 2:初始化專案並安裝節點依附元件

  1. 在電腦上開啟終端機,然後前往 建立函式
  2. 登入 Firebase:

    firebase login
    
  3. 執行下列指令來初始化 Cloud Functions for Firebase

    firebase init functions
    
  4. 選取「使用現有專案」,並指定專案 ID。

  5. 系統提示您選取要使用的語言時,請選擇「Javascript」,然後按下 Enter 鍵。

  6. 至於其他選項,則選取預設設定。

    系統會在目前目錄中建立 functions 目錄。您將在 找出可用來建構函式的 index.js 檔案。 包含函式依附元件的 node_modules 目錄。 以及包含套件依附元件的 package.json 檔案。

  7. 執行下列指令來新增 Admin SDKVertex AI 套件,方法是執行 下列指令,使用 --save 確保儲存在您的 package.json 檔案:

    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,您會看到包含該 ESLint 的汙染物。於 此外,請確認節點引擎版本與安裝的版本相符 以及您的最終在 Google Cloud 上執行的版本。舉例來說 package.json 中的 engines 段落已設為節點版本 18 如果使用的是 Node.js 20,請將檔案更新為使用 20:

  "engines": {
    "node": "20"
  },

步驟 3:設定 Admin SDK 服務帳戶的 IAM 權限並儲存金鑰

在這項解決方案中,您將使用 Firebase Admin SDK 服務帳戶執行 函式。

  1. Google Cloud 控制台中,開啟 IAM 與管理員頁面, 並找出 Admin SDK 服務帳戶 (名為 firebase-adminsdk)。
  2. 選取帳戶,然後按一下「編輯實體」。系統隨即顯示「編輯存取權」頁面。
  3. 按一下「Add another role」,然後選取「Remote Config Viewer」
  4. 按一下「新增其他角色」,選取「AI 平台開發人員」
  5. 按一下「新增其他角色」,選取「Vertex AI 使用者」
  6. 按一下「Add another role」(新增其他角色),然後選取「Cloud Run Invoker」
  7. 按一下 [儲存]

接著,匯出並儲存 Admin SDK 服務帳戶的憑證 在您的 GOOGLE_APPLICATION_CREDENTIALS 環境變數中。

  1. Google Cloud 控制台中,開啟 憑證頁面
  2. 按一下 Admin SDK 服務帳戶,開啟「詳細資料」頁面。
  3. 按一下「鍵」
  4. 按一下「新增鍵」>建立新的金鑰
  5. 確認您已選取「JSON」做為「金鑰類型」,然後按一下「建立」
  6. 將金鑰下載到電腦上的安全位置。
  7. 在終端機中,將金鑰匯出為環境變數:

    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
    
,瞭解如何調查及移除這項存取權。

步驟 4:建立函式

在這個步驟中,您將建構一個函式,用於處理使用者輸入內容 並採用 AI 技術生成回覆您將結合多個程式碼片段,建立可初始化 Admin SDKVertex AI Gemini API、使用 Remote Config 設定預設參數、擷取最新 Remote Config 參數、處理使用者輸入內容,以及將回應串流傳送給使用者的完整函式。

  1. 在程式碼集中,在文字編輯器或 IDE 中開啟 functions/index.js
  2. 刪除現有內容,然後新增 Admin SDKRemote ConfigVertex 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();
    
  3. 設定函式無法連線至 Remote Config 伺服器時,所使用的預設值。這個解決方案會將 textModelgenerationConfigsafetySettingstextPromptlocation 設為 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-preview-0514",
      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
    };
    
  4. 建立函式並設定函式 伺服器端 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;
    
  5. 設定 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');
      }
    });
    
  6. 儲存並關閉檔案。

步驟 5:建立特定伺服器的 Remote Config 範本

接著,請建立伺服器端 Remote Config 範本,並設定要在函式中使用的參數和值。如要建立特定伺服器的 Remote Config 範本,請按照下列步驟操作:

  1. 開啟 Firebase 控制台,然後從導覽選單展開 「Run」並選取 Remote Config
  2. Remote Config 頁面頂端的「Client/Server」選取器中,選取「Server」

    • 如果您是第一次使用 Remote Config 或伺服器範本, 按一下「Create Configuration」。「建立第一個伺服器端參數」窗格隨即顯示。
    • 如果您之前使用過 Remote Config 伺服器範本,請按一下「新增參數」
  3. 請定義下列 Remote Config 參數:

    參數名稱 說明 類型 預設值
    model_name 模型名稱
    如需可在程式碼中使用的模型名稱最新清單,請參閱 型號 版本和生命週期可用 模型名稱
    字串 gemini-1.5-pro-preview-0514
    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
  4. 參數新增完畢後,請仔細檢查參數, 確認資料類型正確無誤後,按一下「發布變更」

步驟 6:部署函式並在 Firebase Local Emulator Suite 中測試。

您現在可以使用 Firebase Local Emulator Suite 在本機部署及測試函式了。

  1. 確認已將 GOOGLE_APPLICATION_CREDENTIALS 設為環境 變數,如步驟 3:為 Admin SDK 服務帳戶,並儲存 鍵。接著,從 functions 目錄的父項目錄,請將函式部署至 Firebase 模擬器:

    firebase emulators:start --project PROJECT_ID --only functions
    
  2. 開啟 模擬器的記錄 頁面。 這樣應該就會顯示函式已載入。

  3. 執行下列指令即可存取函式,其中 PROJECT_ID 是您的專案 ID,LOCATION 則是您部署函式的區域 (例如 us-central1):

    curl http://localhost:5001/PROJECT_ID/LOCATION/generateWithVertex
    
  4. 請等待回應,然後返回 Firebase Emulator 記錄檔頁面,或 控制台,檢查是否有任何錯誤或警告。

  5. 嘗試傳送一些使用者輸入內容,請留意以下因素: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
    
  6. 變更以下網址中的 Remote Config 伺服器範本: Firebase 控制台,然後重新存取函式來觀察變更情形。

步驟 7:將函式部署至 Google Cloud

測試並驗證函式後,即可將其部署至 Google Cloud 並測試實際運作的函式。

部署函式

使用 Firebase CLI 部署函式:

firebase deploy --only functions

禁止在未經驗證的情況下存取函式

使用 Firebase 部署函式時,如果機構政策未禁止未經認證的叫用作業,系統預設會允許這類作業。在測試期間,以及在使用 App Check 進行安全防護前,建議您封鎖未經認證的存取權。

如要封鎖未經驗證的函式存取權,請按照下列步驟操作:

  1. Google Cloud 控制台中開啟「Cloud Run」

  2. 依序按一下 generateWithVertex 和「安全性」分頁標籤。

  3. 啟用「需要驗證」,然後按一下「儲存」

將使用者帳戶設為使用「Admin SDK」服務帳戶憑證

由於 Admin SDK 服務帳戶具備執行函式及與 Remote ConfigVertex AI Gemini API 互動的所有必要角色和權限,因此您應該使用該帳戶執行函式。待辦 如此,您必須能夠從自己的使用者帳戶為該帳戶建立權杖。

下列步驟說明如何設定使用者帳戶和功能 以 Admin SDK 服務帳戶權限執行。

  1. Google Cloud 控制台中啟用 IAM Service Account Credentials API
  2. 服務帳戶權杖建立者角色授予使用者帳戶:在 在 Google Cloud 控制台中開啟 IAM 與管理 >IAM,請選取使用者 然後按一下「編輯主體」>新增其他角色
  3. 選取「Service Account Token Creator」,然後按一下「Save」

    如要進一步瞭解服務帳戶模擬功能,請參閱 服務帳戶 冒用他人身分 Google Cloud說明文件中。

  4. 開啟 Google Cloud 主控台 Cloud Functions 頁面,然後按一下「Functions」清單中的「generateWithVertex」 函式。

  5. 選取「觸發條件」>編輯及展開執行階段、建構、連線和 安全性設定

  6. 在「執行階段」分頁中,將「執行階段服務帳戶」變更為「Admin SDK 帳戶」

  7. 依序按一下「Next」和「Deploy」

設定 gcloud CLI

如要透過指令列安全地執行及測試函式,您必須使用 Cloud Functions 服務進行驗證,並取得有效的驗證權杖。

如要啟用權杖產生功能,請安裝並設定 gcloud CLI:

  1. 如果電腦尚未安裝 gcloud CLI,請按照「安裝 gcloud CLI」一節所述安裝該工具。

  2. 取得 Google Cloud 帳戶的存取憑證:

    gcloud auth login
    
  3. 在 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 伺服器範本並發布 再測試不同選項

後續步驟