About this codelab
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.
What you will learn
- 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
- Sign-in to the Google Cloud Console with your Google account.
- 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.
- 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.
- Confirm billing is enabled in My projects in Cloud Billing
- If your new project says
Billing is disabled
in theBilling account
column:- Click the three dots in the
Actions
column - Click Change billing
- Select the billing account you would like to use
- Click the three dots in the
- If you are attending a live event, the account will likely be named Google Cloud Platform Trial Billing Account
- If your new project says
4. Prepare Cloud Shell Editor
- 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.
- Open terminal window
- Click the hamburger menu
- Click Terminal
- Click New Terminal
- Click the hamburger menu
- In the terminal, configure your project ID:
Replacegcloud config set project [PROJECT_ID]
[PROJECT_ID]
with ID of your project. For example, if your project ID islab-example-project
, the command will be: If you are prompted with the following message, saying that gcloud requesting your credentials to GCPI API, click Authorize to continue.gcloud config set project lab-project-id-example
On successful execution you should see the following message: If you see aUpdated property [core/project].
WARNING
and are askedDo you want to continue (Y/N)?
, then you have likely entered the project ID incorrectly. PressN
, pressEnter
, and try to run thegcloud config set project
command again after you found the correct project ID. - (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.
- In the terminal, create the
codelab-o11y
directory:mkdir ~/codelab-o11y
- Change the current directory to
codelab-o11y
:cd ~/codelab-o11y
- 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 - Create a
main.py
file and open the file in Cloud Shell Editor: An empty file should now appear in the editor window above the terminal. Your screen will look similar to the following:cloudshell edit main.py
- Copy the following code and paste it into the opened
main.py
file: After a few seconds, Cloud Shell Editor will save your code automatically.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)))
Deploy the code of the Gen AI application to Cloud Run
- In the terminal window run the command to deploy the source code of the application to Cloud Run.
If you see the prompt like below, informing you that the command will create a new repository. Clickgcloud run deploy codelab-o11y-service \
--source="${HOME}/codelab-o11y/" \
--region=us-central1 \
--allow-unauthenticatedEnter
. The deployment process may take up to a few minutes. After the deployment process completes you will see output like: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
- 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:
When the URL is opened, you may get 500 error or see the message:gcloud run services list \
--format='value(URL)' \
--filter='SERVICE:"codelab-o11y-service"' 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.Sorry, this is just a placeholder...
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.
- Click on the button below to open the Audit Logs page in the Cloud console
- 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:
If necessary, select the correct project from the combobox. - 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. - In the info panel on the right, select the "Data Read" audit type.
- 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
- Click on the button below to open the Logs Explorer page in the Cloud console:
- Paste the following filter into the Query pane.
The Query pane is an editor located near the top of the Logs Explorer page:LOG_ID("cloudaudit.googleapis.com%2Fdata_access") AND
protoPayload.serviceName="aiplatform.googleapis.com" - Click Run query.
- 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.
- Return to the ‘Cloud Shell' window (or tab) in your browser.
- In the terminal, re-open
main.py
:cloudshell edit ~/codelab-o11y/main.py
- Make following modifications to the application's code:
- Find the last import statement. It should be line 5:
Place the cursor on the next line (line 6) and paste the following code block there.from vertexai.generative_models import GenerativeModel
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) - Find the code that calls the model to generate content. It should be line 30:
Place the cursor at the beginning of the NEXT line (line 31) and paste the following code block there.response = model.generate_content(prompt)
json_fields = {
'animal': animal,
'prompt': prompt,
'response': response.to_dict(),
}
logger.debug('content is generated', extra={'json_fields': json_fields})
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. - Find the last import statement. It should be line 5:
Deploy the code of the Gen AI application to Cloud Run
- In the terminal window run the command to deploy the source code of the application to Cloud Run.
If you see the prompt like below, informing you that the command will create a new repository. Clickgcloud run deploy codelab-o11y-service \
--source="${HOME}/codelab-o11y/" \
--region=us-central1 \
--allow-unauthenticatedEnter
. The deployment process may take up to a few minutes. After the deployment process completes you will see output like: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
- 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:
When the URL is opened, you may get 500 error or see the message:gcloud run services list \
--format='value(URL)' \
--filter='SERVICE:"codelab-o11y-service"' 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.Sorry, this is just a placeholder...
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:
- Click on the button below to open the Logs explorer page in the Cloud console:
- Paste the following filter into the Query pane (#2 in the Log explorer interface):
LOG_ID("run.googleapis.com%2Fstdout") AND
severity=DEBUG - 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.
- 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:
- In the opened menu select the Create metric to open the Create log-based metric panel.
- Follow these steps to configure a new counter metric in the Create log-based metric panel:
- Set the Metric type: Select Counter.
- 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
.
- Log metric name: Set the name to
- Leave the values in the Filter selection section. Note that the Build filter field has the same filter we used to see application logs.
- (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:
- Click Add label.
- 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.
- Label name: Set the name to
- Click Done
- 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:
- Click on the button below to open the Metrics explorer page in the Cloud console:
- 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.
- Verify that PromQL is selected in the Language toggle. The language toggle is in the same toolbar that lets you format your query.
- Enter your query into the Queries editor:
For more information about using PromQL, see PromQL in Cloud Monitoring.sum(rate(logging_googleapis_com:user_model_interaction_count{monitored_resource="cloud_run_revision"}[${__interval}]))
- Click Run Query. You will see a line chart similar to this screenshot:
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
- Return to the ‘Cloud Shell' window (or tab) in your browser.
- 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 - Create a new file
setup_opentelemetry.py
: An empty file should now appear in the editor window above the terminal.cloudshell edit ~/codelab-o11y/setup_opentelemetry.py
- Copy the following code and paste it into the opened
setup_opentelemetry.py
file: After a few seconds, Cloud Shell Editor will save your code automatically.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)}'
Instrument application code with tracing and monitoring capabilities using OTel
- In the terminal, re-open
main.py
:cloudshell edit ~/codelab-o11y/main.py
- Make the following modifications to the application's code:
- 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 - After declaration of the
format()
method (line 9) insert the following code (mind indentation):span = trace.get_current_span()
- After the line 13 (containing
"message": record.getMessage()
) insert the following code (mind indentation): These two additional attributes helps to correlate application logs and OTel tracing spans."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), - After the line
app = Flask(__name__)
(line 31) insert the following code: These line instrument all incoming and outgoing requests of our flask application with tracing.FlaskInstrumentor().instrument_app(app)
RequestsInstrumentor().instrument() - Right after the new added code (after line 33) add the following code:
These lines create a new metric of type counter with the namemeter = metrics.get_meter(__name__)
requests_counter = meter.create_counter(
name="model_call_counter",
description="number of model invocations",
unit="1"
)model_call_counter
and register it for export. - After the call to
logger.debug()
(line 49) insert the following code: This change will increment the counter by 1 each time the application successfully calls Vertex API to interact with the Gemini model.requests_counter.add(1, {'animal': animal})
- Before the line
Deploy the code of the Gen AI application to Cloud Run
- In the terminal window run the command to deploy the source code of the application to Cloud Run.
If you see the prompt like below, informing you that the command will create a new repository. Clickgcloud run deploy codelab-o11y-service \
--source="${HOME}/codelab-o11y/" \
--region=us-central1 \
--allow-unauthenticatedEnter
. The deployment process may take up to a few minutes. After the deployment process completes you will see output like: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
- 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:
When the URL is opened, you may get 500 error or see the message:gcloud run services list \
--format='value(URL)' \
--filter='SERVICE:"codelab-o11y-service"' 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.Sorry, this is just a placeholder...
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
- Click on the button below to open the Trace explorer page in the Cloud console:
- Select one of the most recent traces. You are supposed to see 5 or 6 spans that look like in the screenshot below.
- Find the span that traces the call to the event handler (the
fun_facts
method). It will be the last span with the name/
. - 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
- Click on the button below to open the Metrics explorer page in the Cloud console:
- 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.
- Verify that PromQL is selected in the Language toggle. The language toggle is in the same toolbar that lets you format your query.
- Enter your query into the Queries editor:
sum(rate(workload_googleapis_com:model_call_counter{monitored_resource="generic_task"}[${__interval}]))
- 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.
- Create a PubSub topic to store incoming log entries
- Create a log sink that redirects ingested logs to PubSub topic.
- Create a Dataflow pipeline that modifies logs redirected to PubSub topic following these steps:
- Read a log entry from the PubSub topic
- Inspect the entry's payload for sensitive information using DLP inspection API
- Redact the sensitive information in the payload using one of the DLP redaction methods
- Write the obfuscated log entry to Cloud Logging
- 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.
- To delete the project run the delete project command in the terminal:
Deleting your Cloud project stops billing for all the resources and APIs used within that project. You should see this message wherePROJECT_ID=$(gcloud config get-value project)
gcloud projects delete ${PROJECT_ID} --quietPROJECT_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.
- (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:
- Codelab How to deploy gemini powered chat app on Cloud Run
- Codelab How to use Gemini function calling with Cloud Run
- How to use Cloud Run Jobs Video Intelligence API to process a Video scene-by-scene
- On-demand workshop Google Kubernetes Engine Onboard
- Learn more about configuring counter and distribution metrics using application logs
- Write OTLP metrics by using an OpenTelemetry sidecar
- Reference to use of Open Telemetry in Google Cloud