Practical observability techniques for Generative AI application in Python

Practical observability techniques for Generative AI application in Python

About this codelab

subjectLast updated Oct 22, 2024
account_circleWritten by Leonid Yankulin

1. Overview

Gen AI applications require observability like any other. Are there special observability techniques require for Generative AI?

In this lab, you will create a simple Gen AI application. Deploy it to Cloud Run. And instrument it with essential monitoring and logging capabilities using Google Cloud observability services and products.

  • Write an application that uses Vertex AI with Cloud Shell Editor
  • Store your application code in GitHub
  • Use gcloud CLI to deploy your application's source code to Cloud Run
  • Add monitoring and logging capabilities to your Gen AI application
  • Using log-based metrics
  • Implementing logging and monitoring with Open Telemetry SDK
  • Gain insights into responsible AI data handling

2. Prerequisites

If you do not already have a Google account, you have to create a new account.

3. Project setup

  1. Sign-in to the Google Cloud Console with your Google account.
  2. Create a new project or choose to reuse an existing project. Write down the project ID of the project that you just created or selected.
  3. Enable billing for the project.
    • Completing this lab should cost less than $5 in billing costs.
    • You can follow the steps at the end of this lab to delete resources to avoid further charges.
    • New users are eligible for the $300 USD Free Trial.
  4. Confirm billing is enabled in My projects in Cloud Billing
    • If your new project says Billing is disabled in the Billing account column:
      1. Click the three dots in the Actions column
      2. Click Change billing
      3. Select the billing account you would like to use
    • If you are attending a live event, the account will likely be named Google Cloud Platform Trial Billing Account

4. Prepare Cloud Shell Editor

  1. Navigate to Cloud Shell Editor. If you are prompted with the following message, requesting to authorize cloud shell to call gcloud with your credentials, click Authorize to continue.
    Click to authorize Cloud Shell
  2. Open terminal window
    1. Click the hamburger menu Hamburger menu icon
    2. Click Terminal
    3. Click New Terminal
      Open new terminal in Cloud Shell Editor
  3. In the terminal, configure your project ID:
    gcloud config set project [PROJECT_ID]
    Replace [PROJECT_ID] with ID of your project. For example, if your project ID is lab-example-project, the command will be:
    gcloud config set project lab-project-id-example
    
    If you are prompted with the following message, saying that gcloud requesting your credentials to GCPI API, click Authorize to continue.
    Click to authorize Cloud Shell
    On successful execution you should see the following message:
    Updated property [core/project].
    
    If you see a WARNING and are asked Do you want to continue (Y/N)?, then you have likely entered the project ID incorrectly. Press N, press Enter, and try to run the gcloud config set project command again after you found the correct project ID.
  4. (Optional) If you are having a problem to find the project ID, run the following command to see project ID of all your projects sorted by creation time in descending order:
    gcloud projects list \
         
    --format='value(projectId,createTime)' \
         
    --sort-by=~createTime

5. Enable Google APIs

In the terminal, enable Google APIs that are required for this lab:

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

This command will take some time to complete. Eventually, it produce a successful message similar to this one:

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

If you receive an error message starting with ERROR: (gcloud.services.enable) HttpError accessing and containing error details like below, retry the command after a 1-2 minute delay.

"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. Create a Gen AI Python application

In this step you will write a code of the simple request-based application that uses Gemini model to show 10 fun facts about an animal of your choice. Do the follow to create the application code.

  1. In the terminal, create the codelab-o11y directory:
    mkdir ~/codelab-o11y
  2. Change the current directory to codelab-o11y:
    cd ~/codelab-o11y
  3. Create the requirements.txt with the list of dependencies:
    cat > requirements.txt << EOF
    Flask==3.0.0
    gunicorn==23.0.0
    google-cloud-aiplatform==1.59.0
    google-auth==2.32.0
    EOF
  4. Create a main.py file and open the file in Cloud Shell Editor:
    cloudshell edit main.py
    An empty file should now appear in the editor window above the terminal. Your screen will look similar to the following:
    Show Cloud Shell Editor after starting editing main.py
  5. Copy the following code and paste it into the opened main.py file:
    import os
    from flask import Flask, request
    import google.auth
    import vertexai
    from vertexai.generative_models import GenerativeModel

    _, project = google.auth.default()
    app = Flask(__name__)

    @app.route('/')
    def fun_facts():
       
    vertexai.init(project=project, location='us-central1')
       
    model = GenerativeModel('gemini-1.5-flash')
       
    animal = request.args.get('animal', 'dog')
       
    prompt = f'Give me 10 fun facts about {animal}. Return this as html without backticks.'
       
    response = model.generate_content(prompt)
       
    return response.text

    if __name__ == '__main__':
       
    app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
    After a few seconds, Cloud Shell Editor will save your code automatically.

Deploy the code of the Gen AI application to Cloud Run

  1. In the terminal window run the command to deploy the source code of the application to Cloud Run.
    gcloud run deploy codelab-o11y-service \
         
    --source="${HOME}/codelab-o11y/" \
         
    --region=us-central1 \
         
    --allow-unauthenticated
    If you see the prompt like below, informing you that the command will create a new repository. Click 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)?
    
    The deployment process may take up to a few minutes. After the deployment process completes you will see output like:
    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. Copy the displayed Cloud Run service URL to a separate tab or window in your browser. Alternatively, run the following command in the terminal to print the service URL and click on the shown URL while holding Ctrl key to open the URL:
    gcloud run services list \
         
    --format='value(URL)' \
         
    --filter='SERVICE:"codelab-o11y-service"'
    When the URL is opened, you may get 500 error or see the message:
    Sorry, this is just a placeholder...
    
    It means that the services did not finish its deployment. Wait a few moments and refresh the page. At the end you will see a text starting with Fun Dog Facts and containing 10 fun facts about dogs.

Try to interact with the application to get fun facts about different animals. To do it append the animal parameter to the URL, like ?animal=[ANIMAL] where [ANIMAL] is an animal name. For example, append ?animal=cat to get 10 fun facts about cats or ?animal=sea turtle to get 10 fun facts about sea turtles.

7. Audit your Vertex API calls

Auditing Google API calls provides answers to the questions like "Who call a particular API, where, and when?". Auditing is important when you troubleshoot your application, investigate resource consumption or perform software forensic analysis.

Audit logs allow you to track administrative and system activities as well as to log calls to "data read" and "data write" API operations. To audit Vertex AI requests to generate content you have to enable "Data Read" audit logs in the Cloud console.

  1. Click on the button below to open the Audit Logs page in the Cloud console

  2. Ensure that the page has the project that you created for this lab selected. The selected project is shown at the top left corner of the page right from the hamburger menu:
    Google Cloud Console project dropdown
    If necessary, select the correct project from the combobox.
  3. In the Data Access audit logs configuration table, in the Service column find the Vertex AI API service and select the service by selecting the checkbox located to the left from the service name.
    Select Vertex AI API
  4. In the info panel on the right, select the "Data Read" audit type.
    Check Data Read logs
  5. Click Save.

To generate audit logs open the service URL. Refresh the page while changing the value of the ?animal= parameter to get different results.

Explore audit logs

  1. Click on the button below to open the Logs Explorer page in the Cloud console:

  2. Paste the following filter into the Query pane.
    LOG_ID("cloudaudit.googleapis.com%2Fdata_access") AND
    protoPayload.serviceName="aiplatform.googleapis.com"
    The Query pane is an editor located near the top of the Logs Explorer page:
    Query audit logs
  3. Click Run query.
  4. Select one of the audit log entries and expands the fields to inspect information captured in the log.
    You can see details about Vertex API call including the method and the model that was used. You also can see the identity of the invoker and what permissions authorized the call.

8. Log interactions with Gen AI

You do not find API request parameters or response data in audit logs. However, this information can be important for troubleshooting application and workflow analysis. In this step we fulfill this gap by adding application logging. The logging uses classic Python's logging package. While in your production environment you may use different logging framework the principles are the same.

The Python's logging package does not know to write logs to Google Cloud. It supports writing to standard output (stderr by default) or to a file. However, Cloud Run features capturing information printed to standard output and ingesting it to Cloud Logging automatically. Follow the instructions below to add logging capabilities to our Gen AI application.

  1. Return to the ‘Cloud Shell' window (or tab) in your browser.
  2. In the terminal, re-open main.py:
    cloudshell edit ~/codelab-o11y/main.py
  3. Make following modifications to the application's code:
    1. Find the last import statement. It should be line 5:
      from vertexai.generative_models import GenerativeModel
      
      Place the cursor on the next line (line 6) and paste the following code block there.
      import sys, json, logging
      class JsonFormatter(logging.Formatter):
         
      def format(self, record):
             
      json_log_object = {
                 
      'severity': record.levelname,
                 
      'message': record.getMessage(),
             
      }
             
      json_log_object.update(getattr(record, 'json_fields', {}))
             
      return json.dumps(json_log_object)
      logger = logging.getLogger(__name__)
      sh = logging.StreamHandler(sys.stdout)
      sh.setFormatter(JsonFormatter())
      logger.addHandler(sh)
      logger.setLevel(logging.DEBUG)

    2. Find the code that calls the model to generate content. It should be line 30:
      response = model.generate_content(prompt)
      
      Place the cursor at the beginning of the NEXT line (line 31) and paste the following code block there.
          json_fields = {
               
      'animal': animal,
               
      'prompt': prompt,
               
      'response': response.to_dict(),
         
      }
         
      logger.debug('content is generated', extra={'json_fields': json_fields})

    These changes configure Python standard logging to use a custom formatter to generate stringified JSON that follows structured formatting guidelines. The logging is configured to print logs to stdout where it is collected by Cloud Run logging agent and asynchronously ingests to Cloud Logging. The logs capture the animal parameter of the request and the model's prompt and response.After a few seconds, Cloud Shell Editor saves your changes automatically.

Deploy the code of the Gen AI application to Cloud Run

  1. In the terminal window run the command to deploy the source code of the application to Cloud Run.
    gcloud run deploy codelab-o11y-service \
         
    --source="${HOME}/codelab-o11y/" \
         
    --region=us-central1 \
         
    --allow-unauthenticated
    If you see the prompt like below, informing you that the command will create a new repository. Click 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)?
    
    The deployment process may take up to a few minutes. After the deployment process completes you will see output like:
    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. Copy the displayed Cloud Run service URL to a separate tab or window in your browser. Alternatively, run the following command in the terminal to print the service URL and click on the shown URL while holding Ctrl key to open the URL:
    gcloud run services list \
         
    --format='value(URL)' \
         
    --filter='SERVICE:"codelab-o11y-service"'
    When the URL is opened, you may get 500 error or see the message:
    Sorry, this is just a placeholder...
    
    It means that the services did not finish its deployment. Wait a few moments and refresh the page. At the end you will see a text starting with Fun Dog Facts and containing 10 fun facts about dogs.

To generate application logs open the service URL. Refresh the page while changing the value of the ?animal= parameter to get different results.
To see the application logs do the following:

  1. Click on the button below to open the Logs explorer page in the Cloud console:

  2. Paste the following filter into the Query pane (#2 in the Log explorer interface):
    LOG_ID("run.googleapis.com%2Fstdout") AND
    severity=DEBUG
  3. Click Run query.

The result of the query shows logs with prompt and Vertex AI response including safety ratings.

9. Count interactions with Gen AI

Cloud Run writes managed metrics that can be used to monitor deployed services. User-managed monitoring metrics provide more control over data and frequency of the metric update. To implement such metric requires writing a code that collects data and writes it to Cloud Monitoring. See the next (optional) step for the way to implement it using OpenTelemetry SDK.

This step shows alternative to implementing user metric in the code - log-based metrics. Log-based metrics let you generate monitoring metrics from the log entries that your application write to Cloud Logging. We will use the application logs that we implemented in the previous step to define a log-based metric of the type counter. The metric will count the number of successful calls to Vertex API.

  1. Look at the window of the Logs explorer that we used in the previous step. Under the Query pane locate the Actions drop-down menu and click it to open. See the screenshot below to find the menu:
    Query results toolbar with Actions drop-down menu
  2. In the opened menu select the Create metric to open the Create log-based metric panel.
  3. Follow these steps to configure a new counter metric in the Create log-based metric panel:
    1. Set the Metric type: Select Counter.
    2. Set the following fields in the Details section:
      • Log metric name: Set the name to model_interaction_count. Some naming restrictions apply; See naming restrictions Troubleshooting for details.
      • Description: Enter a description for the metric. For example, Number of log entries capturing successful call to model inference.
      • Units: Leave this blank or insert the digit 1.
    3. Leave the values in the Filter selection section. Note that the Build filter field has the same filter we used to see application logs.
    4. (Optional) Add a label that helps to count a number of calls for each animal. NOTE: this label has potential to greatly increase metric's cardinality and is not recommended for use in production:
      1. Click Add label.
      2. Set the following fields in the Labels section:
        • Label name: Set the name to animal.
        • Description: Enter the description of the label. For example, Animal parameter.
        • Label type: Select STRING.
        • Field name: Type jsonPayload.animal.
        • Regular expression: Leave it empty.
      3. Click Done
    5. Click Create metric to create the metric.

You can also create a log-based metric from the Log-based metrics page, using gcloud logging metrics create CLI command or with google_logging_metric Terraform resource.

To generate metric data open the service URL. Refresh the opened page several times to make multiple calls to the model. Like before, try to use different animals in the parameter.

Enter the PromQL query to search for the log-based metric data. To enter a PromQL query, do the following:

  1. Click on the button below to open the Metrics explorer page in the Cloud console:

  2. In the toolbar of the query-builder pane, select the button whose name is either < > MQL or < > PromQL. See the picture below for the button's location.
    Location of MQL button in Metrics explorer
  3. Verify that PromQL is selected in the Language toggle. The language toggle is in the same toolbar that lets you format your query.
  4. Enter your query into the Queries editor:
    sum(rate(logging_googleapis_com:user_model_interaction_count{monitored_resource="cloud_run_revision"}[${__interval}]))
    For more information about using PromQL, see PromQL in Cloud Monitoring.
  5. Click Run Query. You will see a line chart similar to this screenshot:
    Show queried metrics

    Note that when the Auto-run toggle is enabled, the Run Query button isn't shown.

10. (Optional) Use Open Telemetry for monitoring and tracing

As mentioned in the previous step it is possible to implement metrics using OpenTelemetry (Otel) SDK. Using OTel on micro-service architectures is a recommended practice. This step describes the following:

  • Initializing OTel components to support tracing and monitoring of the application
  • Populating OTel configuration with resource metadata of the Cloud Run environment
  • Instrumenting flask application with automatic tracing capabilities
  • Implementing a counter metric to monitor a number of successful model calls
  • Correlate tracing with application logs

The recommended architecture for product-level services is to use OTel collector to collect and ingest all observability data for one or more services. The code in this step does not use the collector for simplicity sake. Instead it uses OTel exports that write data directly to Google Cloud.

Setup OTel components for tracing and metric monitoring

  1. Return to the ‘Cloud Shell' window (or tab) in your browser.
  2. In the terminal, update the requirements.txt with additional list of dependencies:
    cat >> ~/codelab-o11y/requirements.txt << EOF
    opentelemetry-api==1.24.0
    opentelemetry-sdk==1.24.0
    opentelemetry-exporter-otlp-proto-http==1.24.0
    opentelemetry-instrumentation-flask==0.45b0
    opentelemetry-instrumentation-requests==0.45b0
    opentelemetry-exporter-gcp-trace==1.7.0
    opentelemetry-exporter-gcp-monitoring==1.7.0a0  
    EOF
  3. Create a new file setup_opentelemetry.py:
    cloudshell edit ~/codelab-o11y/setup_opentelemetry.py
    An empty file should now appear in the editor window above the terminal.
  4. Copy the following code and paste it into the opened setup_opentelemetry.py file:
    import os

    from opentelemetry import metrics
    from opentelemetry import trace
    from opentelemetry.exporter.cloud_monitoring import CloudMonitoringMetricsExporter
    from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
    from opentelemetry.resourcedetector.gcp_resource_detector import GoogleCloudResourceDetector
    from opentelemetry.sdk.metrics import MeterProvider
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
    from opentelemetry.sdk.resources import get_aggregated_resources, Resource, CLOUD_ACCOUNT_ID, SERVICE_NAME
    from opentelemetry.sdk.trace.export import BatchSpanProcessor

    resource = get_aggregated_resources(
       
    [GoogleCloudResourceDetector(raise_on_error=True)]
    )
    resource = resource.merge(Resource.create(attributes={
       
    SERVICE_NAME: os.getenv("K_SERVICE"),
    }))

    meter_provider = MeterProvider(
       
    resource=resource,
       
    metric_readers=[
           
    PeriodicExportingMetricReader(
               
    CloudMonitoringMetricsExporter(), export_interval_millis=5000
           
    )
       
    ],
    )
    metrics.set_meter_provider(meter_provider)
    meter = metrics.get_meter(__name__)

    trace_provider = TracerProvider(resource=resource)
    processor = BatchSpanProcessor(CloudTraceSpanExporter(
       
    # send all resource attributes
       
    resource_regex=r".*"
    ))
    trace_provider.add_span_processor(processor)
    trace.set_tracer_provider(trace_provider)

    def google_trace_id_format(trace_id: int) -> str:
       
    project_id = resource.attributes[CLOUD_ACCOUNT_ID]
       
    return f'projects/{project_id}/traces/{trace.format_trace_id(trace_id)}'
    After a few seconds, Cloud Shell Editor will save your code automatically.

Instrument application code with tracing and monitoring capabilities using OTel

  1. In the terminal, re-open main.py:
    cloudshell edit ~/codelab-o11y/main.py
  2. Make the following modifications to the application's code:
    1. Before the line import os (line 1) insert the following code (mind the empty line at the end):
      from setup_opentelemetry import google_trace_id_format
      from opentelemetry import metrics, trace
      from opentelemetry.instrumentation.requests import RequestsInstrumentor
      from opentelemetry.instrumentation.flask import FlaskInstrumentor

    2. After declaration of the format() method (line 9) insert the following code (mind indentation):
              span = trace.get_current_span()
    3. After the line 13 (containing "message": record.getMessage()) insert the following code (mind indentation):
                  "logging.googleapis.com/trace": google_trace_id_format(span.get_span_context().trace_id),
                 
      "logging.googleapis.com/spanId": trace.format_span_id(span.get_span_context().span_id),
      These two additional attributes helps to correlate application logs and OTel tracing spans.
    4. After the line app = Flask(__name__) (line 31) insert the following code:
      FlaskInstrumentor().instrument_app(app)
      RequestsInstrumentor().instrument()
      These line instrument all incoming and outgoing requests of our flask application with tracing.
    5. Right after the new added code (after line 33) add the following code:
      meter = metrics.get_meter(__name__)
      requests_counter = meter.create_counter(
         
      name="model_call_counter",
         
      description="number of model invocations",
         
      unit="1"
      )
      These lines create a new metric of type counter with the name model_call_counter and register it for export.
    6. After the call to logger.debug() (line 49) insert the following code:
          requests_counter.add(1, {'animal': animal})
      This change will increment the counter by 1 each time the application successfully calls Vertex API to interact with the Gemini model.

Deploy the code of the Gen AI application to Cloud Run

  1. In the terminal window run the command to deploy the source code of the application to Cloud Run.
    gcloud run deploy codelab-o11y-service \
         
    --source="${HOME}/codelab-o11y/" \
         
    --region=us-central1 \
         
    --allow-unauthenticated
    If you see the prompt like below, informing you that the command will create a new repository. Click 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)?
    
    The deployment process may take up to a few minutes. After the deployment process completes you will see output like:
    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. Copy the displayed Cloud Run service URL to a separate tab or window in your browser. Alternatively, run the following command in the terminal to print the service URL and click on the shown URL while holding Ctrl key to open the URL:
    gcloud run services list \
         
    --format='value(URL)' \
         
    --filter='SERVICE:"codelab-o11y-service"'
    When the URL is opened, you may get 500 error or see the message:
    Sorry, this is just a placeholder...
    
    It means that the services did not finish its deployment. Wait a few moments and refresh the page. At the end you will see a text starting with Fun Dog Facts and containing 10 fun facts about dogs.

To generate telemetry data open the service URL. Refresh the page while changing the value of the ?animal= parameter to get different results.

Explore application traces

  1. Click on the button below to open the Trace explorer page in the Cloud console:

  2. Select one of the most recent traces. You are supposed to see 5 or 6 spans that look like in the screenshot below.
    View of the app span in Trace explorer
  3. Find the span that traces the call to the event handler (the fun_facts method). It will be the last span with the name /.
  4. In the Trace details pane select Logs & events. You will see application logs that correlate to this particular span. The correlation is detected using the trace and span IDs in the trace and in the log. You are supposed to see the application log that wrote the prompt and the response of the Vertex API.

Explore the counter metric

  1. Click on the button below to open the Metrics explorer page in the Cloud console:

  2. In the toolbar of the query-builder pane, select the button whose name is either < > MQL or < > PromQL. See the picture below for the button's location.
    Location of MQL button in Metrics explorer
  3. Verify that PromQL is selected in the Language toggle. The language toggle is in the same toolbar that lets you format your query.
  4. Enter your query into the Queries editor:
    sum(rate(workload_googleapis_com:model_call_counter{monitored_resource="generic_task"}[${__interval}]))
  5. Click Run Query.When the Auto-run toggle is enabled, the Run Query button isn't shown.

11. (Optional) Obfuscated sensitive information from logs

In Step 10 we logged information about the application's interaction with the Gemini model. This information included the name of the animal, the actual prompt and the model's response. While storing this information in the log should be safe, it is not necessary true for many other scenarios. The prompt may include some personal or otherwise sensitive information that a user does not want to be stored. To address this you can obfuscated the sensitive data that is written to Cloud Logging. To minimize code modifications the following solution is recommended.

  1. Create a PubSub topic to store incoming log entries
  2. Create a log sink that redirects ingested logs to PubSub topic.
  3. Create a Dataflow pipeline that modifies logs redirected to PubSub topic following these steps:
    1. Read a log entry from the PubSub topic
    2. Inspect the entry's payload for sensitive information using DLP inspection API
    3. Redact the sensitive information in the payload using one of the DLP redaction methods
    4. Write the obfuscated log entry to Cloud Logging
  4. Deploy the pipeline

12. (Optional) Clean up

To avoid a risk of incurring charges for resources and APIs used in the codelab it is recommended to clean up after you finished the lab. The easiest way to eliminate billing is to delete the project that you created for the codelab.

  1. To delete the project run the delete project command in the terminal:
    PROJECT_ID=$(gcloud config get-value project)
    gcloud projects delete ${PROJECT_ID} --quiet
    Deleting your Cloud project stops billing for all the resources and APIs used within that project. You should see this message where PROJECT_ID will be your project 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. (Optional) If you receive an error, consult with Step 5 to find the project ID you used during the lab. Substitute it to the command in the first instruction. For example, if your project ID is lab-example-project, the command will be:
    gcloud projects delete lab-project-id-example --quiet

13. Congratulations

In this lab, you created a Gen AI application that uses Gemini model to make predictions. And instrumented the application with essential monitoring and logging capabilities. You deployed the application and changes from the source code to Cloud Run. Then you Google Cloud Observability products to track the application's performance, so you can be ensure in the application's reliability.

If you are interested in being included in a user experience (UX) research study to improve the products you worked with today, register here.

Here are some options for continuing your learning: