在 JavaScript 中實作生成式 AI 應用程式的實際可觀察性技術

1. 總覽

生成式 AI 應用程式與其他應用程式一樣,都需要可觀測性。生成式 AI 是否需要特殊的觀測技術?

在本實驗室中,您將建立簡單的生成式 AI 應用程式。將其部署至 Cloud Run。並使用 Google Cloud Observability 服務和產品,為其導入必要的監控和記錄功能。

學習目標

  • 使用 Cloud Shell 編輯器撰寫使用 Vertex AI 的應用程式
  • 在 GitHub 中儲存應用程式程式碼
  • 使用 gcloud CLI 將應用程式的原始碼部署至 Cloud Run
  • 在生成式 AI 應用程式中新增監控和記錄功能
  • 使用記錄指標
  • 使用 Open Telemetry SDK 實作記錄和監控功能
  • 深入瞭解負責任的 AI 資料處理方式

2. 先決條件

如果沒有 Google 帳戶,請建立新帳戶

3. 專案設定

  1. 使用 Google 帳戶登入 Google Cloud 控制台
  2. 建立新專案,或選擇重複使用現有專案。記下您剛建立或選取的專案 ID。
  3. 為專案啟用計費功能
    • 完成本實驗室的結算費用應低於 $5 美元。
    • 您可以按照本實驗室結尾的步驟刪除資源,以免產生後續費用。
    • 新使用者可獲得價值 $300 美元的免費試用期
  4. 確認 Cloud Billing 的「我的專案」
      已啟用計費功能
    • 如果新專案的「Billing account」欄顯示 Billing is disabled,請按照下列步驟操作:
      1. 按一下「Actions」欄中的三點圖示
      2. 按一下「變更帳單」
      3. 選取要使用的帳單帳戶
    • 如果您參加的是現場活動,帳戶名稱可能為「Google Cloud Platform 試用帳單帳戶」

4. 準備 Cloud Shell 編輯器

  1. 前往 Cloud Shell 編輯器。如果系統顯示以下訊息,要求您授權 Cloud Shell 使用憑證呼叫 gcloud,請按一下「Authorize」(授權)繼續操作。
    按一下即可授權 Cloud Shell
  2. 開啟終端機視窗
    1. 按一下漢堡選單 漢堡選單圖示
    2. 按一下「終端機」
    3. 按一下「New Terminal」(新增終端機)
      在 Cloud Shell 編輯器中開啟新終端機
  3. 在終端機中設定專案 ID:
    gcloud config set project [PROJECT_ID]
    
    [PROJECT_ID] 替換為專案 ID。舉例來說,如果專案 ID 為 lab-example-project,指令會是:
    gcloud config set project lab-project-id-example
    
    如果系統提示以下訊息,指出 gcloud 要求提供憑證給 GCPI API,請按一下「Authorize」(授權)繼續操作。
    按一下即可授權 Cloud Shell
    執行成功後,您應該會看到以下訊息:
    Updated property [core/project].
    
    如果看到 WARNING 並收到 Do you want to continue (Y/N)? 提示,可能是輸入的專案 ID 有誤。按下 NEnter,找到正確的專案 ID 後,再次嘗試執行 gcloud config set project 指令。
  4. (選用) 如果您找不到專案 ID,請執行下列指令,查看所有專案的專案 ID,並依建立時間降序排序:
    gcloud projects list \
         --format='value(projectId,createTime)' \
         --sort-by=~createTime
    

5. 啟用 Google API

在終端機中,啟用本實驗室所需的 Google API:

gcloud services enable \
     run.googleapis.com \
     cloudbuild.googleapis.com \
     aiplatform.googleapis.com \
     logging.googleapis.com \
     monitoring.googleapis.com \
     cloudtrace.googleapis.com

這個指令需要一段時間才能完成。最後,系統會產生類似以下的成功訊息:

Operation "operations/acf.p2-73d90d00-47ee-447a-b600" finished successfully.

如果收到開頭為 ERROR: (gcloud.services.enable) HttpError accessing 的錯誤訊息,且包含下列錯誤詳細資料,請延遲 1 到 2 分鐘後重試指令。

"error": {
  "code": 429,
  "message": "Quota exceeded for quota metric 'Mutate requests' and limit 'Mutate requests per minute' of service 'serviceusage.googleapis.com' ...",
  "status": "RESOURCE_EXHAUSTED",
  ...
}

6. 建立生成式 AI Node.js 應用程式

在這個步驟中,您會編寫簡單的應用程式程式碼,根據要求使用 Gemini 模型顯示 10 個與所選動物相關的有趣事實。請按照下列步驟建立應用程式程式碼。

  1. 在終端機中建立 codelab-o11y 目錄:
    mkdir ~/codelab-o11y
    
  2. 將目前目錄變更為 codelab-o11y
    cd ~/codelab-o11y
    
  3. 初始化 NodeJS 應用程式的 package.json
    npm init -y
    
  4. 安裝 fastify 套件:
    npm install fastify
    
  5. 安裝 Cloud SDK 套件,以便進行驗證及使用 Vertex AI:
    npm install google-auth-library @google-cloud/vertexai
    
  6. 建立 index.js 檔案,然後在 Cloud Shell 編輯器中開啟該檔案:
    cloudshell edit index.js
    
    現在編輯器視窗中應該會顯示空白檔案 (位於終端機上方)。畫面應如下所示:
    開始編輯 main.go 後顯示 Cloud Shell 編輯器
  7. 複製下列程式碼,並貼到開啟的 index.js 檔案中:
    const { VertexAI } = require('@google-cloud/vertexai');
    const { GoogleAuth } = require('google-auth-library');
    
    let generativeModel;
    const auth = new GoogleAuth();
    auth.getProjectId().then(result => {
      const vertex = new VertexAI({ project: result });
      generativeModel = vertex.getGenerativeModel({
          model: 'gemini-1.5-flash'
      });
    });
    
    const fastify = require('fastify')();
    const PORT = parseInt(process.env.PORT || '8080');
    
    fastify.get('/', async function (request, reply) {
      const animal = request.query.animal || 'dog';
      const prompt = `Give me 10 fun facts about ${animal}. Return this as html without backticks.`
      const resp = await generativeModel.generateContent(prompt);
      const html = resp.response.candidates[0].content.parts[0].text;
      reply.type('text/html').send(html);
    })
    
    fastify.listen({ host: '0.0.0.0', port: PORT }, function (err, address) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      console.log(`codelab-genai: listening on ${address}`);
    })
    
    幾秒後,Cloud Shell 編輯器會自動儲存程式碼。

將生成式 AI 應用程式的程式碼部署至 Cloud Run

  1. 在終端機視窗中執行指令,將應用程式的原始碼部署至 Cloud Run。
    gcloud run deploy codelab-o11y-service \
         --source="${HOME}/codelab-o11y/" \
         --region=us-central1 \
         --allow-unauthenticated
    
    如果看到如下提示,表示指令會建立新的存放區。按一下 Enter
    Deploying from source requires an Artifact Registry Docker repository to store built containers.
    A repository named [cloud-run-source-deploy] in region [us-central1] will be created.
    
    Do you want to continue (Y/n)?
    
    部署程序最多可能需要幾分鐘才能完成。部署程序完成後,您會看到類似以下的輸出內容:
    Service [codelab-o11y-service] revision [codelab-o11y-service-00001-t2q] has been deployed and is serving 100 percent of traffic.
    Service URL: https://codelab-o11y-service-12345678901.us-central1.run.app
    
  2. 將顯示的 Cloud Run 服務網址複製到瀏覽器的另一個分頁或視窗。或者,您也可以在終端機中執行下列指令,列印服務網址,然後按住 Ctrl 鍵並點選顯示的網址,開啟該網址:
    gcloud run services list \
         --format='value(URL)' \
         --filter='SERVICE:"codelab-o11y-service"'
    
    開啟網址時,您可能會收到 500 錯誤訊息,或看到以下訊息:
    Sorry, this is just a placeholder...
    
    這表示服務未完成部署作業。請稍候片刻,然後重新整理頁面。最後你會看到以「Fun Dog Facts」(狗狗趣味小知識) 開頭的文字,其中包含 10 個狗狗趣味小知識。

嘗試與應用程式互動,瞭解各種動物的有趣知識。如要這麼做,請將 animal 參數附加至網址,例如 ?animal=[ANIMAL],其中 [ANIMAL] 是動物名稱。舉例來說,附加 ?animal=cat 即可取得 10 個關於貓咪的趣味知識,附加 ?animal=sea turtle 則可取得 10 個關於海龜的趣味知識。

7. 稽核 Vertex API 呼叫

稽核 Google API 呼叫可回答「誰在何時何地呼叫特定 API?」等問題。在排解應用程式問題、調查資源耗用情形或執行軟體鑑識分析時,稽核作業非常重要。

稽核記錄可讓您追蹤管理員和系統活動,以及記錄對「資料讀取」和「資料寫入」API 作業的呼叫。如要稽核生成內容的 Vertex AI 要求,您必須在 Cloud 控制台中啟用「資料讀取」稽核記錄

  1. 按一下下方按鈕,在 Cloud 控制台中開啟「稽核記錄」頁面

  2. 確認頁面已選取您為這個實驗室建立的專案。所選專案會顯示在頁面左上角,漢堡選單的右側:
    Google Cloud 控制台專案下拉式選單
    如有需要,請從下拉式方塊選取正確的專案。
  3. 在「資料存取稽核記錄設定」表格的「服務」欄中,找出 Vertex AI API 服務,然後選取服務名稱左側的核取方塊,選取該服務。
    選取 Vertex AI API
  4. 在右側的資訊面板中,選取「資料讀取」稽核類型。
    檢查資料讀取記錄
  5. 按一下 [儲存]

如要產生稽核記錄,請開啟服務網址。重新整理頁面,同時變更 ?animal= 參數的值,即可取得不同的結果。

瞭解稽核記錄

  1. 按一下下方按鈕,在 Cloud 控制台中開啟「記錄檔探索工具」頁面:

  2. 將下列篩選器貼到「查詢」窗格。
    LOG_ID("cloudaudit.googleapis.com%2Fdata_access") AND
    protoPayload.serviceName="aiplatform.googleapis.com"
    
    「查詢」窗格是位於「Logs Explorer」頁面頂端的編輯器:
    查詢稽核記錄
  3. 點選「執行查詢」
  4. 選取其中一個稽核記錄項目,然後展開欄位,檢查記錄中擷取的資訊。
    您可以查看 Vertex API 呼叫的詳細資料,包括使用的方法和模型。您也可以查看呼叫者的身分,以及授權呼叫的權限。

8. 記錄與生成式 AI 的互動

您不會在稽核記錄中找到 API 要求參數或回應資料。不過,這項資訊對於排解應用程式和工作流程分析問題可能非常重要。在本步驟中,我們將新增應用程式記錄,填補這項缺口。記錄功能會使用 NodeJS console.log 的標準記錄方法,將結構化記錄寫入標準輸出。這個方法會運用 Cloud Run 功能,擷取列印至標準輸出的資訊,並自動擷取至 Cloud Logging。如要正確擷取結構化記錄,列印的記錄必須符合格式。請按照下列操作說明,在 NodeJS 應用程式中新增結構化記錄功能。

  1. 返回瀏覽器中的「Cloud Shell」視窗 (或分頁)。
  2. 在終端機中重新開啟 index.js
    cloudshell edit ~/codelab-o11y/index.js
    
  3. 請按照下列步驟記錄模型的回覆:
    1. 找到對 await generativeModel.generateContent() 的呼叫 (第 20 行)。
    2. 複製下列程式碼,然後貼到下一行的開頭。
        console.log(JSON.stringify({
            severity: 'DEBUG',
            message: 'Content is generated',
            animal: animal,
            prompt: prompt,
            response: resp.response,
        }));
      

修改處理常式函式,呼叫 console.log() 列印 JSON 結構,該結構定義遵循結構化格式設定指南。記錄會擷取要求中的動物參數,以及模型的提示和回覆。

幾秒後,Cloud Shell 編輯器會自動儲存變更。

將生成式 AI 應用程式的程式碼部署至 Cloud Run

  1. 在終端機視窗中執行指令,將應用程式的原始碼部署至 Cloud Run。
    gcloud run deploy codelab-o11y-service \
         --source="${HOME}/codelab-o11y/" \
         --region=us-central1 \
         --allow-unauthenticated
    
    如果看到如下提示,表示指令會建立新的存放區。按一下 Enter
    Deploying from source requires an Artifact Registry Docker repository to store built containers.
    A repository named [cloud-run-source-deploy] in region [us-central1] will be created.
    
    Do you want to continue (Y/n)?
    
    部署程序最多可能需要幾分鐘才能完成。部署程序完成後,您會看到類似以下的輸出內容:
    Service [codelab-o11y-service] revision [codelab-o11y-service-00001-t2q] has been deployed and is serving 100 percent of traffic.
    Service URL: https://codelab-o11y-service-12345678901.us-central1.run.app
    
  2. 將顯示的 Cloud Run 服務網址複製到瀏覽器的另一個分頁或視窗。或者,您也可以在終端機中執行下列指令,列印服務網址,然後按住 Ctrl 鍵並點選顯示的網址,開啟該網址:
    gcloud run services list \
         --format='value(URL)' \
         --filter='SERVICE:"codelab-o11y-service"'
    
    開啟網址時,您可能會收到 500 錯誤訊息,或看到以下訊息:
    Sorry, this is just a placeholder...
    
    這表示服務未完成部署作業。請稍候片刻,然後重新整理頁面。最後你會看到以「Fun Dog Facts」(狗狗趣味小知識) 開頭的文字,其中包含 10 個狗狗趣味小知識。

如要產生應用程式記錄,請開啟服務網址。重新整理頁面,同時變更 ?animal= 參數的值,即可取得不同的結果。
如要查看應用程式記錄,請執行下列操作:

  1. 按一下下方按鈕,在 Cloud 控制台中開啟記錄檔探索工具頁面:

  2. 將下列篩選條件貼到「查詢」窗格 (記錄檔探索工具介面中的 #2):
    LOG_ID("run.googleapis.com%2Fstdout") AND
    severity=DEBUG
    
  3. 點選「執行查詢」

查詢結果會顯示記錄,包括提示和 Vertex AI 回覆,以及安全評分

9. 計算與生成式 AI 的互動次數

Cloud Run 會寫入代管指標,可用於監控已部署的服務。使用者管理的監控指標可進一步控管資料,以及指標更新的頻率。如要實作這類指標,必須編寫程式碼來收集資料,並將資料寫入 Cloud Monitoring。如要瞭解如何使用 OpenTelemetry SDK 實作,請參閱下一個 (選用) 步驟。

這個步驟說明實作使用者指標的替代做法,也就是記錄指標。記錄指標可讓您從應用程式寫入 Cloud Logging 的記錄項目產生監控指標。我們將使用上一個步驟中實作的應用程式記錄,定義計數器類型的記錄型指標。這項指標會計算 Vertex API 的成功呼叫次數。

  1. 查看上一步使用的「記錄檔探索器」視窗。在「查詢」窗格下方找到「動作」下拉式選單,然後點選開啟。請參閱下方螢幕截圖,找出選單:
    查詢結果工具列,內含「動作」下拉式選單
  2. 在開啟的選單中選取「建立指標」,開啟「建立記錄指標」面板。
  3. 請按照下列步驟,在「建立記錄指標」面板中設定新的計數器指標:
    1. 設定「指標類型」:選取「計數器」
    2. 在「詳細資料」部分中,設定下列欄位:
      • 記錄指標名稱:將名稱設為 model_interaction_count。存在一些命名限制;詳情請參閱疑難排解一文。
      • 說明:輸入指標說明。例如:Number of log entries capturing successful call to model inference.
      • 單位:保留此欄位空白,或插入數字 1
    3. 保留「篩選器選取」部分的值。請注意,「Build filter」(建立篩選器) 欄位與我們用來查看應用程式記錄的篩選器相同。
    4. (選用) 新增標籤,方便計算每種動物的叫聲次數。注意:這個標籤可能會大幅增加指標的基數,因此不建議用於正式環境:
      1. 按一下 [Add label] (新增標籤)
      2. 在「標籤」部分中設定下列欄位:
        • 標籤名稱:將名稱設為 animal
        • 說明:輸入標籤說明。例如:Animal parameter
        • 標籤類型:選取 STRING
        • 欄位名稱:輸入 jsonPayload.animal
        • 規則運算式:留空。
      3. 然後按一下 [完成]
    5. 按一下「建立指標」即可建立指標。

您也可以使用 gcloud logging metrics create CLI 指令google_logging_metric Terraform 資源,從「記錄指標」頁面建立記錄指標。

如要產生指標資料,請開啟服務網址。多次重新整理開啟的頁面,對模型發出多個呼叫。和先前一樣,請嘗試在參數中使用不同動物。

輸入 PromQL 查詢,搜尋記錄指標資料。如要輸入 PromQL 查詢,請按照下列步驟操作:

  1. 按一下下方按鈕,在 Cloud 控制台中開啟 Metrics Explorer 頁面:

  2. 在查詢建構工具窗格的工具列中,選取名稱為「< > MQL」或「< > PromQL」的按鈕。如要瞭解按鈕位置,請參閱下圖。
    Metrics Explorer 中的 MQL 按鈕位置
  3. 確認「語言」切換按鈕已選取「PromQL」。語言切換鍵位於可格式化查詢的工具列中。
  4. 在「查詢」編輯器中輸入查詢:
    sum(rate(logging_googleapis_com:user_model_interaction_count{monitored_resource="cloud_run_revision"}[${__interval}]))
    
    如要進一步瞭解如何使用 PromQL,請參閱「在 Cloud Monitoring 中使用 PromQL」。
  5. 按一下 [Run query] (執行查詢),您會看到類似以下螢幕截圖的折線圖:
    顯示查詢的指標

    請注意,啟用「自動執行」切換按鈕後,系統就不會顯示「執行查詢」按鈕。

10. (選用) 使用 Open Telemetry 監控及追蹤

如上一步所述,您可以使用 OpenTelemetry (Otel) SDK 導入指標。建議在微服務架構中使用 OTel。這個步驟說明下列事項:

  • 初始化 OTel 元件,支援追蹤及監控應用程式
  • 使用 Cloud Run 環境的資源中繼資料填入 OTel 設定
  • 使用自動追蹤功能檢測 Flask 應用程式
  • 導入計數器指標,監控模型呼叫成功次數
  • 將追蹤記錄與應用程式記錄檔建立關聯

建議您使用 OTel 收集器,收集及擷取一或多項服務的所有可觀測性資料,做為產品層級服務的架構。為簡化程序,這個步驟中的程式碼不會使用收集器。而是使用 OTel 匯出功能,將資料直接寫入 Google Cloud。

設定 OTel 元件,以追蹤及監控指標

  1. 返回瀏覽器中的「Cloud Shell」視窗 (或分頁)。
  2. 安裝使用 OpenTelemetry 自動檢測功能所需的套件:
    npm install @opentelemetry/sdk-node \
      @opentelemetry/api \
      @opentelemetry/auto-instrumentations-node \
      @opentelemetry/instrumentation-express \
      @opentelemetry/instrumentation-http \
      @opentelemetry/sdk-metrics \
      @opentelemetry/sdk-trace-node \
      @google-cloud/opentelemetry-cloud-trace-exporter \
      @google-cloud/opentelemetry-cloud-monitoring-exporter \
      @google-cloud/opentelemetry-resource-util
    
  3. 在終端機中,建立新檔案 setup.js
    cloudshell edit ~/codelab-o11y/setup.js
    
  4. 複製下列程式碼並貼到編輯器,設定 OpenTelemetry 追蹤和監控功能。
    const opentelemetry = require("@opentelemetry/api");
    const { registerInstrumentations } = require('@opentelemetry/instrumentation');
    const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
    const { MeterProvider, PeriodicExportingMetricReader } = require("@opentelemetry/sdk-metrics");
    const { AlwaysOnSampler, SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base');
    const { Resource } = require('@opentelemetry/resources');
    const { ATTR_SERVICE_NAME } = require('@opentelemetry/semantic-conventions');
    const { FastifyInstrumentation } = require('@opentelemetry/instrumentation-fastify');
    const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
    const { TraceExporter } = require("@google-cloud/opentelemetry-cloud-trace-exporter");
    const { MetricExporter } = require("@google-cloud/opentelemetry-cloud-monitoring-exporter");
    const { GcpDetectorSync } = require("@google-cloud/opentelemetry-resource-util");
    
    module.exports = { setupTelemetry };
    
    function setupTelemetry() {
      const gcpResource = new Resource({
        [ATTR_SERVICE_NAME]: process.env.K_SERVICE,
      }).merge(new GcpDetectorSync().detect())
    
      const tracerProvider = new NodeTracerProvider({
        resource: gcpResource,
        sampler: new AlwaysOnSampler(),
        spanProcessors: [new SimpleSpanProcessor(new TraceExporter({
          // will export all resource attributes that start with "service."
          resourceFilter: /^service\./
        }))],
      });
      registerInstrumentations({
        tracerProvider: tracerProvider,
        instrumentations: [
          // Express instrumentation expects HTTP layer to be instrumented
          new HttpInstrumentation(),
          new FastifyInstrumentation(),
        ],
      });
      // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings
      tracerProvider.register();
    
      const meterProvider = new MeterProvider({
        resource: gcpResource,
        readers: [new PeriodicExportingMetricReader({
          // Export metrics every second (default quota is 30,000 time series ingestion requests per minute)
          exportIntervalMillis: 1_000,
          exporter: new MetricExporter(),
        })],
      });
      opentelemetry.metrics.setGlobalMeterProvider(meterProvider);
    }
    
  5. 返回終端機,然後重新開啟 index.js
    cloudshell edit ~/codelab-o11y/index.js
    
  6. 將程式碼換成可初始化 OpenTelemetry 追蹤和指標收集作業的版本,並在每次成功執行時更新效能計數器。如要更新程式碼,請刪除檔案內容,然後複製並貼上下列程式碼:
    const { VertexAI } = require('@google-cloud/vertexai');
    const { GoogleAuth } = require('google-auth-library');
    
    let generativeModel, traceIdPrefix;
    const auth = new GoogleAuth();
    auth.getProjectId().then(result => {
      const vertex = new VertexAI({ project: result });
      generativeModel = vertex.getGenerativeModel({
            model: 'gemini-1.5-flash'
      });
      traceIdPrefix = `projects/${result}/traces/`;
    });
    
    // setup tracing and monitoring OTel providers
    const { setupTelemetry }= require('./setup');
    setupTelemetry();
    
    const { trace, context } = require('@opentelemetry/api');
    function getCurrentSpan() {
      const current_span = trace.getSpan(context.active());
      return {
          trace_id: current_span.spanContext().traceId,
          span_id: current_span.spanContext().spanId,
          flags: current_span.spanContext().traceFlags
      };
    };
    
    const opentelemetry = require("@opentelemetry/api");
    const meter = opentelemetry.metrics.getMeter("genai-o11y/nodejs/workshop/example");
    const counter = meter.createCounter("model_call_counter");
    
    const fastify = require('fastify')();
    const PORT = parseInt(process.env.PORT || '8080');
    
    fastify.get('/', async function (request, reply) {
      const animal = request.query.animal || 'dog';
      const prompt = `Give me 10 fun facts about ${animal}. Return this as html without backticks.`
      const resp = await generativeModel.generateContent(prompt)
      const span = getCurrentSpan();
      console.log(JSON.stringify({
          severity: 'DEBUG',
          message: 'Content is generated',
          animal: animal,
          prompt: prompt,
          response: resp.response,
          "logging.googleapis.com/trace": traceIdPrefix + span.trace_id,
          "logging.googleapis.com/spanId": span.span_id,
      }));
      counter.add(1, { animal: animal });
      const html = resp.response.candidates[0].content.parts[0].text;
      reply.type('text/html').send(html);
    });
    
    fastify.listen({ host: '0.0.0.0', port: PORT }, function (err, address) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      console.log(`codelab-genai: listening on ${address}`);
    });
    

應用程式現在會使用 OpenTelemetry SDK,透過追蹤功能監控程式碼執行作業,並將成功執行的次數做為指標。main() 方法已修改,可設定追蹤記錄和指標的 OpenTelemetry 匯出工具,直接寫入 Google Cloud Tracing 和 Monitoring。此外,這項服務還會執行額外設定,以 Cloud Run 環境相關中繼資料填入收集到的追蹤記錄和指標。Handler() 函式已更新,每次 Vertex AI API 呼叫傳回有效結果時,指標計數器就會遞增。

幾秒後,Cloud Shell 編輯器會自動儲存變更。

將生成式 AI 應用程式的程式碼部署至 Cloud Run

  1. 在終端機視窗中執行指令,將應用程式的原始碼部署至 Cloud Run。
    gcloud run deploy codelab-o11y-service \
         --source="${HOME}/codelab-o11y/" \
         --region=us-central1 \
         --allow-unauthenticated
    
    如果看到如下提示,表示指令會建立新的存放區。按一下 Enter
    Deploying from source requires an Artifact Registry Docker repository to store built containers.
    A repository named [cloud-run-source-deploy] in region [us-central1] will be created.
    
    Do you want to continue (Y/n)?
    
    部署程序最多可能需要幾分鐘才能完成。部署程序完成後,您會看到類似以下的輸出內容:
    Service [codelab-o11y-service] revision [codelab-o11y-service-00001-t2q] has been deployed and is serving 100 percent of traffic.
    Service URL: https://codelab-o11y-service-12345678901.us-central1.run.app
    
  2. 將顯示的 Cloud Run 服務網址複製到瀏覽器的另一個分頁或視窗。或者,您也可以在終端機中執行下列指令,列印服務網址,然後按住 Ctrl 鍵並點選顯示的網址,開啟該網址:
    gcloud run services list \
         --format='value(URL)' \
         --filter='SERVICE:"codelab-o11y-service"'
    
    開啟網址時,您可能會收到 500 錯誤訊息,或看到以下訊息:
    Sorry, this is just a placeholder...
    
    這表示服務未完成部署作業。請稍候片刻,然後重新整理頁面。最後你會看到以「Fun Dog Facts」(狗狗趣味小知識) 開頭的文字,其中包含 10 個狗狗趣味小知識。

如要產生遙測資料,請開啟服務網址。重新整理頁面,同時變更 ?animal= 參數的值,即可取得不同的結果。

探索應用程式追蹤記錄

  1. 按一下下方按鈕,在 Cloud 控制台中開啟 Trace 探索工具頁面:

  2. 選取其中一個最近的追蹤記錄。您應該會看到 5 或 6 個類似下方螢幕截圖的範圍。
    在 Trace 探索器中查看應用程式時距
  3. 找出追蹤事件處理常式 (fun_facts 方法) 呼叫的範圍。這是最後一個名為「/」的範圍。
  4. 在「追蹤詳細資料」窗格中,選取「記錄和事件」。您會看到與這個特定時距相關聯的應用程式記錄檔。系統會使用追蹤記錄和記錄檔中的追蹤記錄和時距 ID,偵測關聯性。您應該會看到寫入提示的應用程式記錄,以及 Vertex API 的回覆。

探索計數器指標

  1. 按一下下方按鈕,在 Cloud 控制台中開啟 Metrics Explorer 頁面:

  2. 在查詢建構工具窗格的工具列中,選取名稱為「< > MQL」或「< > PromQL」的按鈕。如要瞭解按鈕位置,請參閱下圖。
    Metrics Explorer 中的 MQL 按鈕位置
  3. 確認「語言」切換按鈕已選取「PromQL」。語言切換鍵位於可格式化查詢的工具列中。
  4. 在「查詢」編輯器中輸入查詢:
    sum(rate(workload_googleapis_com:model_call_counter{monitored_resource="generic_task"}[${__interval}]))
    
  5. 按一下「執行查詢」。啟用「自動執行」切換鈕後,系統就不會顯示「執行查詢」按鈕。

11. (選用) 記錄中經過模糊處理的機密資訊

在步驟 10 中,我們記錄了應用程式與 Gemini 模型互動的相關資訊。這項資訊包括動物名稱、實際提示和模型的回應。雖然將這項資訊儲存在記錄檔中應該很安全,但許多其他情況並非如此。提示可能包含使用者不想儲存的個人或其他私密資訊。為解決這個問題,您可以模糊處理寫入 Cloud Logging 的機密資料。為盡量減少程式碼修改,建議採用下列解決方案。

  1. 建立 PubSub 主題,用來儲存傳入的記錄項目
  2. 建立記錄接收器,將擷取的記錄重新導向至 Pub/Sub 主題。
  3. 按照下列步驟建立 Dataflow 管道,修改重新導向至 PubSub 主題的記錄:
    1. 從 Pub/Sub 主題讀取記錄檔項目
    2. 使用 DLP 檢查 API 檢查項目酬載是否含有機密資訊
    3. 使用其中一種 DLP 遮蓋方法,遮蓋酬載中的機密資訊
    4. 將經過模糊處理的記錄項目寫入 Cloud Logging
  4. 部署管道

12. (選用) 清除

為避免因使用程式碼研究室的資源和 API 而產生費用,建議您在完成實驗室後進行清理。如要避免付費,最簡單的方法就是刪除您為了本程式碼研究室所建立的專案。

  1. 如要刪除專案,請在終端機中執行刪除專案指令:
    PROJECT_ID=$(gcloud config get-value project)
    gcloud projects delete ${PROJECT_ID} --quiet
    
    刪除 Cloud 專案後,系統就會停止對該專案使用的所有資源和 API 收取費用。您應該會看到以下訊息,其中 PROJECT_ID 是您的專案 ID:
    Deleted [https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID].
    
    You can undo this operation for a limited period by running the command below.
        $ gcloud projects undelete PROJECT_ID
    
    See https://cloud.google.com/resource-manager/docs/creating-managing-projects for information on shutting down projects.
    
  2. (選用) 如果收到錯誤訊息,請參閱步驟 5,找出您在實驗室中使用的專案 ID。並代入第一個指令。舉例來說,如果專案 ID 為 lab-example-project,指令會是:
    gcloud projects delete lab-project-id-example --quiet
    

13. 恭喜

在本實驗室中,您已建立生成式 AI 應用程式,並使用 Gemini 模型進行預測。並透過基礎的監控和記錄功能檢測應用程式。您已將應用程式和原始碼的變更內容部署至 Cloud Run。接著,您可以使用 Google Cloud Observability 產品追蹤應用程式效能,確保應用程式的可靠性。

如要參與使用者體驗研究,協助我們改善您今天使用的產品,請按這裡註冊

以下提供幾種繼續學習的方式: