genkit-google-cloud 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- genkit_google_cloud/__init__.py +64 -0
- genkit_google_cloud/py.typed +0 -0
- genkit_google_cloud/telemetry/__init__.py +45 -0
- genkit_google_cloud/telemetry/action.py +126 -0
- genkit_google_cloud/telemetry/config.py +318 -0
- genkit_google_cloud/telemetry/constants.py +50 -0
- genkit_google_cloud/telemetry/engagement.py +171 -0
- genkit_google_cloud/telemetry/exporters.py +112 -0
- genkit_google_cloud/telemetry/feature.py +186 -0
- genkit_google_cloud/telemetry/gcp_logger.py +246 -0
- genkit_google_cloud/telemetry/generate.py +562 -0
- genkit_google_cloud/telemetry/metrics.py +246 -0
- genkit_google_cloud/telemetry/metrics_exporter.py +153 -0
- genkit_google_cloud/telemetry/path.py +157 -0
- genkit_google_cloud/telemetry/trace_exporter.py +254 -0
- genkit_google_cloud/telemetry/tracing.py +198 -0
- genkit_google_cloud/telemetry/utils.py +189 -0
- genkit_google_cloud-0.9.0.dist-info/METADATA +45 -0
- genkit_google_cloud-0.9.0.dist-info/RECORD +21 -0
- genkit_google_cloud-0.9.0.dist-info/WHEEL +4 -0
- genkit_google_cloud-0.9.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
"""Google Cloud Plugin for Genkit.
|
|
19
|
+
|
|
20
|
+
This plugin provides Google Cloud observability integration for Genkit,
|
|
21
|
+
enabling telemetry export to Cloud Trace, Cloud Monitoring, and Cloud Logging.
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
```python
|
|
25
|
+
from genkit import Genkit
|
|
26
|
+
from genkit_google_genai import GoogleAI
|
|
27
|
+
from genkit_google_cloud import enable_google_cloud_telemetry
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# 1. Enable Google Cloud Trace and Monitoring export
|
|
31
|
+
enable_google_cloud_telemetry(project_id='my-project')
|
|
32
|
+
|
|
33
|
+
# 2. All subsequent Genkit actions automatically export telemetry
|
|
34
|
+
ai = Genkit(plugins=[GoogleAI()], model='googleai/gemini-flash-latest')
|
|
35
|
+
await ai.generate(prompt='Hello, world!')
|
|
36
|
+
# => Traces exported asynchronously to Cloud Trace (latency, tokens, status)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Requirements:
|
|
40
|
+
- Requires Google Cloud Application Default Credentials (ADC) or explicit credentials.
|
|
41
|
+
- Telemetry export is disabled by default in local dev environments unless explicitly configured.
|
|
42
|
+
|
|
43
|
+
See Also:
|
|
44
|
+
- Cloud Trace: https://cloud.google.com/trace
|
|
45
|
+
- Cloud Monitoring: https://cloud.google.com/monitoring
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from .telemetry import add_gcp_telemetry, enable_google_cloud_telemetry
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def package_name() -> str:
|
|
52
|
+
"""Get the package name for the Google Cloud plugin.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
The fully qualified package name as a string.
|
|
56
|
+
"""
|
|
57
|
+
return 'genkit_google_cloud'
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
'add_gcp_telemetry',
|
|
62
|
+
'enable_google_cloud_telemetry',
|
|
63
|
+
'package_name',
|
|
64
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Google Cloud telemetry integration for Genkit.
|
|
18
|
+
|
|
19
|
+
This package provides telemetry export to Google Cloud's observability suite,
|
|
20
|
+
enabling monitoring and debugging of Genkit applications through Cloud Trace,
|
|
21
|
+
Cloud Monitoring, and Cloud Logging.
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
```python
|
|
25
|
+
from genkit import Genkit
|
|
26
|
+
from genkit_google_genai import GoogleAI
|
|
27
|
+
from genkit_google_cloud import enable_google_cloud_telemetry
|
|
28
|
+
|
|
29
|
+
# 1. Enable Google Cloud Trace and Monitoring export
|
|
30
|
+
enable_google_cloud_telemetry(project_id='my-project')
|
|
31
|
+
|
|
32
|
+
# 2. All subsequent Genkit actions automatically export telemetry
|
|
33
|
+
ai = Genkit(plugins=[GoogleAI()], model='googleai/gemini-flash-latest')
|
|
34
|
+
await ai.generate(prompt='Hello, world!')
|
|
35
|
+
# => Traces exported asynchronously to Cloud Trace (latency, tokens, status)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
See Also:
|
|
39
|
+
- Cloud Trace: https://cloud.google.com/trace/docs
|
|
40
|
+
- Cloud Monitoring: https://cloud.google.com/monitoring/docs
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from .tracing import add_gcp_telemetry, enable_google_cloud_telemetry
|
|
44
|
+
|
|
45
|
+
__all__ = ['add_gcp_telemetry', 'enable_google_cloud_telemetry']
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Action telemetry for GCP.
|
|
18
|
+
|
|
19
|
+
This module logs input/output for tool and generate actions,
|
|
20
|
+
matching the JavaScript implementation.
|
|
21
|
+
|
|
22
|
+
Logging:
|
|
23
|
+
When log_input_and_output=True, logs action inputs and outputs to
|
|
24
|
+
Cloud Logging with structured attributes for correlation.
|
|
25
|
+
|
|
26
|
+
Cross-Language Parity:
|
|
27
|
+
- JavaScript: js/plugins/google-cloud/src/telemetry/action.ts
|
|
28
|
+
- Go: go/plugins/googlecloud/action.go
|
|
29
|
+
|
|
30
|
+
See Also:
|
|
31
|
+
- Cloud Logging: https://cloud.google.com/logging/docs
|
|
32
|
+
- Structured Logging: https://cloud.google.com/logging/docs/structured-logging
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import structlog
|
|
38
|
+
from opentelemetry.sdk.trace import ReadableSpan
|
|
39
|
+
|
|
40
|
+
from genkit.plugin_api import to_display_path
|
|
41
|
+
|
|
42
|
+
from .gcp_logger import gcp_logger
|
|
43
|
+
from .utils import (
|
|
44
|
+
create_common_log_attributes,
|
|
45
|
+
extract_outer_feature_name_from_path,
|
|
46
|
+
truncate,
|
|
47
|
+
truncate_path,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
logger = structlog.get_logger(__name__)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ActionTelemetry:
|
|
54
|
+
"""Telemetry handler for Genkit actions (tools, generate)."""
|
|
55
|
+
|
|
56
|
+
def tick(
|
|
57
|
+
self,
|
|
58
|
+
span: ReadableSpan,
|
|
59
|
+
log_input_and_output: bool,
|
|
60
|
+
project_id: str | None = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Record telemetry for an action span.
|
|
63
|
+
|
|
64
|
+
Only logs input/output if log_input_and_output is True.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
span: The span to record telemetry for.
|
|
68
|
+
log_input_and_output: Whether to log input/output.
|
|
69
|
+
project_id: Optional GCP project ID.
|
|
70
|
+
"""
|
|
71
|
+
if not log_input_and_output:
|
|
72
|
+
return
|
|
73
|
+
|
|
74
|
+
attrs = span.attributes or {}
|
|
75
|
+
action_name = str(attrs.get('genkit:name', '')) or '<unknown>'
|
|
76
|
+
subtype = str(attrs.get('genkit:metadata:subtype', ''))
|
|
77
|
+
|
|
78
|
+
# Only log for tools and generate actions
|
|
79
|
+
if subtype != 'tool' and action_name != 'generate':
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
path = str(attrs.get('genkit:path', '')) or '<unknown>'
|
|
83
|
+
input_val = truncate(str(attrs.get('genkit:input', '')))
|
|
84
|
+
output_val = truncate(str(attrs.get('genkit:output', '')))
|
|
85
|
+
session_id = str(attrs.get('genkit:sessionId', '')) or None
|
|
86
|
+
thread_name = str(attrs.get('genkit:threadName', '')) or None
|
|
87
|
+
|
|
88
|
+
feature_name = extract_outer_feature_name_from_path(path)
|
|
89
|
+
if not feature_name or feature_name == '<unknown>':
|
|
90
|
+
feature_name = action_name
|
|
91
|
+
|
|
92
|
+
if input_val:
|
|
93
|
+
self._write_log(span, 'Input', feature_name, path, input_val, project_id, session_id, thread_name)
|
|
94
|
+
if output_val:
|
|
95
|
+
self._write_log(span, 'Output', feature_name, path, output_val, project_id, session_id, thread_name)
|
|
96
|
+
|
|
97
|
+
def _write_log(
|
|
98
|
+
self,
|
|
99
|
+
span: ReadableSpan,
|
|
100
|
+
tag: str,
|
|
101
|
+
feature_name: str,
|
|
102
|
+
qualified_path: str,
|
|
103
|
+
content: str,
|
|
104
|
+
project_id: str | None,
|
|
105
|
+
session_id: str | None,
|
|
106
|
+
thread_name: str | None,
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Write a structured log entry to Cloud Logging."""
|
|
109
|
+
path = truncate_path(to_display_path(qualified_path))
|
|
110
|
+
metadata = {
|
|
111
|
+
**create_common_log_attributes(span, project_id),
|
|
112
|
+
'path': path,
|
|
113
|
+
'qualifiedPath': qualified_path,
|
|
114
|
+
'featureName': feature_name,
|
|
115
|
+
'content': content,
|
|
116
|
+
}
|
|
117
|
+
if session_id:
|
|
118
|
+
metadata['sessionId'] = session_id
|
|
119
|
+
if thread_name:
|
|
120
|
+
metadata['threadName'] = thread_name
|
|
121
|
+
|
|
122
|
+
gcp_logger.log_structured(f'{tag}[{path}, {feature_name}]', metadata)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# Singleton instance
|
|
126
|
+
action_telemetry = ActionTelemetry()
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Configuration management for GCP telemetry.
|
|
18
|
+
|
|
19
|
+
This module handles project ID resolution, telemetry configuration,
|
|
20
|
+
and initialization of tracing, metrics, and logging.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import os
|
|
25
|
+
import uuid
|
|
26
|
+
from collections.abc import Mapping
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import structlog
|
|
30
|
+
from opentelemetry import metrics
|
|
31
|
+
from opentelemetry.exporter.cloud_monitoring import CloudMonitoringMetricsExporter
|
|
32
|
+
from opentelemetry.resourcedetector.gcp_resource_detector import GoogleCloudResourceDetector
|
|
33
|
+
from opentelemetry.sdk.metrics import MeterProvider
|
|
34
|
+
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
|
35
|
+
from opentelemetry.sdk.resources import SERVICE_INSTANCE_ID, SERVICE_NAME, Resource
|
|
36
|
+
from opentelemetry.sdk.trace.sampling import Sampler
|
|
37
|
+
from opentelemetry.trace import get_current_span, span as trace_span
|
|
38
|
+
|
|
39
|
+
from genkit.plugin_api import add_custom_exporter, is_dev_environment
|
|
40
|
+
|
|
41
|
+
from .constants import (
|
|
42
|
+
DEFAULT_METRIC_EXPORT_INTERVAL_MS,
|
|
43
|
+
DEV_METRIC_EXPORT_INTERVAL_MS,
|
|
44
|
+
MIN_METRIC_EXPORT_INTERVAL_MS,
|
|
45
|
+
PROJECT_ID_ENV_VARS,
|
|
46
|
+
)
|
|
47
|
+
from .exporters import handle_metric_error, handle_tracing_error
|
|
48
|
+
from .metrics_exporter import GenkitMetricExporter
|
|
49
|
+
from .trace_exporter import GcpAdjustingTraceExporter, GenkitGCPExporter
|
|
50
|
+
|
|
51
|
+
logger = structlog.get_logger(__name__)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resolve_project_id(
|
|
55
|
+
project_id: str | None = None,
|
|
56
|
+
credentials: dict[str, Any] | None = None,
|
|
57
|
+
) -> str | None:
|
|
58
|
+
"""Resolve the GCP project ID from multiple sources.
|
|
59
|
+
|
|
60
|
+
Resolution order (matching JS/Go):
|
|
61
|
+
1. Explicit project_id parameter
|
|
62
|
+
2. FIREBASE_PROJECT_ID environment variable
|
|
63
|
+
3. GOOGLE_CLOUD_PROJECT environment variable
|
|
64
|
+
4. GCLOUD_PROJECT environment variable
|
|
65
|
+
5. Project ID from credentials
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
project_id: Explicitly provided project ID.
|
|
69
|
+
credentials: Optional credentials dict with project_id.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
The resolved project ID or None.
|
|
73
|
+
"""
|
|
74
|
+
if project_id:
|
|
75
|
+
return project_id
|
|
76
|
+
|
|
77
|
+
# Check environment variables in order of priority
|
|
78
|
+
for env_var in PROJECT_ID_ENV_VARS:
|
|
79
|
+
env_value = os.environ.get(env_var)
|
|
80
|
+
if env_value:
|
|
81
|
+
return env_value
|
|
82
|
+
|
|
83
|
+
# Check credentials for project_id
|
|
84
|
+
if credentials and 'project_id' in credentials:
|
|
85
|
+
return credentials['project_id']
|
|
86
|
+
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class GcpTelemetry:
|
|
91
|
+
"""Central manager for GCP Telemetry configuration.
|
|
92
|
+
|
|
93
|
+
Encapsulates configuration and manages the lifecycle of Tracing, Metrics,
|
|
94
|
+
and Logging setup, ensuring consistent state (like project_id) across all
|
|
95
|
+
telemetry components.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
project_id: str | None = None,
|
|
101
|
+
credentials: dict[str, Any] | None = None,
|
|
102
|
+
sampler: Sampler | None = None,
|
|
103
|
+
log_input_and_output: bool = False,
|
|
104
|
+
force_dev_export: bool = False,
|
|
105
|
+
disable_metrics: bool = False,
|
|
106
|
+
disable_traces: bool = False,
|
|
107
|
+
metric_export_interval_ms: int | None = None,
|
|
108
|
+
metric_export_timeout_ms: int | None = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
"""Initialize the GCP Telemetry manager.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
project_id: GCP project ID.
|
|
114
|
+
credentials: Optional credentials dict.
|
|
115
|
+
sampler: Trace sampler.
|
|
116
|
+
log_input_and_output: If False, hides sensitive data.
|
|
117
|
+
force_dev_export: Check to force export in dev environment.
|
|
118
|
+
disable_metrics: If True, metrics are not exported.
|
|
119
|
+
disable_traces: If True, traces are not exported.
|
|
120
|
+
metric_export_interval_ms: Export interval in ms.
|
|
121
|
+
metric_export_timeout_ms: Export timeout in ms.
|
|
122
|
+
"""
|
|
123
|
+
self.credentials = credentials
|
|
124
|
+
self.sampler = sampler
|
|
125
|
+
self.log_input_and_output = log_input_and_output
|
|
126
|
+
self.force_dev_export = force_dev_export
|
|
127
|
+
self.disable_metrics = disable_metrics
|
|
128
|
+
self.disable_traces = disable_traces
|
|
129
|
+
|
|
130
|
+
# Resolve project ID immediately
|
|
131
|
+
self.project_id = resolve_project_id(project_id, credentials)
|
|
132
|
+
|
|
133
|
+
# Determine metric export settings
|
|
134
|
+
is_dev = is_dev_environment()
|
|
135
|
+
|
|
136
|
+
default_interval = DEV_METRIC_EXPORT_INTERVAL_MS if is_dev else DEFAULT_METRIC_EXPORT_INTERVAL_MS
|
|
137
|
+
self.metric_export_interval_ms = metric_export_interval_ms or default_interval
|
|
138
|
+
|
|
139
|
+
if self.metric_export_interval_ms < MIN_METRIC_EXPORT_INTERVAL_MS:
|
|
140
|
+
logger.warning(
|
|
141
|
+
f'metric_export_interval_ms ({self.metric_export_interval_ms}) is below minimum '
|
|
142
|
+
f'({MIN_METRIC_EXPORT_INTERVAL_MS}), using minimum'
|
|
143
|
+
)
|
|
144
|
+
self.metric_export_interval_ms = MIN_METRIC_EXPORT_INTERVAL_MS
|
|
145
|
+
|
|
146
|
+
self.metric_export_timeout_ms = metric_export_timeout_ms or self.metric_export_interval_ms
|
|
147
|
+
|
|
148
|
+
def _build_exporter_kwargs(self) -> dict[str, Any]:
|
|
149
|
+
"""Build kwargs dict for exporters with project_id and credentials.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
A dict with project_id and/or credentials if available, empty dict otherwise.
|
|
153
|
+
"""
|
|
154
|
+
kwargs: dict[str, Any] = {}
|
|
155
|
+
if self.project_id:
|
|
156
|
+
kwargs['project_id'] = self.project_id
|
|
157
|
+
if self.credentials:
|
|
158
|
+
kwargs['credentials'] = self.credentials
|
|
159
|
+
return kwargs
|
|
160
|
+
|
|
161
|
+
def initialize(self) -> None:
|
|
162
|
+
"""Actuates the telemetry configuration.
|
|
163
|
+
|
|
164
|
+
CRITICAL: This method MUST be called to initialize telemetry handlers
|
|
165
|
+
even in dev mode. The 'export' flag controls whether data is sent to
|
|
166
|
+
GCP, but initialization is ALWAYS required for proper operation.
|
|
167
|
+
"""
|
|
168
|
+
is_dev = is_dev_environment()
|
|
169
|
+
should_export = self.force_dev_export or not is_dev
|
|
170
|
+
|
|
171
|
+
# ALWAYS configure logging (required for telemetry handlers)
|
|
172
|
+
# The export flag is passed down to control Cloud Logging export
|
|
173
|
+
self._configure_logging()
|
|
174
|
+
|
|
175
|
+
# Only configure tracing/metrics if exporting (performance optimization)
|
|
176
|
+
if should_export:
|
|
177
|
+
self._configure_tracing()
|
|
178
|
+
self._configure_metrics()
|
|
179
|
+
logger.info(
|
|
180
|
+
'Telemetry fully initialized',
|
|
181
|
+
project_id=self.project_id,
|
|
182
|
+
export_enabled=True,
|
|
183
|
+
environment='dev' if is_dev else 'prod',
|
|
184
|
+
force_dev_export=self.force_dev_export,
|
|
185
|
+
)
|
|
186
|
+
else:
|
|
187
|
+
logger.debug(
|
|
188
|
+
'Telemetry initialized in local-only mode',
|
|
189
|
+
export_enabled=False,
|
|
190
|
+
environment='dev',
|
|
191
|
+
note='Use force_dev_export=True for full AIM visibility in dev',
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def _configure_logging(self) -> None:
|
|
195
|
+
"""Configure structlog with Cloud Logging export and trace correlation."""
|
|
196
|
+
from .gcp_logger import gcp_logger
|
|
197
|
+
|
|
198
|
+
is_dev = is_dev_environment()
|
|
199
|
+
should_export = self.force_dev_export or not is_dev
|
|
200
|
+
|
|
201
|
+
# Initialize the GCP logger for telemetry modules
|
|
202
|
+
gcp_logger.initialize(
|
|
203
|
+
project_id=self.project_id,
|
|
204
|
+
credentials=self.credentials,
|
|
205
|
+
export=should_export,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
# Configure structlog processors for trace correlation
|
|
209
|
+
try:
|
|
210
|
+
current_config = structlog.get_config()
|
|
211
|
+
processors = list(current_config.get('processors', []))
|
|
212
|
+
|
|
213
|
+
# Early return if already configured
|
|
214
|
+
if any(getattr(p, '__name__', '') == '_genkit_inject_trace_context' for p in processors):
|
|
215
|
+
return
|
|
216
|
+
|
|
217
|
+
# Define processor function that captures self
|
|
218
|
+
def _genkit_inject_trace_context(
|
|
219
|
+
logger_instance: logging.Logger,
|
|
220
|
+
method_name: str,
|
|
221
|
+
event_dict: dict[str, Any],
|
|
222
|
+
) -> Mapping[str, Any]:
|
|
223
|
+
return self._inject_trace_context(logger_instance, method_name, event_dict)
|
|
224
|
+
|
|
225
|
+
# Append processor to chain
|
|
226
|
+
processors.append(_genkit_inject_trace_context)
|
|
227
|
+
structlog.configure(processors=processors)
|
|
228
|
+
logger.debug('Configured structlog for GCP trace correlation')
|
|
229
|
+
|
|
230
|
+
except Exception as e:
|
|
231
|
+
logger.warning('Failed to configure structlog for trace correlation', error=str(e))
|
|
232
|
+
|
|
233
|
+
def _configure_tracing(self) -> None:
|
|
234
|
+
if self.disable_traces:
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
try:
|
|
238
|
+
exporter_kwargs = self._build_exporter_kwargs()
|
|
239
|
+
base_exporter = GenkitGCPExporter(**exporter_kwargs) if exporter_kwargs else GenkitGCPExporter()
|
|
240
|
+
|
|
241
|
+
trace_exporter = GcpAdjustingTraceExporter(
|
|
242
|
+
exporter=base_exporter,
|
|
243
|
+
log_input_and_output=self.log_input_and_output,
|
|
244
|
+
project_id=self.project_id,
|
|
245
|
+
error_handler=handle_tracing_error,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
add_custom_exporter(trace_exporter, 'gcp_telemetry_server')
|
|
249
|
+
except Exception as e:
|
|
250
|
+
handle_tracing_error(e)
|
|
251
|
+
|
|
252
|
+
def _configure_metrics(self) -> None:
|
|
253
|
+
if self.disable_metrics:
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
resource = Resource.create({
|
|
258
|
+
SERVICE_NAME: 'genkit',
|
|
259
|
+
SERVICE_INSTANCE_ID: str(uuid.uuid4()),
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
# Suppress detector warnings during GCP resource detection
|
|
263
|
+
detector_logger = logging.getLogger('opentelemetry.resourcedetector.gcp_resource_detector')
|
|
264
|
+
original_level = detector_logger.level
|
|
265
|
+
detector_logger.setLevel(logging.ERROR)
|
|
266
|
+
|
|
267
|
+
try:
|
|
268
|
+
gcp_resource = GoogleCloudResourceDetector(raise_on_error=True).detect()
|
|
269
|
+
resource = resource.merge(gcp_resource)
|
|
270
|
+
except Exception as e:
|
|
271
|
+
# For detection failure log the exception and use the default resource
|
|
272
|
+
detector_logger.warning(f'Google Cloud resource detection failed: {e}')
|
|
273
|
+
finally:
|
|
274
|
+
detector_logger.setLevel(original_level)
|
|
275
|
+
|
|
276
|
+
exporter_kwargs = self._build_exporter_kwargs()
|
|
277
|
+
cloud_monitoring_exporter = CloudMonitoringMetricsExporter(**exporter_kwargs)
|
|
278
|
+
|
|
279
|
+
metrics_exporter = GenkitMetricExporter(
|
|
280
|
+
exporter=cloud_monitoring_exporter,
|
|
281
|
+
error_handler=handle_metric_error,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
reader = PeriodicExportingMetricReader(
|
|
285
|
+
metrics_exporter,
|
|
286
|
+
export_interval_millis=self.metric_export_interval_ms,
|
|
287
|
+
export_timeout_millis=self.metric_export_timeout_ms,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
provider = MeterProvider(metric_readers=[reader], resource=resource)
|
|
291
|
+
metrics.set_meter_provider(provider)
|
|
292
|
+
|
|
293
|
+
except Exception as e:
|
|
294
|
+
handle_metric_error(e)
|
|
295
|
+
|
|
296
|
+
def _inject_trace_context(
|
|
297
|
+
self, logger: logging.Logger, method_name: str, event_dict: dict[str, Any]
|
|
298
|
+
) -> dict[str, Any]:
|
|
299
|
+
"""Structlog processor to inject GCP-compatible trace context."""
|
|
300
|
+
# Only inject if event_dict is a dict or mapping
|
|
301
|
+
if not isinstance(event_dict, dict) and not hasattr(event_dict, '__setitem__'):
|
|
302
|
+
return event_dict
|
|
303
|
+
|
|
304
|
+
span = get_current_span()
|
|
305
|
+
if span == trace_span.INVALID_SPAN:
|
|
306
|
+
return event_dict
|
|
307
|
+
|
|
308
|
+
ctx = span.get_span_context()
|
|
309
|
+
if not ctx.is_valid:
|
|
310
|
+
return event_dict
|
|
311
|
+
|
|
312
|
+
if self.project_id:
|
|
313
|
+
event_dict['logging.googleapis.com/trace'] = f'projects/{self.project_id}/traces/{ctx.trace_id:032x}'
|
|
314
|
+
|
|
315
|
+
event_dict['logging.googleapis.com/spanId'] = f'{ctx.span_id:016x}'
|
|
316
|
+
event_dict['logging.googleapis.com/trace_sampled'] = '1' if ctx.trace_flags.sampled else '0'
|
|
317
|
+
|
|
318
|
+
return event_dict
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Constants for GCP telemetry.
|
|
18
|
+
|
|
19
|
+
This module centralizes all constants used across the GCP telemetry
|
|
20
|
+
implementation, matching the pattern from JS/Go implementations.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
# Metric export intervals (matching JS/Go implementations)
|
|
24
|
+
MIN_METRIC_EXPORT_INTERVAL_MS = 5000
|
|
25
|
+
DEFAULT_METRIC_EXPORT_INTERVAL_MS = 300000
|
|
26
|
+
DEV_METRIC_EXPORT_INTERVAL_MS = 5000
|
|
27
|
+
PROD_METRIC_EXPORT_INTERVAL_MS = 300000
|
|
28
|
+
|
|
29
|
+
# Project ID environment variables (resolution order)
|
|
30
|
+
# Priority: FIREBASE_PROJECT_ID > GOOGLE_CLOUD_PROJECT > GCLOUD_PROJECT
|
|
31
|
+
PROJECT_ID_ENV_VARS = (
|
|
32
|
+
'FIREBASE_PROJECT_ID',
|
|
33
|
+
'GOOGLE_CLOUD_PROJECT',
|
|
34
|
+
'GCLOUD_PROJECT',
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Retry configuration for trace export to Cloud Trace
|
|
38
|
+
TRACE_RETRY_INITIAL = 0.1
|
|
39
|
+
TRACE_RETRY_MAXIMUM = 30.0
|
|
40
|
+
TRACE_RETRY_MULTIPLIER = 2
|
|
41
|
+
TRACE_RETRY_DEADLINE = 120.0
|
|
42
|
+
|
|
43
|
+
# Time adjustment for GCP span requirements
|
|
44
|
+
# GCP requires end_time > start_time, so we add 1 microsecond minimum duration
|
|
45
|
+
MIN_SPAN_DURATION_NS = 1000 # 1 microsecond in nanoseconds
|
|
46
|
+
|
|
47
|
+
# Start time adjustment for metrics to prevent DELTA->CUMULATIVE overlap
|
|
48
|
+
# Cloud Monitoring converts DELTA to CUMULATIVE, causing overlap issues
|
|
49
|
+
# We add 1 millisecond to ensure discrete export timeframes
|
|
50
|
+
METRIC_START_TIME_ADJUSTMENT_NS = 1_000_000 # 1 millisecond in nanoseconds
|