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 Go 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
- Initialize Go modules:
go mod init codelab
- Install the Vertex AI SDK for Go:
go get cloud.google.com/go/vertexai/genai
- Install the Metadata library for Go to get the current project ID:
go get cloud.google.com/go/compute/metadata
- Create a
setup.go
file and open the file in Cloud Shell Editor: It will be used to host initialization code. A new empty file with the namecloudshell edit setup.go
setup.go
will appear in the editor window. - Copy the following code and paste it into the opened
setup.go
file:package main
import (
"context"
"os"
"cloud.google.com/go/compute/metadata"
)
func projectID(ctx context.Context) (string, error) {
var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
return metadata.ProjectIDWithContext(ctx)
}
return projectID, nil
} - Return to the terminal window and run the following command to create and open a
main.go
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.go
- Copy the following code and paste it into the opened
main.go
file: After a few seconds, Cloud Shell Editor will save your code automatically.package main
import (
"context"
"fmt"
"net/http"
"os"
"cloud.google.com/go/vertexai/genai"
)
var model *genai.GenerativeModel
func main() {
ctx := context.Background()
projectID, err := projectID(ctx)
if err != nil {
return
}
var client *genai.Client
client, err = genai.NewClient(ctx, projectID, "us-central1")
if err != nil {
return
}
defer client.Close()
model = client.GenerativeModel("gemini-1.5-flash-001")
http.HandleFunc("/", Handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
if err := http.ListenAndServe(":"+port, nil); err != nil {
return
}
}
func Handler(w http.ResponseWriter, r *http.Request) {
animal := r.URL.Query().Get("animal")
if animal == "" {
animal = "dog"
}
prompt := fmt.Sprintf("Give me 10 fun facts about %s. Return the results as HTML without markdown backticks.", animal)
resp, err := model.GenerateContent(r.Context(), genai.Text(prompt))
if err != nil {
w.WriteHeader(http.StatusTooManyRequests)
return
}
if len(resp.Candidates) > 0 && len(resp.Candidates[0].Content.Parts) > 0 {
htmlContent := resp.Candidates[0].Content.Parts[0]
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, htmlContent)
}
}
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 the standard Go log/slog
package for writing structured logs. The log/slog
package does not know to write logs to Google Cloud. It supports writing to standard output. However, Cloud Run features capturing information printed to standard output and ingesting it to Cloud Logging automatically. In order to correctly capture the structured logs, the printed log should be formatted accordingly. Follow the instructions below to add structured logging capabilities to our Go application.
- Return to the ‘Cloud Shell' window (or tab) in your browser.
- In the terminal, re-open
setup.go
:cloudshell edit ~/codelab-o11y/setup.go
- Replace the code with the version that sets up logging. To replace the code, delete the content of the file and then copy the code below and paste it into the editor:
package main
import (
"context"
"os"
"log/slog"
"cloud.google.com/go/compute/metadata"
)
func projectID(ctx context.Context) (string, error) {
var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
return metadata.ProjectIDWithContext(ctx)
}
return projectID, nil
}
func setupLogging() {
opts := &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(group []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.LevelKey:
a.Key = "severity"
if level := a.Value.Any().(slog.Level); level == slog.LevelWarn {
a.Value = slog.StringValue("WARNING")
}
case slog.MessageKey:
a.Key = "message"
case slog.TimeKey:
a.Key = "timestamp"
}
return a
},
}
jsonHandler := slog.NewJSONHandler(os.Stdout, opts)
slog.SetDefault(slog.New(jsonHandler))
} - Return to the terminal, and re-open
main.go
:cloudshell edit ~/codelab-o11y/main.go
- Replace the application code with the version that logs interaction with the model. To replace the code, delete the content of the file and then copy the code below and paste it into the editor:
package main
import (
"context"
"fmt"
"net/http"
"os"
"encoding/json"
"log/slog"
"cloud.google.com/go/vertexai/genai"
)
var model *genai.GenerativeModel
func main() {
ctx := context.Background()
projectID, err := projectID(ctx)
if err != nil {
return
}
setupLogging()
var client *genai.Client
client, err = genai.NewClient(ctx, projectID, "us-central1")
if err != nil {
slog.ErrorContext(ctx, "Failed to marshal response to JSON", slog.Any("error", err))
os.Exit(1)
}
defer client.Close()
model = client.GenerativeModel("gemini-1.5-flash-001")
http.HandleFunc("/", Handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
if err := http.ListenAndServe(":"+port, nil); err != nil {
slog.ErrorContext(ctx, "Failed to start the server", slog.Any("error", err))
os.Exit(1)
}
}
func Handler(w http.ResponseWriter, r *http.Request) {
animal := r.URL.Query().Get("animal")
if animal == "" {
animal = "dog"
}
prompt := fmt.Sprintf("Give me 10 fun facts about %s. Return the results as HTML without markdown backticks.", animal)
resp, err := model.GenerateContent(r.Context(), genai.Text(prompt))
if err != nil {
w.WriteHeader(http.StatusTooManyRequests)
return
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
slog.Error("Failed to marshal response to JSON", slog.Any("error", err))
} else {
slog.DebugContext(r.Context(), "content is generated", slog.String("animal", animal),
slog.String("prompt", prompt), slog.String("response", string(jsonBytes)))
}
if len(resp.Candidates) > 0 && len(resp.Candidates[0].Content.Parts) > 0 {
htmlContent := resp.Candidates[0].Content.Parts[0]
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, htmlContent)
}
}
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 main()
function is modified to setup the Go standard structured log to use JSON schema that follows structured formatting guidelines. All its return
statements are replaced with the code that writes error logs before exiting. The Handler()
function is instrumented to write structured log when receiving the response from the Vertex AI API call. The log captures 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
- 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, re-open
setup.go
:cloudshell edit ~/codelab-o11y/setup.go
- Replace the code with the version that initializes OpenTelemetry tracing and metric collection. To replace the code, delete the content of the file and then copy the code below and paste it into the editor:
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"log/slog"
"go.opentelemetry.io/contrib/detectors/gcp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/contrib/propagators/autoprop"
"go.opentelemetry.io/otel"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
"go.opentelemetry.io/otel/trace"
cloudmetric "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric"
cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
"cloud.google.com/go/compute/metadata"
)
var (
projID string
)
func projectID(ctx context.Context) (string, error) {
var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
return metadata.ProjectIDWithContext(ctx)
}
return projectID, nil
}
func setupLogging() {
opts := &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(group []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.LevelKey:
a.Key = "severity"
if level := a.Value.Any().(slog.Level); level == slog.LevelWarn {
a.Value = slog.StringValue("WARNING")
}
case slog.MessageKey:
a.Key = "message"
case slog.TimeKey:
a.Key = "timestamp"
}
return a
},
}
jsonHandler := slog.NewJSONHandler(os.Stdout, opts)
instrumentedHandler := handlerWithSpanContext(jsonHandler)
slog.SetDefault(slog.New(instrumentedHandler))
}
type spanContextLogHandler struct {
slog.Handler
}
func handlerWithSpanContext(handler slog.Handler) *spanContextLogHandler {
return &spanContextLogHandler{Handler: handler}
}
func (t *spanContextLogHandler) Handle(ctx context.Context, record slog.Record) error {
if s := trace.SpanContextFromContext(ctx); s.IsValid() {
trace := fmt.Sprintf("projects/%s/traces/%s", projID, s.TraceID())
record.AddAttrs(
slog.Any("logging.googleapis.com/trace", trace),
)
record.AddAttrs(
slog.Any("logging.googleapis.com/spanId", s.SpanID()),
)
record.AddAttrs(
slog.Bool("logging.googleapis.com/trace_sampled", s.TraceFlags().IsSampled()),
)
}
return t.Handler.Handle(ctx, record)
}
func setupTelemetry(ctx context.Context) (shutdown func(context.Context) error, err error) {
var shutdownFuncs []func(context.Context) error
shutdown = func(ctx context.Context) error {
var err error
for _, fn := range shutdownFuncs {
err = errors.Join(err, fn(ctx))
}
shutdownFuncs = nil
return err
}
projID, err = projectID(ctx)
if err != nil {
err = errors.Join(err, shutdown(ctx))
return
}
res, err2 := resource.New(
ctx,
resource.WithDetectors(gcp.NewDetector()),
resource.WithTelemetrySDK(),
resource.WithAttributes(semconv.ServiceNameKey.String(os.Getenv("K_SERVICE"))),
)
if err2 != nil {
err = errors.Join(err2, shutdown(ctx))
return
}
otel.SetTextMapPropagator(autoprop.NewTextMapPropagator())
texporter, err2 := cloudtrace.New(cloudtrace.WithProjectID(projID))
if err2 != nil {
err = errors.Join(err2, shutdown(ctx))
return
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithSampler(sdktrace.AlwaysSample()),
sdktrace.WithResource(res),
sdktrace.WithBatcher(texporter))
shutdownFuncs = append(shutdownFuncs, tp.Shutdown)
otel.SetTracerProvider(tp)
mexporter, err2 := cloudmetric.New(cloudmetric.WithProjectID(projID))
if err2 != nil {
err = errors.Join(err2, shutdown(ctx))
return
}
mp := sdkmetric.NewMeterProvider(
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(mexporter)),
sdkmetric.WithResource(res),
)
shutdownFuncs = append(shutdownFuncs, mp.Shutdown)
otel.SetMeterProvider(mp)
return shutdown, nil
}
func registerHttpHandler(route string, handleFn http.HandlerFunc) {
instrumentedHandler := otelhttp.NewHandler(otelhttp.WithRouteTag(route, handleFn), route)
http.Handle(route, instrumentedHandler)
} - Return to the terminal and run the following command to update the Go module definitions in the
go.mod
file:go mod tidy
- Return to the terminal, and re-open
main.go
:cloudshell edit ~/codelab-o11y/main.go
- Replace the current code with the version that instruments HTTP tracing and writes performance metric. To replace the code, delete the content of the file and then copy the code below and paste it into the editor:
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"encoding/json"
"log/slog"
"cloud.google.com/go/vertexai/genai"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
)
var model *genai.GenerativeModel
var counter metric.Int64Counter
const scopeName = "genai-o11y/go/workshop/example"
func main() {
ctx := context.Background()
projectID, err := projectID(ctx)
if err != nil {
return
}
setupLogging()
shutdown, err := setupTelemetry(ctx)
if err != nil {
slog.ErrorContext(ctx, "error setting up OpenTelemetry", slog.Any("error", err))
os.Exit(1)
}
meter := otel.Meter(scopeName)
counter, err = meter.Int64Counter("model_call_counter")
if err != nil {
slog.ErrorContext(ctx, "error setting up OpenTelemetry", slog.Any("error", err))
os.Exit(1)
}
var client *genai.Client
client, err = genai.NewClient(ctx, projectID, "us-central1")
if err != nil {
slog.ErrorContext(ctx, "Failed to marshal response to JSON", slog.Any("error", err))
os.Exit(1)
}
defer client.Close()
model = client.GenerativeModel("gemini-1.5-flash-001")
registerHttpHandler("/", Handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
if err = errors.Join(http.ListenAndServe(":"+port, nil), shutdown(ctx)); err != nil {
slog.ErrorContext(ctx, "Failed to start the server", slog.Any("error", err))
os.Exit(1)
}
}
func Handler(w http.ResponseWriter, r *http.Request) {
animal := r.URL.Query().Get("animal")
if animal == "" {
animal = "dog"
}
prompt := fmt.Sprintf("Give me 10 fun facts about %s. Return the results as HTML without markdown backticks.", animal)
resp, err := model.GenerateContent(r.Context(), genai.Text(prompt))
if err != nil {
w.WriteHeader(http.StatusTooManyRequests)
return
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
slog.ErrorContext(r.Context(), "Failed to marshal response to JSON", slog.Any("error", err))
} else {
slog.DebugContext(r.Context(), "content is generated", slog.String("animal", animal),
slog.String("prompt", prompt), slog.String("response", string(jsonBytes)))
}
if len(resp.Candidates) > 0 && len(resp.Candidates[0].Content.Parts) > 0 {
clabels := []attribute.KeyValue{attribute.Key("animal").String(animal)}
counter.Add(r.Context(), 1, metric.WithAttributes(clabels...))
htmlContent := resp.Candidates[0].Content.Parts[0]
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, htmlContent)
}
}
The application now uses OpenTelemetry SDK to instrument the code execution with tracing and to implement counting a number of successful execution as a metric. The main()
method is modified to setup the OpenTelemetry exporters for traces and metrics to write to Google Cloud Tracing and Monitoring directly. It also performs additional configurations to populate the collected traces and metrics with metadata related to the Cloud Run environment. The Handler()
function is updated to increment the metric counter each time the Vertex AI API call returns valid results.
After a few seconds, Cloud Shell Editor saves your changes automatically.
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