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.
@@ -0,0 +1,171 @@
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
+ """Engagement telemetry for GCP.
18
+
19
+ This module tracks user feedback and acceptance metrics,
20
+ matching the JavaScript implementation.
21
+
22
+ Metrics Recorded:
23
+ - genkit/engagement/feedback: Counter for user feedback events
24
+ - genkit/engagement/acceptance: Counter for user acceptance events
25
+
26
+ Cross-Language Parity:
27
+ - JavaScript: js/plugins/google-cloud/src/telemetry/engagement.ts
28
+ - Go: go/plugins/googlecloud/engagement.go
29
+
30
+ See Also:
31
+ - Cloud Monitoring Custom Metrics: https://cloud.google.com/monitoring/custom-metrics
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import re
37
+ from typing import Any
38
+
39
+ import structlog
40
+ from opentelemetry import metrics
41
+ from opentelemetry.sdk.trace import ReadableSpan
42
+
43
+ from genkit.plugin_api import GENKIT_VERSION
44
+
45
+ from .gcp_logger import gcp_logger
46
+ from .utils import create_common_log_attributes, truncate
47
+
48
+ logger = structlog.get_logger(__name__)
49
+
50
+ # Lazy-initialized metrics
51
+ _feedback_counter: metrics.Counter | None = None
52
+ _acceptance_counter: metrics.Counter | None = None
53
+
54
+
55
+ def _get_feedback_counter() -> metrics.Counter:
56
+ """Get or create the user feedback counter."""
57
+ global _feedback_counter
58
+ if _feedback_counter is None:
59
+ meter = metrics.get_meter('genkit')
60
+ _feedback_counter = meter.create_counter(
61
+ 'genkit/engagement/feedback',
62
+ description='Counts user feedback events.',
63
+ unit='1',
64
+ )
65
+ return _feedback_counter
66
+
67
+
68
+ def _get_acceptance_counter() -> metrics.Counter:
69
+ """Get or create the user acceptance counter."""
70
+ global _acceptance_counter
71
+ if _acceptance_counter is None:
72
+ meter = metrics.get_meter('genkit')
73
+ _acceptance_counter = meter.create_counter(
74
+ 'genkit/engagement/acceptance',
75
+ description='Tracks user acceptance events.',
76
+ unit='1',
77
+ )
78
+ return _acceptance_counter
79
+
80
+
81
+ class EngagementTelemetry:
82
+ """Telemetry handler for user engagement (feedback, acceptance)."""
83
+
84
+ def tick(
85
+ self,
86
+ span: ReadableSpan,
87
+ log_input_and_output: bool,
88
+ project_id: str | None = None,
89
+ ) -> None:
90
+ """Record telemetry for a user engagement span.
91
+
92
+ Args:
93
+ span: The span to record telemetry for.
94
+ log_input_and_output: Whether to log input/output (unused here).
95
+ project_id: Optional GCP project ID.
96
+ """
97
+ attrs: dict[str, Any] = dict(span.attributes) if span.attributes else {}
98
+ subtype = str(attrs.get('genkit:metadata:subtype', ''))
99
+
100
+ if subtype == 'userFeedback':
101
+ self._write_user_feedback(span, attrs, project_id)
102
+ elif subtype == 'userAcceptance':
103
+ self._write_user_acceptance(span, attrs, project_id)
104
+ else:
105
+ logger.warning('Unknown user engagement subtype', subtype=subtype)
106
+
107
+ def _write_user_feedback(
108
+ self,
109
+ span: ReadableSpan,
110
+ attrs: dict[str, Any],
111
+ project_id: str | None,
112
+ ) -> None:
113
+ """Record user feedback metrics and logs."""
114
+ name = self._extract_trace_name(attrs)
115
+ feedback_value = attrs.get('genkit:metadata:feedbackValue')
116
+ text_feedback = attrs.get('genkit:metadata:textFeedback')
117
+
118
+ dimensions = {
119
+ 'name': str(name)[:256],
120
+ 'value': str(feedback_value)[:256] if feedback_value else '',
121
+ 'hasText': str(bool(text_feedback)),
122
+ 'source': 'py',
123
+ 'sourceVersion': GENKIT_VERSION,
124
+ }
125
+ _get_feedback_counter().add(1, dimensions)
126
+
127
+ metadata: dict[str, Any] = {
128
+ **create_common_log_attributes(span, project_id),
129
+ 'feedbackValue': feedback_value,
130
+ }
131
+ if text_feedback:
132
+ metadata['textFeedback'] = truncate(str(text_feedback))
133
+
134
+ gcp_logger.log_structured(f'UserFeedback[{name}]', metadata)
135
+
136
+ def _write_user_acceptance(
137
+ self,
138
+ span: ReadableSpan,
139
+ attrs: dict[str, Any],
140
+ project_id: str | None,
141
+ ) -> None:
142
+ """Record user acceptance metrics and logs."""
143
+ name = self._extract_trace_name(attrs)
144
+ acceptance_value = attrs.get('genkit:metadata:acceptanceValue')
145
+
146
+ dimensions = {
147
+ 'name': str(name)[:256],
148
+ 'value': str(acceptance_value)[:256] if acceptance_value else '',
149
+ 'source': 'py',
150
+ 'sourceVersion': GENKIT_VERSION,
151
+ }
152
+ _get_acceptance_counter().add(1, dimensions)
153
+
154
+ metadata = {
155
+ **create_common_log_attributes(span, project_id),
156
+ 'acceptanceValue': acceptance_value,
157
+ }
158
+ gcp_logger.log_structured(f'UserAcceptance[{name}]', metadata)
159
+
160
+ def _extract_trace_name(self, attrs: dict[str, Any]) -> str:
161
+ """Extract the trace name from span attributes."""
162
+ path = str(attrs.get('genkit:path', ''))
163
+ if not path or path == '<unknown>':
164
+ return '<unknown>'
165
+
166
+ match = re.search(r'/{(.+)}', path)
167
+ return match.group(1) if match else '<unknown>'
168
+
169
+
170
+ # Singleton instance
171
+ engagement_telemetry = EngagementTelemetry()
@@ -0,0 +1,112 @@
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
+ """Base exporter utilities for GCP telemetry.
18
+
19
+ This module provides reusable error handling and base utilities for
20
+ trace and metrics exporters, eliminating code duplication.
21
+ """
22
+
23
+ import structlog
24
+
25
+ logger = structlog.get_logger(__name__)
26
+
27
+
28
+ class ErrorHandler:
29
+ """Manages error handling for telemetry exports.
30
+
31
+ Ensures error messages are logged only once to avoid spam, while still
32
+ logging subsequent errors without the detailed help text.
33
+
34
+ This replaces the previous pattern of module-level boolean flags and
35
+ separate error handler functions for tracing and metrics.
36
+ """
37
+
38
+ def __init__(self) -> None:
39
+ """Initialize the error handler."""
40
+ self._logged = False
41
+
42
+ def handle(
43
+ self,
44
+ error: Exception,
45
+ error_message: str,
46
+ help_text: str,
47
+ ) -> None:
48
+ """Handle export error with one-time detailed logging.
49
+
50
+ Args:
51
+ error: The exception that occurred.
52
+ error_message: Brief description of what failed.
53
+ help_text: Detailed help text shown only on first error.
54
+ """
55
+ if not self._logged:
56
+ self._logged = True
57
+ logger.error(f'{error_message}\n{help_text}\nError: {error}')
58
+ else:
59
+ logger.error(f'{error_message}: {error}')
60
+
61
+
62
+ # Singleton error handlers for tracing and metrics
63
+ _tracing_error_handler = ErrorHandler()
64
+ _metrics_error_handler = ErrorHandler()
65
+
66
+ # Help text for tracing errors (GCP IAM requirements)
67
+ TRACING_HELP_TEXT = 'Ensure the service account has the "Cloud Trace Agent" (roles/cloudtrace.agent) role.'
68
+
69
+ # Help text for metrics errors (GCP IAM requirements)
70
+ METRICS_HELP_TEXT = (
71
+ 'Ensure the service account has the "Monitoring Metric Writer" '
72
+ '(roles/monitoring.metricWriter) or "Cloud Telemetry Metrics Writer" '
73
+ '(roles/telemetry.metricsWriter) role.'
74
+ )
75
+
76
+
77
+ def handle_tracing_error(error: Exception) -> None:
78
+ """Handle trace export errors with helpful messages.
79
+
80
+ Only logs detailed instructions once to avoid spam.
81
+
82
+ Args:
83
+ error: The export error.
84
+ """
85
+ error_str = str(error).lower()
86
+ if 'permission' in error_str or 'denied' in error_str or '403' in error_str:
87
+ _tracing_error_handler.handle(
88
+ error,
89
+ 'Unable to send traces to Google Cloud.',
90
+ TRACING_HELP_TEXT,
91
+ )
92
+ else:
93
+ logger.error('Error exporting traces to GCP', error=str(error))
94
+
95
+
96
+ def handle_metric_error(error: Exception) -> None:
97
+ """Handle metrics export errors with helpful messages.
98
+
99
+ Only logs detailed instructions once to avoid spam.
100
+
101
+ Args:
102
+ error: The export error.
103
+ """
104
+ error_str = str(error).lower()
105
+ if 'permission' in error_str or 'denied' in error_str or '403' in error_str:
106
+ _metrics_error_handler.handle(
107
+ error,
108
+ 'Unable to send metrics to Google Cloud.',
109
+ METRICS_HELP_TEXT,
110
+ )
111
+ else:
112
+ logger.error('Error exporting metrics to GCP', error=str(error))
@@ -0,0 +1,186 @@
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
+ """Feature telemetry for GCP.
18
+
19
+ This module tracks feature-level metrics (requests, latencies) and logs
20
+ input/output for root spans, matching the JavaScript implementation.
21
+
22
+ Metrics Recorded:
23
+ - genkit/feature/requests: Counter for root span calls
24
+ - genkit/feature/latency: Histogram for root span latency (ms)
25
+
26
+ Cross-Language Parity:
27
+ - JavaScript: js/plugins/google-cloud/src/telemetry/feature.ts
28
+ - Go: go/plugins/googlecloud/feature.go
29
+
30
+ See Also:
31
+ - Cloud Monitoring Custom Metrics: https://cloud.google.com/monitoring/custom-metrics
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import structlog
37
+ from opentelemetry import metrics
38
+ from opentelemetry.sdk.trace import ReadableSpan
39
+
40
+ from genkit.plugin_api import GENKIT_VERSION, to_display_path
41
+
42
+ from .gcp_logger import gcp_logger
43
+ from .utils import (
44
+ create_common_log_attributes,
45
+ extract_error_name,
46
+ truncate,
47
+ truncate_path,
48
+ )
49
+
50
+ logger = structlog.get_logger(__name__)
51
+
52
+ # Lazy-initialized metrics
53
+ _feature_counter: metrics.Counter | None = None
54
+ _feature_latency: metrics.Histogram | None = None
55
+
56
+
57
+ def _get_feature_counter() -> metrics.Counter:
58
+ """Get or create the feature requests counter."""
59
+ global _feature_counter
60
+ if _feature_counter is None:
61
+ meter = metrics.get_meter('genkit')
62
+ _feature_counter = meter.create_counter(
63
+ 'genkit/feature/requests',
64
+ description='Counts calls to genkit features.',
65
+ unit='1',
66
+ )
67
+ return _feature_counter
68
+
69
+
70
+ def _get_feature_latency() -> metrics.Histogram:
71
+ """Get or create the feature latency histogram."""
72
+ global _feature_latency
73
+ if _feature_latency is None:
74
+ meter = metrics.get_meter('genkit')
75
+ _feature_latency = meter.create_histogram(
76
+ 'genkit/feature/latency',
77
+ description='Latencies when calling Genkit features.',
78
+ unit='ms',
79
+ )
80
+ return _feature_latency
81
+
82
+
83
+ class FeaturesTelemetry:
84
+ """Telemetry handler for Genkit features (root spans)."""
85
+
86
+ def tick(
87
+ self,
88
+ span: ReadableSpan,
89
+ log_input_and_output: bool,
90
+ project_id: str | None = None,
91
+ ) -> None:
92
+ """Record telemetry for a feature span.
93
+
94
+ Args:
95
+ span: The span to record telemetry for.
96
+ log_input_and_output: Whether to log input/output.
97
+ project_id: Optional GCP project ID.
98
+ """
99
+ attrs = span.attributes or {}
100
+ name = str(attrs.get('genkit:name', '<unknown>'))
101
+ path = str(attrs.get('genkit:path', ''))
102
+ state = str(attrs.get('genkit:state', ''))
103
+
104
+ # Calculate latency
105
+ latency_ms = 0.0
106
+ if span.end_time and span.start_time:
107
+ latency_ms = (span.end_time - span.start_time) / 1_000_000
108
+
109
+ if state == 'success':
110
+ self._write_feature_success(name, latency_ms)
111
+ elif state == 'error':
112
+ error_name = extract_error_name(list(span.events)) or '<unknown>'
113
+ self._write_feature_failure(name, latency_ms, error_name)
114
+ else:
115
+ logger.warning('Unknown state', state=state)
116
+ return
117
+
118
+ if log_input_and_output:
119
+ input_val = truncate(str(attrs.get('genkit:input', '')))
120
+ output_val = truncate(str(attrs.get('genkit:output', '')))
121
+ session_id = str(attrs.get('genkit:sessionId', '')) or None
122
+ thread_name = str(attrs.get('genkit:threadName', '')) or None
123
+
124
+ if input_val:
125
+ self._write_log(span, 'Input', name, path, input_val, project_id, session_id, thread_name)
126
+ if output_val:
127
+ self._write_log(span, 'Output', name, path, output_val, project_id, session_id, thread_name)
128
+
129
+ def _write_feature_success(self, feature_name: str, latency_ms: float) -> None:
130
+ """Record success metrics for a feature."""
131
+ dimensions = {
132
+ 'name': feature_name[:256],
133
+ 'status': 'success',
134
+ 'source': 'py',
135
+ 'sourceVersion': GENKIT_VERSION,
136
+ }
137
+ _get_feature_counter().add(1, dimensions)
138
+ _get_feature_latency().record(latency_ms, dimensions)
139
+
140
+ def _write_feature_failure(
141
+ self,
142
+ feature_name: str,
143
+ latency_ms: float,
144
+ error_name: str,
145
+ ) -> None:
146
+ """Record failure metrics for a feature."""
147
+ dimensions = {
148
+ 'name': feature_name[:256],
149
+ 'status': 'failure',
150
+ 'source': 'py',
151
+ 'sourceVersion': GENKIT_VERSION,
152
+ 'error': error_name[:256],
153
+ }
154
+ _get_feature_counter().add(1, dimensions)
155
+ _get_feature_latency().record(latency_ms, dimensions)
156
+
157
+ def _write_log(
158
+ self,
159
+ span: ReadableSpan,
160
+ tag: str,
161
+ feature_name: str,
162
+ qualified_path: str,
163
+ content: str,
164
+ project_id: str | None,
165
+ session_id: str | None,
166
+ thread_name: str | None,
167
+ ) -> None:
168
+ """Write a structured log entry to Cloud Logging."""
169
+ path = truncate_path(to_display_path(qualified_path))
170
+ metadata = {
171
+ **create_common_log_attributes(span, project_id),
172
+ 'path': path,
173
+ 'qualifiedPath': qualified_path,
174
+ 'featureName': feature_name,
175
+ 'content': content,
176
+ }
177
+ if session_id:
178
+ metadata['sessionId'] = session_id
179
+ if thread_name:
180
+ metadata['threadName'] = thread_name
181
+
182
+ gcp_logger.log_structured(f'{tag}[{path}, {feature_name}]', metadata)
183
+
184
+
185
+ # Singleton instance
186
+ features_telemetry = FeaturesTelemetry()