Get started with Genkit Monitoring
This quickstart guide describes how to set up Genkit Monitoring for your deployed Genkit features, so that you can collect and view real-time telemetry data. With Genkit Monitoring, you get visibility into how your Genkit features are performing in production.
Key capabilities of Genkit Monitoring include:
- Viewing quantitative metrics like Genkit feature latency, errors, and token usage.
- Inspecting traces to see your Genkit’s feature steps, inputs, and outputs, to help with debugging and quality improvement.
- Exporting production traces to run evals within Genkit.
Setting up Genkit Monitoring requires completing tasks in both your codebase and on the Google Cloud Console.
Before you begin
Section titled “Before you begin”-
If you haven’t already, create a Firebase project.
In the Firebase console, click Add a project, then follow the on-screen instructions. You can create a new project or add Firebase services to an already-existing Google Cloud project.
-
Ensure your project is on the Blaze pricing plan.
Genkit Monitoring relies on telemetry data written to Google Cloud Logging, Metrics, and Trace, which are paid services. View the Google Cloud Observability pricing page for pricing details and to learn about free-of-charge tier limits.
-
Write a Genkit feature by following the Get Started Guide, and prepare your code for deployment by using one of the following guides:
Deploy your flows with Cloud Run or to any platform that runs a Python ASGI or WSGI server.
Step 1. Add the Firebase plugin
Section titled “Step 1. Add the Firebase plugin”Install the genkit-google-cloud package:
uv add genkit-google-cloudEnvironment-based configuration
Section titled “Environment-based configuration”There is no environment variable that turns telemetry on. You always call
enable_google_cloud_telemetry() in code.
Environment variables still affect what happens after you call it:
GENKIT_ENV: when set todev, nothing is exported unless you also passforce_dev_export=True.GOOGLE_CLOUD_PROJECTandGCLOUD_PROJECT: used to resolve the destination project when you leaveproject=unset.
The destination project is the first one found in this order:
project=GOOGLE_CLOUD_PROJECTGCLOUD_PROJECTcredentials['project_id']- The project on Application Default Credentials (ADC), looked up only when exporting
FIREBASE_PROJECT_ID is not read. If it is set and differs from the resolved
project, Genkit logs FIREBASE_PROJECT_ID is not used for telemetry; set project= or GOOGLE_CLOUD_PROJECT.
Programmatic configuration
Section titled “Programmatic configuration”Call enable_google_cloud_telemetry() once at module startup, before
Genkit(...). Calling it a second time in the same process raises GenkitError
(FAILED_PRECONDITION).
from fastapi import FastAPIfrom genkit import Genkitfrom genkit_fastapi import serve_flowfrom genkit_google_cloud import enable_google_cloud_telemetryfrom genkit_google_genai import GoogleAI
# 1. Attach Cloud Trace, Cloud Monitoring, and Cloud Logging exporters onceenable_google_cloud_telemetry()
# 2. Initialize Genkit and define a flowai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
@ai.flow()async def suggest_menu_item(dietary_preference: str) -> str: response = await ai.generate( prompt=f'Suggest one lunch special for a {dietary_preference} guest.' ) return response.text
# 3. Expose the flow over FastAPIapp = FastAPI()app.include_router(serve_flow(suggest_menu_item))See Advanced configuration for sampling, export intervals, and content capture options.
Step 2. Enable the required APIs
Section titled “Step 2. Enable the required APIs”Make sure that the following APIs are enabled for your Google Cloud project:
These APIs should be listed in the API dashboard for your project.
Step 3. Set up permissions
Section titled “Step 3. Set up permissions”The Firebase plugin needs to use a service account to authenticate with Google Cloud Logging, Metrics, and Trace services.
Grant the following roles to whichever service account is configured to run your code within the Google Cloud IAM Console. For Cloud Functions for Firebase and Cloud Run, that’s typically the default compute service account.
- Monitoring Metric Writer (
roles/monitoring.metricWriter) - Cloud Trace Agent (
roles/cloudtrace.agent) - Logs Writer (
roles/logging.logWriter)
Step 4. (Optional) Test your configuration locally
Section titled “Step 4. (Optional) Test your configuration locally”Before deploying, you can run your Genkit code locally to confirm that telemetry data is being collected, and is viewable in the Genkit Monitoring dashboard.
-
In your Genkit code, set
force_dev_export=Trueto send telemetry from your local environment:from genkit_google_cloud import enable_google_cloud_telemetryenable_google_cloud_telemetry(force_dev_export=True) -
Use your service account to authenticate and test your configuration.
With the Google Cloud CLI tool, authenticate using the service account:
gcloud auth application-default login --impersonate-service-account SERVICE_ACCT_EMAIL-
Run and invoke your Genkit feature, and then view metrics on the Genkit Monitoring dashboard. Allow for up to 5 minutes to collect the first metric. You can reduce this delay by lowering the metric export interval in the telemetry configuration.
-
If metrics are not appearing in the Genkit Monitoring dashboard, view the Troubleshooting guide for steps to debug.
Step 5. Re-build and deploy code
Section titled “Step 5. Re-build and deploy code”Re-build, deploy, and invoke your Genkit feature to start collecting data. After Genkit Monitoring receives your metrics, you can view them by visiting the Genkit Monitoring dashboard
Correlating a user report to a trace
Section titled “Correlating a user report to a trace”A support ticket is only useful if you can find the request it describes. Read the current trace ID inside the flow and hand it back to the caller.
from opentelemetry import tracefrom pydantic import BaseModelfrom genkit import Genkit, get_loggerfrom genkit_google_genai import GoogleAI
logger = get_logger(__name__)ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
class SupportReply(BaseModel): answer: str trace_id: str
@ai.flow()async def answer_billing_question(question: str) -> SupportReply: # 1. Read the active trace ID span_ctx = trace.get_current_span().get_span_context() trace_id = f'{span_ctx.trace_id:032x}' if span_ctx.is_valid else ''
# 2. Put the ID on your own log line so you can search for it logger.info('answering billing question', trace_id=trace_id) # => [info ] answering billing question trace_id=4bf92f3577b34da6a3ce929d0e0e4736
# 3. Return the ID so the caller can quote it in a report response = await ai.generate(prompt=f'Answer concisely: {question}') return SupportReply(answer=response.text, trace_id=trace_id) # => SupportReply(answer='Refunds post in 5-7 days.', trace_id='4bf92f3577b34da6a3ce929d0e0e4736')An X-Trace-Id response header works just as well if you do not want to change
the response body.
With the ID in hand:
- Search for it directly in Cloud Trace.
- Search Cloud Logging for the ID to find log lines that include it, like the
trace_id=field above.enable_google_cloud_telemetry()adds trace correlation togenkit.get_logger()records.
Export to any OTLP backend
Section titled “Export to any OTLP backend”Firebase and Google Cloud are not the only destinations. GenAiInstrumentation
creates Genkit’s spans on the global OpenTelemetry TracerProvider, so any OTLP
backend works:
Datadog, Honeycomb, Grafana, or a self-hosted collector. See
OpenTelemetry GenAI semantic conventions
for the setup.