适用于 JavaScript 中生成式 AI 应用的实用可观测性技术

1. 概览

生成式 AI 应用与其他应用一样,需要可观测性。生成式 AI 是否需要特殊的观测技术?

在本实验中,您将创建一个简单的生成式 AI 应用。将其部署到 Cloud Run。并使用 Google Cloud 可观测性服务和产品为其配备必要的监控和日志记录功能。

学习内容

  • 使用 Cloud Shell 编辑器 编写一个使用 Vertex AI 的应用
  • 在 GitHub 中存储应用代码
  • 使用 gcloud CLI 将应用的源代码部署到 Cloud Run
  • 为生成式 AI 应用添加监控和日志记录功能
  • 使用基于日志的指标
  • 使用 Open Telemetry SDK 实现日志记录和监控
  • 深入了解 Responsible AI 数据处理

2. 前提条件

如果您还没有 Google 账号,则必须创建一个新账号

3. 项目设置

  1. 使用您的 Google 账号登录 Google Cloud 控制台
  2. 创建新项目或选择重复使用现有项目。记下您刚刚创建或选择的项目的项目 ID。
  3. 为项目启用结算功能
    • 完成本实验的结算费用应低于 5 美元。
    • 您可以按照本实验末尾的步骤删除资源,以避免产生更多费用。
    • 新用户符合参与 $300 USD 免费试用计划的条件。
  4. 确认 Cloud Billing 中的我的项目已启用结算功能
    • 如果新项目的 Billing account 列中显示 Billing is disabled,请执行以下操作:
      1. 点击 Actions 列中的三点状图标
      2. 点击更改结算信息
      3. 选择您要使用的结算账号
    • 如果您参加的是现场活动,则该账号的名称很可能是 Google Cloud Platform 试用结算账号

4. 准备 Cloud Shell 编辑器

  1. 前往 Cloud Shell 编辑器。如果系统提示以下消息,要求您授权 Cloud Shell 使用您的凭据调用 gcloud,请点击授权继续。
    点击以授权 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,请点击授权以继续。
    点击以授权 Cloud Shell
    成功执行后,您应该会看到以下消息:
    Updated property [core/project].
    
    如果您看到 WARNING 并被问到 Do you want to continue (Y/N)?,则很可能是您输入的项目 ID 有误。按 N,按 Enter,然后在找到正确的项目 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 NodeJS 应用

在此步骤中,您将编写一个简单的基于请求的应用的代码,该应用使用 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 Editor 中打开该文件:
    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 控制台中打开 Logs Explorer 页面:

  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 结构。该日志会捕获请求的 animal 参数以及模型的提示和回答。

几秒钟后,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. 查看我们在上一步中使用的 Logs Explorer 窗口。在“查询”窗格下,找到操作下拉菜单,然后点击该菜单以将其打开。请参见下面的屏幕截图,找到相应菜单:
    包含“操作”下拉菜单的查询结果工具栏
  2. 在打开的菜单中,选择创建指标以打开创建基于日志的指标面板。
  3. 请按照以下步骤在创建基于日志的指标面板中配置新的计数器指标:
    1. 设置指标类型:选择计数器
    2. 详细信息部分中设置以下字段:
      • 日志指标名称:将名称设置为 model_interaction_count。您需遵循一些命名限制;如需了解详情,请参阅问题排查中的命名限制。
      • 说明:输入此指标的说明。例如 Number of log entries capturing successful call to model inference.
      • 单位:可将此字段留空或者插入数字 1
    3. 保留过滤器选择部分中的值。请注意,构建过滤条件字段中包含我们用于查看应用日志的相同过滤条件。
    4. (可选)添加一个有助于统计每种动物叫声次数的标签。注意:此标签可能会大幅增加指标的基数,不建议在生产环境中使用:
      1. 点击添加标签
      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. 点击运行查询。您会看到类似于此屏幕截图的折线图:
    显示查询的指标

    请注意,启用自动运行切换开关后,系统不会显示运行查询按钮。

10. (可选)使用 Open Telemetry 进行监控和跟踪

如上一步中所述,可以使用 OpenTelemetry (Otel) SDK 实现指标。建议在微服务架构中使用 OTel。此步骤介绍了以下内容:

  • 初始化 OTel 组件以支持应用的跟踪和监控
  • 使用 Cloud Run 环境的资源元数据填充 OTel 配置
  • 使用自动跟踪功能对 Flask 应用进行插桩
  • 实现计数器指标以监控成功模型调用的次数
  • 将跟踪记录与应用日志相关联

对于产品级服务,建议的架构是使用 OTel 收集器来收集和提取一项或多项服务的所有可观测性数据。为简单起见,此步骤中的代码未使用收集器。而是使用直接将数据写入 Google Cloud 的 OTel 导出器。

设置 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 探索器中的应用 span 视图
  3. 找到跟踪对事件处理脚本(即 fun_facts 方法)的调用的 span。它将是名称为 / 的最后一个 span。
  4. 轨迹详情窗格中,选择日志和事件。您将看到与此特定 span 相关联的应用日志。系统会使用跟踪记录和日志中的跟踪记录 ID 和 span 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. 创建 Pub/Sub 主题以存储传入的日志条目
  2. 创建将注入的日志重定向到 PubSub 主题的日志接收器
  3. 创建一个 Dataflow 流水线,用于修改重定向到 PubSub 主题的日志,具体步骤如下:
    1. 从 Pub/Sub 主题读取日志条目
    2. 使用 DLP 检查 API 检查条目的载荷中是否包含敏感信息
    3. 使用 DLP 隐去方法之一隐去载荷中的敏感信息
    4. 将混淆处理后的日志条目写入 Cloud Logging
  4. 部署流水线。

12. (可选)清理

为避免因 Codelab 中使用的资源和 API 而产生费用,建议您在完成实验后进行清理。若要避免产生费用,最简单的方法是删除您为本 Codelab 创建的项目。

  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. 恭喜

在本实验中,您创建了一个使用 Gemini 模型进行预测的生成式 AI 应用。并为应用添加了必要的监控和日志记录功能。您已将应用和源代码中的更改部署到 Cloud Run。然后,您可以使用 Google Cloud Observability 产品来跟踪应用的性能,从而确保应用的可靠性。

如果您有兴趣参与用户体验 (UX) 调研,帮助我们改进您今天使用的产品,请在此处注册

以下是一些可供您继续学习的选项: