telemetry-dev-google-genai 0.2.2__tar.gz → 0.2.3__tar.gz
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.
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/PKG-INFO +4 -4
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/README.md +3 -3
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/pyproject.toml +1 -1
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/pyproject.toml.orig +1 -1
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/src/telemetry_dev_google_genai/__init__.py +399 -81
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/LICENSE +0 -0
- {telemetry_dev_google_genai-0.2.2 → telemetry_dev_google_genai-0.2.3}/src/telemetry_dev_google_genai/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: telemetry-dev-google-genai
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: Google GenAI (Gemini) integration for telemetry.dev Python SDK
|
|
5
5
|
Keywords: telemetry,opentelemetry,gemini,google-genai,llm,genai,tracing
|
|
6
6
|
Author: telemetry.dev
|
|
@@ -120,13 +120,13 @@ The integration maps native Gemini request/response shapes directly. It never mu
|
|
|
120
120
|
|
|
121
121
|
Block, safety, grounding, and URL-context metadata are raw attributes, which the core's `capture_output` check and mask never see. The block reason message is free text. Grounding metadata repeats the answer text segment by segment and can carry retrieved document text, source titles and URIs, and search queries; URL-context metadata lists the retrieved URLs. This metadata is recorded whole only when output is captured and no mask is configured. Otherwise `google_genai.response.block_reason_message` is omitted and the other attributes keep only their structure: the block reason; each safety rating's category, probability, severity, their scores, `blocked`, and overwritten threshold, with enum fields kept only when they look like an enum value (such as `HARM_CATEGORY_HARASSMENT`); each grounding chunk's source type (such as `{"web": {}}`), segment offsets, chunk indices, confidence scores, and the dynamic retrieval score; and each URL's retrieval status.
|
|
122
122
|
|
|
123
|
-
Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `capture_input`, the mask, and `max_attribute_length=0` do not remove them.
|
|
123
|
+
Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `capture_input`, the mask, and `max_attribute_length=0` do not remove them. Like other raw attributes, they are cut at `max_attribute_length` without a marker, and are sent whole when `max_attribute_length` is 0 or `None` (the default). With `telemetry-dev` 0.3.2 or earlier, they are cut at 65,536 characters by default and when `max_attribute_length` is 0; those versions do not accept `None`.
|
|
124
124
|
|
|
125
125
|
## Streaming
|
|
126
126
|
|
|
127
127
|
Gemini streams already include cumulative `usage_metadata` on chunks, so no request injection is needed. Stream spans record time-to-first-chunk, aggregate text parts (merging consecutive text with the same `thought` flag), last-seen usage/finish reasons, and end once when the stream completes, errors, or is closed.
|
|
128
128
|
|
|
129
|
-
Stream reconstruction
|
|
129
|
+
Stream reconstruction, shared with streamed safety, grounding, and URL-context metadata, is kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. Media request inputs are retained up to 16 MiB. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs. A stream that is cut at its bound, closed early, or fails sets `telemetry.dev.capture.truncated`. A chunk that fails to map is reported to `on_error`; only the first such failure of a stream is reported. Any other failure while a chunk is recorded, such as in its response ID, model version, candidate index or role, parts, or finish reasons, also sets the attribute, and no later part is kept; parts of that chunk recorded before the failure are kept. A failure in a chunk's time to first chunk, response ID and model version for the span, or output-chunk timing loses only that value and does not set the attribute. A failure in usage loses only that value and does not set the attribute. A failure in a candidate's safety ratings, grounding or URL-context metadata can lose all of that candidate's metadata from that chunk, and a failure in prompt feedback can lose all of that chunk's prompt feedback (block reason, its message, and prompt safety ratings); the output stays whole. Such a failure sets the attribute when that metadata is recorded whole (output captured and no mask configured), as a value dropped by the bound does, and not when only its structure is kept. The AFC history is the only record of the tool calls and their results, so a failure while it is recorded sets the attribute, also with a mask configured. The history is not output, so the output is kept whole and is not withheld by a mask; the history kept from an earlier chunk, if any, is exported, and a later history that maps replaces it. A stream whose fields fail to map when it ends exports no output and sets the attribute. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value.
|
|
130
130
|
|
|
131
131
|
## Automatic function calling (AFC)
|
|
132
132
|
|
|
@@ -143,7 +143,7 @@ Embedding calls emit `gen_ai.operation.name = "embeddings"`, request model/input
|
|
|
143
143
|
|
|
144
144
|
## Fail-open guarantee
|
|
145
145
|
|
|
146
|
-
Mapping code is defensive; wrapped calls return the SDK response unchanged and re-raise exceptions untouched. Telemetry bugs never break callers.
|
|
146
|
+
Mapping code is defensive; wrapped calls return the SDK response unchanged and re-raise exceptions untouched. Telemetry bugs never break callers. When the response of a successful `generate_content`, `embed_content`, image, or video call fails to map, the failure is reported to `on_error` and the span ends without output and with `telemetry.dev.capture.truncated`; it is not marked failed.
|
|
147
147
|
|
|
148
148
|
## Limitations
|
|
149
149
|
|
|
@@ -97,13 +97,13 @@ The integration maps native Gemini request/response shapes directly. It never mu
|
|
|
97
97
|
|
|
98
98
|
Block, safety, grounding, and URL-context metadata are raw attributes, which the core's `capture_output` check and mask never see. The block reason message is free text. Grounding metadata repeats the answer text segment by segment and can carry retrieved document text, source titles and URIs, and search queries; URL-context metadata lists the retrieved URLs. This metadata is recorded whole only when output is captured and no mask is configured. Otherwise `google_genai.response.block_reason_message` is omitted and the other attributes keep only their structure: the block reason; each safety rating's category, probability, severity, their scores, `blocked`, and overwritten threshold, with enum fields kept only when they look like an enum value (such as `HARM_CATEGORY_HARASSMENT`); each grounding chunk's source type (such as `{"web": {}}`), segment offsets, chunk indices, confidence scores, and the dynamic retrieval score; and each URL's retrieval status.
|
|
99
99
|
|
|
100
|
-
Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `capture_input`, the mask, and `max_attribute_length=0` do not remove them.
|
|
100
|
+
Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `capture_input`, the mask, and `max_attribute_length=0` do not remove them. Like other raw attributes, they are cut at `max_attribute_length` without a marker, and are sent whole when `max_attribute_length` is 0 or `None` (the default). With `telemetry-dev` 0.3.2 or earlier, they are cut at 65,536 characters by default and when `max_attribute_length` is 0; those versions do not accept `None`.
|
|
101
101
|
|
|
102
102
|
## Streaming
|
|
103
103
|
|
|
104
104
|
Gemini streams already include cumulative `usage_metadata` on chunks, so no request injection is needed. Stream spans record time-to-first-chunk, aggregate text parts (merging consecutive text with the same `thought` flag), last-seen usage/finish reasons, and end once when the stream completes, errors, or is closed.
|
|
105
105
|
|
|
106
|
-
Stream reconstruction
|
|
106
|
+
Stream reconstruction, shared with streamed safety, grounding, and URL-context metadata, is kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. Media request inputs are retained up to 16 MiB. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs. A stream that is cut at its bound, closed early, or fails sets `telemetry.dev.capture.truncated`. A chunk that fails to map is reported to `on_error`; only the first such failure of a stream is reported. Any other failure while a chunk is recorded, such as in its response ID, model version, candidate index or role, parts, or finish reasons, also sets the attribute, and no later part is kept; parts of that chunk recorded before the failure are kept. A failure in a chunk's time to first chunk, response ID and model version for the span, or output-chunk timing loses only that value and does not set the attribute. A failure in usage loses only that value and does not set the attribute. A failure in a candidate's safety ratings, grounding or URL-context metadata can lose all of that candidate's metadata from that chunk, and a failure in prompt feedback can lose all of that chunk's prompt feedback (block reason, its message, and prompt safety ratings); the output stays whole. Such a failure sets the attribute when that metadata is recorded whole (output captured and no mask configured), as a value dropped by the bound does, and not when only its structure is kept. The AFC history is the only record of the tool calls and their results, so a failure while it is recorded sets the attribute, also with a mask configured. The history is not output, so the output is kept whole and is not withheld by a mask; the history kept from an earlier chunk, if any, is exported, and a later history that maps replaces it. A stream whose fields fail to map when it ends exports no output and sets the attribute. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value.
|
|
107
107
|
|
|
108
108
|
## Automatic function calling (AFC)
|
|
109
109
|
|
|
@@ -120,7 +120,7 @@ Embedding calls emit `gen_ai.operation.name = "embeddings"`, request model/input
|
|
|
120
120
|
|
|
121
121
|
## Fail-open guarantee
|
|
122
122
|
|
|
123
|
-
Mapping code is defensive; wrapped calls return the SDK response unchanged and re-raise exceptions untouched. Telemetry bugs never break callers.
|
|
123
|
+
Mapping code is defensive; wrapped calls return the SDK response unchanged and re-raise exceptions untouched. Telemetry bugs never break callers. When the response of a successful `generate_content`, `embed_content`, image, or video call fails to map, the failure is reported to `on_error` and the span ends without output and with `telemetry.dev.capture.truncated`; it is not marked failed.
|
|
124
124
|
|
|
125
125
|
## Limitations
|
|
126
126
|
|
|
@@ -8,12 +8,14 @@ from __future__ import annotations
|
|
|
8
8
|
|
|
9
9
|
import contextvars
|
|
10
10
|
import json
|
|
11
|
+
import os
|
|
11
12
|
import re
|
|
12
13
|
import threading
|
|
13
14
|
import time
|
|
14
15
|
from collections import OrderedDict
|
|
15
16
|
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping, Sequence
|
|
16
17
|
from functools import wraps
|
|
18
|
+
from io import StringIO
|
|
17
19
|
from typing import Any, TypeVar, cast
|
|
18
20
|
from weakref import WeakKeyDictionary
|
|
19
21
|
|
|
@@ -24,7 +26,7 @@ from google.genai.models import AsyncModels, Models
|
|
|
24
26
|
from google.genai.operations import AsyncOperations, Operations
|
|
25
27
|
from telemetry_dev._serialize import json_dumps
|
|
26
28
|
|
|
27
|
-
__version__ = "0.2.
|
|
29
|
+
__version__ = "0.2.3"
|
|
28
30
|
|
|
29
31
|
ProviderResolver = Callable[[object | None], str]
|
|
30
32
|
RequestMapper = Callable[[Any, Any, Any], tuple[str, dict[str, Any]]]
|
|
@@ -35,14 +37,29 @@ _ORIGINAL_ATTR = "_telemetry_dev_google_genai_original"
|
|
|
35
37
|
_ORIGINALS: list[tuple[type[Any], str, Any]] = []
|
|
36
38
|
_installed = False
|
|
37
39
|
_install_lock = threading.Lock()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _reset_install_lock_in_child() -> None:
|
|
43
|
+
"""A thread of the parent can hold the lock at a fork, and only this thread exists here."""
|
|
44
|
+
global _install_lock
|
|
45
|
+
_install_lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# A hook is enough: a fork that runs no hooks, as uWSGI's fork of its workers by default,
|
|
49
|
+
# starts from its master, which serves no requests. os.register_at_fork cannot remove a hook,
|
|
50
|
+
# and importlib.reload runs this module again with the same globals, so the hook of the first
|
|
51
|
+
# run stays. Windows has no fork.
|
|
52
|
+
if hasattr(os, "register_at_fork") and "_install_fork_hook" not in globals():
|
|
53
|
+
_install_fork_hook = True
|
|
54
|
+
os.register_at_fork(after_in_child=_reset_install_lock_in_child)
|
|
55
|
+
|
|
38
56
|
_T = TypeVar("_T")
|
|
39
57
|
_AFC_USAGE_STATE: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar(
|
|
40
58
|
"telemetry_dev_google_genai_afc_usage_state", default=None
|
|
41
59
|
)
|
|
42
60
|
_MAX_PENDING_VIDEO_OPERATIONS = 1024
|
|
43
61
|
_MAX_CAPTURE_DEPTH = 32
|
|
44
|
-
#
|
|
45
|
-
_STREAM_CAPTURE_MAX_BYTES = 48 * 1024
|
|
62
|
+
# The core applies max_attribute_length after the mask. More candidates than this are not kept.
|
|
46
63
|
_STREAM_CAPTURE_MAX_ITEMS = 1000
|
|
47
64
|
# Retained finish reasons stay outside the output budget so a terminal one is still exported,
|
|
48
65
|
# so each is capped instead. Gemini's longest is 25 characters.
|
|
@@ -204,8 +221,11 @@ def _record_afc_usage(response: Any) -> Any:
|
|
|
204
221
|
state["tool_use_prompt_tokens"] = int(state.get("tool_use_prompt_tokens", 0)) + int(
|
|
205
222
|
tool_use
|
|
206
223
|
)
|
|
207
|
-
except Exception:
|
|
208
|
-
|
|
224
|
+
except Exception as exc:
|
|
225
|
+
# The turn's usage is lost, so the call's usage is undercounted; its output is not cut.
|
|
226
|
+
report_error = state.get("report_error")
|
|
227
|
+
if callable(report_error):
|
|
228
|
+
report_error(exc)
|
|
209
229
|
return response
|
|
210
230
|
|
|
211
231
|
|
|
@@ -241,11 +261,26 @@ def _clean_fields(fields: Mapping[str, Any]) -> dict[str, Any]:
|
|
|
241
261
|
return {key: value for key, value in fields.items() if value is not None}
|
|
242
262
|
|
|
243
263
|
|
|
244
|
-
def _safe_fields(
|
|
264
|
+
def _safe_fields(
|
|
265
|
+
mapper: ResponseMapper,
|
|
266
|
+
response: Any,
|
|
267
|
+
handle: telemetry_dev.SpanHandle | None,
|
|
268
|
+
report_error: Callable[[BaseException], None] | None = None,
|
|
269
|
+
) -> dict[str, Any]:
|
|
245
270
|
try:
|
|
246
271
|
return mapper(response)
|
|
247
|
-
except Exception:
|
|
248
|
-
|
|
272
|
+
except Exception as exc:
|
|
273
|
+
if report_error is not None:
|
|
274
|
+
report_error(exc)
|
|
275
|
+
elif handle is not None:
|
|
276
|
+
_stream_span_reporter(handle)(exc)
|
|
277
|
+
else:
|
|
278
|
+
# A finished video operation is ended where its span handle is not kept.
|
|
279
|
+
client = telemetry_dev.get_client()
|
|
280
|
+
if client is not None:
|
|
281
|
+
client.report("provider instrumentation failed", exc)
|
|
282
|
+
# The call succeeded, so it is not failed; its output and response fields are lost.
|
|
283
|
+
return {"attributes": {_CAPTURE_TRUNCATED_ATTRIBUTE: True}}
|
|
249
284
|
|
|
250
285
|
|
|
251
286
|
def _end_once(handle: telemetry_dev.SpanHandle) -> Callable[..., None]:
|
|
@@ -473,10 +508,25 @@ class _VideoOperationTracker:
|
|
|
473
508
|
self._pending: OrderedDict[tuple[object, str], tuple[str, Callable[..., None]]] = (
|
|
474
509
|
OrderedDict()
|
|
475
510
|
)
|
|
476
|
-
|
|
511
|
+
# The lock of each process, by process ID. A fork can copy the lock while another thread
|
|
512
|
+
# holds it, and no thread of the child can release the copy. Not a fork hook:
|
|
513
|
+
# os.register_at_fork keeps each hook for good, and each wrapped client has a tracker.
|
|
514
|
+
# Not the lock helper of telemetry-dev: the oldest version this package supports lacks it.
|
|
515
|
+
self._locks = {os.getpid(): threading.Lock()}
|
|
477
516
|
self._closed = False
|
|
478
517
|
self._closed_scopes: WeakKeyDictionary[object, set[str]] = WeakKeyDictionary()
|
|
479
518
|
|
|
519
|
+
def _lock(self) -> threading.Lock:
|
|
520
|
+
pid = os.getpid()
|
|
521
|
+
lock = self._locks.get(pid)
|
|
522
|
+
if lock is None:
|
|
523
|
+
# setdefault, so that threads that get here at the same time share one lock.
|
|
524
|
+
lock = self._locks.setdefault(pid, threading.Lock())
|
|
525
|
+
for other in list(self._locks):
|
|
526
|
+
if other != pid:
|
|
527
|
+
self._locks.pop(other, None)
|
|
528
|
+
return lock
|
|
529
|
+
|
|
480
530
|
def _scope(self, resource: Any) -> object:
|
|
481
531
|
return _field(resource, "_api_client") if self._scoped else self
|
|
482
532
|
|
|
@@ -484,7 +534,7 @@ class _VideoOperationTracker:
|
|
|
484
534
|
evicted: Callable[..., None] | None = None
|
|
485
535
|
closed_error: RuntimeError | None = None
|
|
486
536
|
scope = self._scope(resource)
|
|
487
|
-
with self._lock:
|
|
537
|
+
with self._lock():
|
|
488
538
|
if self._closed:
|
|
489
539
|
closed_error = RuntimeError(
|
|
490
540
|
"Google GenAI instrumentation removed during video operation"
|
|
@@ -505,13 +555,13 @@ class _VideoOperationTracker:
|
|
|
505
555
|
evicted(error=RuntimeError("video operation tracking capacity exceeded"))
|
|
506
556
|
|
|
507
557
|
def take(self, resource: Any, name: str) -> Callable[..., None] | None:
|
|
508
|
-
with self._lock:
|
|
558
|
+
with self._lock():
|
|
509
559
|
pending = self._pending.pop((self._scope(resource), name), None)
|
|
510
560
|
return pending[1] if pending is not None else None
|
|
511
561
|
|
|
512
562
|
def close_scope(self, resource: Any, transport: str) -> None:
|
|
513
563
|
scope = self._scope(resource)
|
|
514
|
-
with self._lock:
|
|
564
|
+
with self._lock():
|
|
515
565
|
self._closed_scopes.setdefault(scope, set()).add(transport)
|
|
516
566
|
pending: list[Callable[..., None]] = []
|
|
517
567
|
for key, (pending_transport, end) in list(self._pending.items()):
|
|
@@ -522,7 +572,7 @@ class _VideoOperationTracker:
|
|
|
522
572
|
end(error=RuntimeError("Google GenAI client closed during video operation"))
|
|
523
573
|
|
|
524
574
|
def close(self) -> None:
|
|
525
|
-
with self._lock:
|
|
575
|
+
with self._lock():
|
|
526
576
|
if self._closed:
|
|
527
577
|
return
|
|
528
578
|
self._closed = True
|
|
@@ -642,7 +692,7 @@ def _record_candidate_metadata(
|
|
|
642
692
|
index: int,
|
|
643
693
|
attrs: dict[str, Any],
|
|
644
694
|
metadata_content: bool,
|
|
645
|
-
|
|
695
|
+
accept: Callable[[str, str], bool] | None = None,
|
|
646
696
|
) -> None:
|
|
647
697
|
ratings = _field(candidate, "safety_ratings")
|
|
648
698
|
if ratings:
|
|
@@ -656,25 +706,36 @@ def _record_candidate_metadata(
|
|
|
656
706
|
entries = []
|
|
657
707
|
else:
|
|
658
708
|
entries = []
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
)
|
|
709
|
+
entry = {
|
|
710
|
+
"candidateIndex": index,
|
|
711
|
+
"ratings": _metadata(ratings, _SAFETY_RATINGS_STRUCTURE, metadata_content),
|
|
712
|
+
}
|
|
713
|
+
# A stream repeats a candidate's ratings on later chunks; the latest replaces them.
|
|
714
|
+
for at, existing_entry in enumerate(entries):
|
|
715
|
+
if isinstance(existing_entry, dict) and existing_entry.get("candidateIndex") == index:
|
|
716
|
+
entries[at] = entry
|
|
717
|
+
break
|
|
718
|
+
else:
|
|
719
|
+
entries.append(entry)
|
|
665
720
|
encoded = _json_attr(entries)
|
|
666
|
-
if encoded is not None and (
|
|
721
|
+
if encoded is not None and (
|
|
722
|
+
accept is None or accept("google_genai.response.safety_ratings", encoded)
|
|
723
|
+
):
|
|
667
724
|
attrs["google_genai.response.safety_ratings"] = encoded
|
|
668
725
|
if index == 0:
|
|
669
726
|
grounding = _field(candidate, "grounding_metadata")
|
|
670
727
|
if grounding is not None:
|
|
671
728
|
encoded = _metadata_attr(grounding, _GROUNDING_STRUCTURE, metadata_content)
|
|
672
|
-
if encoded is not None and (
|
|
729
|
+
if encoded is not None and (
|
|
730
|
+
accept is None or accept("google_genai.response.grounding_metadata", encoded)
|
|
731
|
+
):
|
|
673
732
|
attrs["google_genai.response.grounding_metadata"] = encoded
|
|
674
733
|
url_context = _field(candidate, "url_context_metadata")
|
|
675
734
|
if url_context is not None:
|
|
676
735
|
encoded = _metadata_attr(url_context, _URL_CONTEXT_STRUCTURE, metadata_content)
|
|
677
|
-
if encoded is not None and (
|
|
736
|
+
if encoded is not None and (
|
|
737
|
+
accept is None or accept("google_genai.response.url_context_metadata", encoded)
|
|
738
|
+
):
|
|
678
739
|
attrs["google_genai.response.url_context_metadata"] = encoded
|
|
679
740
|
|
|
680
741
|
|
|
@@ -777,15 +838,94 @@ def _embed_response_fields(response: Any) -> dict[str, Any]:
|
|
|
777
838
|
return fields
|
|
778
839
|
|
|
779
840
|
|
|
841
|
+
# On Python 3.10 and 3.11, StringIO keeps up to 100,000 written strings in a list before it
|
|
842
|
+
# joins them, about 60 bytes each that the stream bound does not charge: 15 bytes a character
|
|
843
|
+
# for 4-character deltas. Deltas are joined 256 at a time, so that those waiting hold under
|
|
844
|
+
# about 22 KB, onto a string that is written once it has 4,096 characters, so that what is
|
|
845
|
+
# written costs about 1.5% more than its text. Python 3.12 dropped the list.
|
|
846
|
+
_DELTA_BATCH = 256
|
|
847
|
+
_WRITE_CHARS = 4096
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
class _DeltaBuffer:
|
|
851
|
+
# A write takes several steps, unlike one StringIO call, so without the lock a read on
|
|
852
|
+
# another thread, such as one that closes the stream, could copy a batch twice or drop it.
|
|
853
|
+
# A fork copies the lock held if another thread was writing, and that thread does not run
|
|
854
|
+
# in the child to release it. Every fork, also one that runs no at-fork hooks, changes the
|
|
855
|
+
# process ID, so a child takes a new lock. The check is inline because it runs per delta.
|
|
856
|
+
# A signal handler runs on the thread it interrupts, so one that reads the stream, such as
|
|
857
|
+
# one that closes it, can read inside a write. So the lock is reentrant, and each step takes
|
|
858
|
+
# the deltas and the tail out of the buffer before it joins or writes them, so that a read
|
|
859
|
+
# inside the step does not write them as well; that read returns a prefix, which can leave
|
|
860
|
+
# out the deltas being joined. A handler that writes inside a step is not supported. An
|
|
861
|
+
# exception inside a step, such as KeyboardInterrupt from a handler, puts back the text the
|
|
862
|
+
# step took unless the StringIO has it, so that a later read still has every delta.
|
|
863
|
+
__slots__ = ("_buffer", "_lock", "_pending", "_pid", "_tail")
|
|
864
|
+
|
|
865
|
+
def __init__(self) -> None:
|
|
866
|
+
self._buffer = StringIO()
|
|
867
|
+
self._lock = threading.RLock()
|
|
868
|
+
self._pid = os.getpid()
|
|
869
|
+
self._pending: list[str] = []
|
|
870
|
+
self._tail = ""
|
|
871
|
+
|
|
872
|
+
def write(self, text: str) -> None:
|
|
873
|
+
pid = os.getpid()
|
|
874
|
+
if self._pid != pid:
|
|
875
|
+
self._lock = threading.RLock()
|
|
876
|
+
self._pid = pid
|
|
877
|
+
with self._lock:
|
|
878
|
+
self._pending.append(text)
|
|
879
|
+
if len(self._pending) >= _DELTA_BATCH:
|
|
880
|
+
self._join(_WRITE_CHARS)
|
|
881
|
+
|
|
882
|
+
def getvalue(self) -> str:
|
|
883
|
+
pid = os.getpid()
|
|
884
|
+
if self._pid != pid:
|
|
885
|
+
self._lock = threading.RLock()
|
|
886
|
+
self._pid = pid
|
|
887
|
+
with self._lock:
|
|
888
|
+
self._join(1)
|
|
889
|
+
return self._buffer.getvalue()
|
|
890
|
+
|
|
891
|
+
def _join(self, write_at: int) -> None:
|
|
892
|
+
if not self._pending and len(self._tail) < write_at:
|
|
893
|
+
return
|
|
894
|
+
written = self._buffer.tell()
|
|
895
|
+
pending: list[str] = []
|
|
896
|
+
tail = ""
|
|
897
|
+
try:
|
|
898
|
+
pending, self._pending = self._pending, []
|
|
899
|
+
tail, self._tail = self._tail, ""
|
|
900
|
+
joined = "".join([tail, *pending])
|
|
901
|
+
if len(joined) >= write_at:
|
|
902
|
+
self._buffer.write(joined)
|
|
903
|
+
else:
|
|
904
|
+
self._tail = joined
|
|
905
|
+
except BaseException:
|
|
906
|
+
if self._buffer.tell() == written:
|
|
907
|
+
self._pending[:0] = pending
|
|
908
|
+
self._tail = tail + self._tail
|
|
909
|
+
raise
|
|
910
|
+
|
|
911
|
+
|
|
780
912
|
class _CandidateState:
|
|
781
913
|
def __init__(self) -> None:
|
|
782
914
|
self.role = "model"
|
|
783
915
|
self.parts: list[Any] = []
|
|
916
|
+
# The text of parts[-1] while later deltas extend it: repeated concatenation copies the
|
|
917
|
+
# whole text for each delta. _candidate_parts writes it back.
|
|
918
|
+
self.text_fragments: _DeltaBuffer | None = None
|
|
784
919
|
|
|
785
920
|
|
|
786
921
|
class _StreamState:
|
|
787
|
-
def __init__(
|
|
922
|
+
def __init__(
|
|
923
|
+
self,
|
|
924
|
+
metadata_content: bool = False,
|
|
925
|
+
report_error: Callable[[BaseException], None] = lambda _cause: None,
|
|
926
|
+
) -> None:
|
|
788
927
|
self.metadata_content = metadata_content
|
|
928
|
+
self.report_error = report_error
|
|
789
929
|
self.candidates: dict[int, _CandidateState] = {}
|
|
790
930
|
self.finish_reasons: dict[int, str] = {}
|
|
791
931
|
self.usage: dict[str, int | float] | None = None
|
|
@@ -795,10 +935,61 @@ class _StreamState:
|
|
|
795
935
|
self.committed_usage: dict[str, int | float] | None = None
|
|
796
936
|
self.prior_contents: list[dict[str, Any]] = []
|
|
797
937
|
self.afc_history: Any = None
|
|
798
|
-
self.budget =
|
|
799
|
-
|
|
800
|
-
|
|
938
|
+
self.budget = _stream_budget()
|
|
939
|
+
# The bytes charged for each value that a chunk replaces whole, by key.
|
|
940
|
+
self.replaced_bytes: dict[str, int] = {}
|
|
801
941
|
self.output_truncated = False
|
|
942
|
+
# Set when response content outside the output is lost: metadata kept as response
|
|
943
|
+
# content (metadata_content), or the AFC history. It flags the capture without cutting
|
|
944
|
+
# the output or withholding it from a mask.
|
|
945
|
+
self.metadata_lost = False
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def _reserve_bytes(budget: telemetry_dev.CaptureBudget, total: int) -> bool:
|
|
949
|
+
# Older cores have no reserve_bytes; there the measure against max_bytes stands.
|
|
950
|
+
reserve = getattr(budget, "reserve_bytes", None)
|
|
951
|
+
if callable(reserve):
|
|
952
|
+
return bool(reserve(total))
|
|
953
|
+
if total > budget.max_bytes:
|
|
954
|
+
return False
|
|
955
|
+
budget.bytes_used = total
|
|
956
|
+
return True
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def _accept_replacement(state: _StreamState, key: str, value: Any) -> bool:
|
|
960
|
+
"""Charges ``value`` to the stream in place of the value charged under ``key`` before: each
|
|
961
|
+
chunk repeats the whole AFC history and metadata, which replace the last ones."""
|
|
962
|
+
budget = state.budget
|
|
963
|
+
if budget.truncated:
|
|
964
|
+
return False
|
|
965
|
+
measured = telemetry_dev.CaptureBudget()
|
|
966
|
+
held = state.replaced_bytes.get(key, 0)
|
|
967
|
+
if not measured.accept(value) or not _reserve_bytes(
|
|
968
|
+
budget, budget.bytes_used - held + measured.bytes_used
|
|
969
|
+
):
|
|
970
|
+
budget.truncated = True
|
|
971
|
+
return False
|
|
972
|
+
state.replaced_bytes[key] = measured.bytes_used
|
|
973
|
+
return True
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def _stream_budget() -> telemetry_dev.CaptureBudget:
|
|
977
|
+
# Older cores have no for_stream and bound each budget at 64 KiB on its own.
|
|
978
|
+
for_stream = getattr(telemetry_dev.CaptureBudget, "for_stream", None)
|
|
979
|
+
budget = for_stream() if callable(for_stream) else telemetry_dev.CaptureBudget()
|
|
980
|
+
return cast(telemetry_dev.CaptureBudget, budget)
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def _ending_stream(end: Callable[..., None], state: _StreamState) -> Callable[..., None]:
|
|
984
|
+
def end_stream(**fields: Any) -> None:
|
|
985
|
+
try:
|
|
986
|
+
end(**fields)
|
|
987
|
+
finally:
|
|
988
|
+
release = getattr(state.budget, "release", None)
|
|
989
|
+
if callable(release):
|
|
990
|
+
release()
|
|
991
|
+
|
|
992
|
+
return end_stream
|
|
802
993
|
|
|
803
994
|
|
|
804
995
|
def _capture_masked(handle: telemetry_dev.SpanHandle) -> bool:
|
|
@@ -821,7 +1012,7 @@ def _capture_metadata_content(handle: telemetry_dev.SpanHandle) -> bool:
|
|
|
821
1012
|
def _mark_stream_capture(
|
|
822
1013
|
fields: dict[str, Any], state: _StreamState, *, completed: bool, mask_output: bool
|
|
823
1014
|
) -> dict[str, Any]:
|
|
824
|
-
if completed and not state.budget.truncated:
|
|
1015
|
+
if completed and not state.budget.truncated and not state.metadata_lost:
|
|
825
1016
|
return fields
|
|
826
1017
|
attributes = fields.get("attributes")
|
|
827
1018
|
fields["attributes"] = {
|
|
@@ -833,22 +1024,32 @@ def _mark_stream_capture(
|
|
|
833
1024
|
return fields
|
|
834
1025
|
|
|
835
1026
|
|
|
836
|
-
def _append_part(
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
1027
|
+
def _append_part(state: _CandidateState, native: Any) -> None:
|
|
1028
|
+
parts = state.parts
|
|
1029
|
+
if isinstance(native, dict):
|
|
1030
|
+
text = native.get("text")
|
|
1031
|
+
if text is not None:
|
|
1032
|
+
thought = native.get("thought", False)
|
|
1033
|
+
if parts:
|
|
1034
|
+
previous = parts[-1]
|
|
1035
|
+
if isinstance(previous, dict) and previous.get("text") is not None:
|
|
1036
|
+
if previous.get("thought", False) == thought:
|
|
1037
|
+
if state.text_fragments is None:
|
|
1038
|
+
state.text_fragments = _DeltaBuffer()
|
|
1039
|
+
state.text_fragments.write(f"{previous.get('text', '')}")
|
|
1040
|
+
state.text_fragments.write(f"{text}")
|
|
1041
|
+
return
|
|
1042
|
+
_candidate_parts(state)
|
|
1043
|
+
state.text_fragments = None
|
|
849
1044
|
parts.append(native)
|
|
850
1045
|
|
|
851
1046
|
|
|
1047
|
+
def _candidate_parts(state: _CandidateState) -> list[Any]:
|
|
1048
|
+
if state.text_fragments is not None:
|
|
1049
|
+
state.parts[-1]["text"] = state.text_fragments.getvalue()
|
|
1050
|
+
return state.parts
|
|
1051
|
+
|
|
1052
|
+
|
|
852
1053
|
def _fold_turn(state: _StreamState) -> None:
|
|
853
1054
|
# An AFC turn ended: archive its output and fold its usage so the next
|
|
854
1055
|
# internal model call does not overwrite what this turn produced.
|
|
@@ -856,7 +1057,7 @@ def _fold_turn(state: _StreamState) -> None:
|
|
|
856
1057
|
candidate_state = state.candidates[index]
|
|
857
1058
|
if candidate_state.parts:
|
|
858
1059
|
state.prior_contents.append(
|
|
859
|
-
{"role": candidate_state.role, "parts": candidate_state
|
|
1060
|
+
{"role": candidate_state.role, "parts": _candidate_parts(candidate_state)}
|
|
860
1061
|
)
|
|
861
1062
|
state.candidates.clear()
|
|
862
1063
|
state.finish_reasons.clear()
|
|
@@ -864,11 +1065,37 @@ def _fold_turn(state: _StreamState) -> None:
|
|
|
864
1065
|
state.usage = None
|
|
865
1066
|
|
|
866
1067
|
|
|
1068
|
+
def _stream_span_reporter(
|
|
1069
|
+
handle: telemetry_dev.SpanHandle,
|
|
1070
|
+
) -> Callable[[BaseException], None]:
|
|
1071
|
+
reported = False
|
|
1072
|
+
|
|
1073
|
+
# One report per stream: a mapper that fails on one chunk likely fails on each one after it.
|
|
1074
|
+
def report(cause: BaseException) -> None:
|
|
1075
|
+
nonlocal reported
|
|
1076
|
+
if reported:
|
|
1077
|
+
return
|
|
1078
|
+
reported = True
|
|
1079
|
+
try:
|
|
1080
|
+
handle.report_error(cause)
|
|
1081
|
+
except Exception:
|
|
1082
|
+
return
|
|
1083
|
+
|
|
1084
|
+
return report
|
|
1085
|
+
|
|
1086
|
+
|
|
867
1087
|
def _record_chunk(chunk: Any, state: _StreamState) -> None:
|
|
868
1088
|
try:
|
|
869
1089
|
_record_chunk_inner(chunk, state)
|
|
870
|
-
except Exception:
|
|
871
|
-
|
|
1090
|
+
except Exception as exc:
|
|
1091
|
+
# Candidate metadata, usage, prompt feedback and the function-calling history are
|
|
1092
|
+
# guarded where they are recorded. Any other failure, such as one in the response ID,
|
|
1093
|
+
# model version or finish reason, may stop the chunk before some of its parts, or those
|
|
1094
|
+
# of a later candidate, are recorded. The truncated budget keeps no later part, so the
|
|
1095
|
+
# output stays a prefix of the stream.
|
|
1096
|
+
state.budget.truncated = True
|
|
1097
|
+
state.output_truncated = True
|
|
1098
|
+
state.report_error(exc)
|
|
872
1099
|
|
|
873
1100
|
|
|
874
1101
|
def _record_chunk_inner(chunk: Any, state: _StreamState) -> None:
|
|
@@ -898,18 +1125,58 @@ def _record_chunk_inner(chunk: Any, state: _StreamState) -> None:
|
|
|
898
1125
|
for part in _sequence_items(_field(content, "parts")):
|
|
899
1126
|
native = _native(part)
|
|
900
1127
|
if state.budget.accept(native):
|
|
901
|
-
_append_part(candidate_state
|
|
1128
|
+
_append_part(candidate_state, native)
|
|
902
1129
|
else:
|
|
903
1130
|
state.output_truncated = True
|
|
904
1131
|
finish = _enum_value(_field(candidate, "finish_reason"))
|
|
905
1132
|
if finish is not None:
|
|
906
1133
|
state.finish_reasons[candidate_index] = finish[:_FINISH_REASON_MAX_LENGTH]
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1134
|
+
try:
|
|
1135
|
+
_record_candidate_metadata(
|
|
1136
|
+
candidate,
|
|
1137
|
+
candidate_index,
|
|
1138
|
+
state.attrs,
|
|
1139
|
+
state.metadata_content,
|
|
1140
|
+
lambda key, value: _accept_replacement(state, key, value),
|
|
1141
|
+
)
|
|
1142
|
+
except Exception as exc:
|
|
1143
|
+
_lose_metadata(state, exc)
|
|
1144
|
+
try:
|
|
1145
|
+
_record_chunk_usage(chunk, state)
|
|
1146
|
+
except Exception as exc:
|
|
1147
|
+
state.report_error(exc)
|
|
1148
|
+
try:
|
|
1149
|
+
_record_prompt_feedback(chunk, state)
|
|
1150
|
+
except Exception as exc:
|
|
1151
|
+
_lose_metadata(state, exc)
|
|
1152
|
+
try:
|
|
1153
|
+
_record_afc_history(chunk, state)
|
|
1154
|
+
except Exception as exc:
|
|
1155
|
+
# The history is the only record of the tool calls and their results, so losing it
|
|
1156
|
+
# flags the capture whether or not a mask is configured. It is not output, so the
|
|
1157
|
+
# output is not cut; the last history that mapped, if any, is kept, and a later one
|
|
1158
|
+
# that maps replaces it.
|
|
1159
|
+
state.metadata_lost = True
|
|
1160
|
+
state.report_error(exc)
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def _lose_metadata(state: _StreamState, cause: BaseException) -> None:
|
|
1164
|
+
# Metadata is not output, so the output stays whole. With metadata_content the metadata is
|
|
1165
|
+
# response content, and its loss flags the capture as the bound does when it drops it.
|
|
1166
|
+
# Without it only the structure is kept, which holds no response content, so its loss is
|
|
1167
|
+
# reported only.
|
|
1168
|
+
if state.metadata_content:
|
|
1169
|
+
state.metadata_lost = True
|
|
1170
|
+
state.report_error(cause)
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
def _record_chunk_usage(chunk: Any, state: _StreamState) -> None:
|
|
910
1174
|
usage = _generate_usage(_field(chunk, "usage_metadata"), state.attrs)
|
|
911
1175
|
if usage:
|
|
912
1176
|
state.usage = usage
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def _record_prompt_feedback(chunk: Any, state: _StreamState) -> None:
|
|
913
1180
|
feedback = _field(chunk, "prompt_feedback")
|
|
914
1181
|
block_reason = _enum_value(_field(feedback, "block_reason"))
|
|
915
1182
|
if block_reason:
|
|
@@ -920,19 +1187,26 @@ def _record_chunk_inner(chunk: Any, state: _StreamState) -> None:
|
|
|
920
1187
|
prompt_ratings = _sequence_items(_field(feedback, "safety_ratings"))
|
|
921
1188
|
if prompt_ratings:
|
|
922
1189
|
encoded = _metadata_attr(prompt_ratings, _SAFETY_RATINGS_STRUCTURE, state.metadata_content)
|
|
923
|
-
|
|
924
|
-
|
|
1190
|
+
key = "google_genai.response.prompt_safety_ratings"
|
|
1191
|
+
if encoded is not None and _accept_replacement(state, key, encoded):
|
|
1192
|
+
state.attrs[key] = encoded
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
def _record_afc_history(chunk: Any, state: _StreamState) -> None:
|
|
925
1196
|
history = _field(chunk, "automatic_function_calling_history")
|
|
926
1197
|
if history:
|
|
927
1198
|
native_history = _native(history)
|
|
928
|
-
if native_history and state
|
|
1199
|
+
if native_history and _accept_replacement(state, "afc_history", native_history):
|
|
929
1200
|
state.afc_history = native_history
|
|
930
1201
|
|
|
931
1202
|
|
|
932
1203
|
def _stream_fields(state: _StreamState) -> dict[str, Any]:
|
|
933
1204
|
try:
|
|
934
1205
|
return _stream_fields_inner(state)
|
|
935
|
-
except Exception:
|
|
1206
|
+
except Exception as exc:
|
|
1207
|
+
# The output that the stream kept is lost.
|
|
1208
|
+
state.budget.truncated = True
|
|
1209
|
+
state.report_error(exc)
|
|
936
1210
|
return {}
|
|
937
1211
|
|
|
938
1212
|
|
|
@@ -948,7 +1222,9 @@ def _stream_fields_inner(state: _StreamState) -> dict[str, Any]:
|
|
|
948
1222
|
for index in sorted(state.candidates):
|
|
949
1223
|
candidate_state = state.candidates[index]
|
|
950
1224
|
if candidate_state.parts:
|
|
951
|
-
output.append(
|
|
1225
|
+
output.append(
|
|
1226
|
+
{"role": candidate_state.role, "parts": _candidate_parts(candidate_state)}
|
|
1227
|
+
)
|
|
952
1228
|
if index in state.finish_reasons:
|
|
953
1229
|
finish_reasons.append(state.finish_reasons[index])
|
|
954
1230
|
if state.afc_history:
|
|
@@ -1007,7 +1283,12 @@ def _start_embed_span(
|
|
|
1007
1283
|
return handle, _end_once(handle), time.perf_counter()
|
|
1008
1284
|
|
|
1009
1285
|
|
|
1010
|
-
def _first_chunk_update(
|
|
1286
|
+
def _first_chunk_update(
|
|
1287
|
+
chunk: Any,
|
|
1288
|
+
handle: telemetry_dev.SpanHandle,
|
|
1289
|
+
started_at: float,
|
|
1290
|
+
report_error: Callable[[BaseException], None],
|
|
1291
|
+
) -> None:
|
|
1011
1292
|
try:
|
|
1012
1293
|
update: dict[str, Any] = {
|
|
1013
1294
|
"time_to_first_chunk_ms": (time.perf_counter() - started_at) * 1000,
|
|
@@ -1019,8 +1300,9 @@ def _first_chunk_update(chunk: Any, handle: telemetry_dev.SpanHandle, started_at
|
|
|
1019
1300
|
if response_model:
|
|
1020
1301
|
update["response_model"] = response_model
|
|
1021
1302
|
handle.update(**_clean_fields(update))
|
|
1022
|
-
except Exception:
|
|
1023
|
-
|
|
1303
|
+
except Exception as exc:
|
|
1304
|
+
# Only the first-chunk timing and IDs are lost; the chunk is still recorded.
|
|
1305
|
+
report_error(exc)
|
|
1024
1306
|
|
|
1025
1307
|
|
|
1026
1308
|
def _chunk_has_output(chunk: Any) -> bool:
|
|
@@ -1077,11 +1359,14 @@ class _ObservedStream:
|
|
|
1077
1359
|
) -> None:
|
|
1078
1360
|
self._inner = inner
|
|
1079
1361
|
self._handle = handle
|
|
1080
|
-
self._end = end
|
|
1081
1362
|
self._started_at = started_at
|
|
1082
|
-
self._state = _StreamState(_capture_metadata_content(handle))
|
|
1363
|
+
self._state = _StreamState(_capture_metadata_content(handle), _stream_span_reporter(handle))
|
|
1364
|
+
self._end = _ending_stream(end, self._state)
|
|
1083
1365
|
self._saw_first = False
|
|
1084
1366
|
self._afc_usage_state = afc_usage_state
|
|
1367
|
+
if afc_usage_state is not None:
|
|
1368
|
+
# An AFC turn that fails to map reports through the stream, once per stream.
|
|
1369
|
+
afc_usage_state["report_error"] = self._state.report_error
|
|
1085
1370
|
self._completed = False
|
|
1086
1371
|
self._mask_output_when_incomplete = _capture_masked(handle)
|
|
1087
1372
|
|
|
@@ -1142,13 +1427,17 @@ class _ObservedStream:
|
|
|
1142
1427
|
finally:
|
|
1143
1428
|
if token is not None:
|
|
1144
1429
|
_AFC_USAGE_STATE.reset(token)
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
record_output_chunk
|
|
1430
|
+
try:
|
|
1431
|
+
if _chunk_has_output(chunk):
|
|
1432
|
+
record_output_chunk = getattr(self._handle, "record_output_chunk", None)
|
|
1433
|
+
if callable(record_output_chunk):
|
|
1434
|
+
record_output_chunk(received_at * 1000)
|
|
1435
|
+
except Exception as exc:
|
|
1436
|
+
# Only the chunk's timing is lost; the chunk is still recorded.
|
|
1437
|
+
self._state.report_error(exc)
|
|
1149
1438
|
if not self._saw_first:
|
|
1150
1439
|
self._saw_first = True
|
|
1151
|
-
_first_chunk_update(chunk, self._handle, self._started_at)
|
|
1440
|
+
_first_chunk_update(chunk, self._handle, self._started_at, self._state.report_error)
|
|
1152
1441
|
_record_chunk(chunk, self._state)
|
|
1153
1442
|
return chunk
|
|
1154
1443
|
|
|
@@ -1170,11 +1459,14 @@ class _ObservedAsyncStream:
|
|
|
1170
1459
|
) -> None:
|
|
1171
1460
|
self._inner = inner
|
|
1172
1461
|
self._handle = handle
|
|
1173
|
-
self._end = end
|
|
1174
1462
|
self._started_at = started_at
|
|
1175
|
-
self._state = _StreamState(_capture_metadata_content(handle))
|
|
1463
|
+
self._state = _StreamState(_capture_metadata_content(handle), _stream_span_reporter(handle))
|
|
1464
|
+
self._end = _ending_stream(end, self._state)
|
|
1176
1465
|
self._saw_first = False
|
|
1177
1466
|
self._afc_usage_state = afc_usage_state
|
|
1467
|
+
if afc_usage_state is not None:
|
|
1468
|
+
# An AFC turn that fails to map reports through the stream, once per stream.
|
|
1469
|
+
afc_usage_state["report_error"] = self._state.report_error
|
|
1178
1470
|
self._completed = False
|
|
1179
1471
|
self._mask_output_when_incomplete = _capture_masked(handle)
|
|
1180
1472
|
|
|
@@ -1238,13 +1530,17 @@ class _ObservedAsyncStream:
|
|
|
1238
1530
|
finally:
|
|
1239
1531
|
if token is not None:
|
|
1240
1532
|
_AFC_USAGE_STATE.reset(token)
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
record_output_chunk
|
|
1533
|
+
try:
|
|
1534
|
+
if _chunk_has_output(chunk):
|
|
1535
|
+
record_output_chunk = getattr(self._handle, "record_output_chunk", None)
|
|
1536
|
+
if callable(record_output_chunk):
|
|
1537
|
+
record_output_chunk(received_at * 1000)
|
|
1538
|
+
except Exception as exc:
|
|
1539
|
+
# Only the chunk's timing is lost; the chunk is still recorded.
|
|
1540
|
+
self._state.report_error(exc)
|
|
1245
1541
|
if not self._saw_first:
|
|
1246
1542
|
self._saw_first = True
|
|
1247
|
-
_first_chunk_update(chunk, self._handle, self._started_at)
|
|
1543
|
+
_first_chunk_update(chunk, self._handle, self._started_at, self._state.report_error)
|
|
1248
1544
|
_record_chunk(chunk, self._state)
|
|
1249
1545
|
return chunk
|
|
1250
1546
|
|
|
@@ -1323,6 +1619,10 @@ def _wrap_sync_generate(
|
|
|
1323
1619
|
provider_resolver(resource),
|
|
1324
1620
|
)
|
|
1325
1621
|
afc_state = _afc_usage_state(kwargs.get("config"))
|
|
1622
|
+
# The call reports once, whether an AFC turn or the response fails to map.
|
|
1623
|
+
report_error = _stream_span_reporter(handle)
|
|
1624
|
+
if afc_state is not None:
|
|
1625
|
+
afc_state["report_error"] = report_error
|
|
1326
1626
|
token = _AFC_USAGE_STATE.set(afc_state) if afc_state is not None else None
|
|
1327
1627
|
try:
|
|
1328
1628
|
result = original(*args, **kwargs)
|
|
@@ -1334,7 +1634,10 @@ def _wrap_sync_generate(
|
|
|
1334
1634
|
_AFC_USAGE_STATE.reset(token)
|
|
1335
1635
|
metadata_content = _capture_metadata_content(handle)
|
|
1336
1636
|
fields = _safe_fields(
|
|
1337
|
-
lambda response: _generate_response_fields(response, metadata_content),
|
|
1637
|
+
lambda response: _generate_response_fields(response, metadata_content),
|
|
1638
|
+
result,
|
|
1639
|
+
handle,
|
|
1640
|
+
report_error,
|
|
1338
1641
|
)
|
|
1339
1642
|
end(**_fields_with_afc_usage(fields, afc_state))
|
|
1340
1643
|
return result
|
|
@@ -1375,7 +1678,7 @@ def _wrap_sync_embed(
|
|
|
1375
1678
|
@wraps(original)
|
|
1376
1679
|
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
1377
1680
|
resource = args[0] if args else None
|
|
1378
|
-
|
|
1681
|
+
handle, end, _started_at = _start_embed_span(
|
|
1379
1682
|
kwargs.get("model"),
|
|
1380
1683
|
kwargs.get("contents"),
|
|
1381
1684
|
kwargs.get("config"),
|
|
@@ -1386,7 +1689,7 @@ def _wrap_sync_embed(
|
|
|
1386
1689
|
except BaseException as exc:
|
|
1387
1690
|
end(error=exc)
|
|
1388
1691
|
raise
|
|
1389
|
-
end(**_safe_fields(_embed_response_fields, result))
|
|
1692
|
+
end(**_safe_fields(_embed_response_fields, result, handle))
|
|
1390
1693
|
return result
|
|
1391
1694
|
|
|
1392
1695
|
setattr(wrapper, _WRAPPED_ATTR, True)
|
|
@@ -1407,6 +1710,10 @@ def _wrap_async_generate(
|
|
|
1407
1710
|
provider_resolver(resource),
|
|
1408
1711
|
)
|
|
1409
1712
|
afc_state = _afc_usage_state(kwargs.get("config"))
|
|
1713
|
+
# The call reports once, whether an AFC turn or the response fails to map.
|
|
1714
|
+
report_error = _stream_span_reporter(handle)
|
|
1715
|
+
if afc_state is not None:
|
|
1716
|
+
afc_state["report_error"] = report_error
|
|
1410
1717
|
token = _AFC_USAGE_STATE.set(afc_state) if afc_state is not None else None
|
|
1411
1718
|
try:
|
|
1412
1719
|
result = await original(*args, **kwargs)
|
|
@@ -1418,7 +1725,10 @@ def _wrap_async_generate(
|
|
|
1418
1725
|
_AFC_USAGE_STATE.reset(token)
|
|
1419
1726
|
metadata_content = _capture_metadata_content(handle)
|
|
1420
1727
|
fields = _safe_fields(
|
|
1421
|
-
lambda response: _generate_response_fields(response, metadata_content),
|
|
1728
|
+
lambda response: _generate_response_fields(response, metadata_content),
|
|
1729
|
+
result,
|
|
1730
|
+
handle,
|
|
1731
|
+
report_error,
|
|
1422
1732
|
)
|
|
1423
1733
|
end(**_fields_with_afc_usage(fields, afc_state))
|
|
1424
1734
|
return result
|
|
@@ -1459,7 +1769,7 @@ def _wrap_async_embed(
|
|
|
1459
1769
|
@wraps(original)
|
|
1460
1770
|
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
1461
1771
|
resource = args[0] if args else None
|
|
1462
|
-
|
|
1772
|
+
handle, end, _started_at = _start_embed_span(
|
|
1463
1773
|
kwargs.get("model"),
|
|
1464
1774
|
kwargs.get("contents"),
|
|
1465
1775
|
kwargs.get("config"),
|
|
@@ -1470,7 +1780,7 @@ def _wrap_async_embed(
|
|
|
1470
1780
|
except BaseException as exc:
|
|
1471
1781
|
end(error=exc)
|
|
1472
1782
|
raise
|
|
1473
|
-
end(**_safe_fields(_embed_response_fields, result))
|
|
1783
|
+
end(**_safe_fields(_embed_response_fields, result, handle))
|
|
1474
1784
|
return result
|
|
1475
1785
|
|
|
1476
1786
|
setattr(wrapper, _WRAPPED_ATTR, True)
|
|
@@ -1549,7 +1859,7 @@ def _media_contents(kwargs: Mapping[str, Any]) -> tuple[Any, bool]:
|
|
|
1549
1859
|
client = telemetry_dev.get_client()
|
|
1550
1860
|
if client is None or not client.capture_input:
|
|
1551
1861
|
return None, False
|
|
1552
|
-
#
|
|
1862
|
+
# The core applies max_attribute_length after the mask.
|
|
1553
1863
|
budget = telemetry_dev.CaptureBudget()
|
|
1554
1864
|
try:
|
|
1555
1865
|
result: dict[str, Any] = {}
|
|
@@ -1640,7 +1950,9 @@ def _wrap_sync_media(
|
|
|
1640
1950
|
tracker.add(resource, operation_name, "sync", end)
|
|
1641
1951
|
else:
|
|
1642
1952
|
end(
|
|
1643
|
-
**_safe_fields(
|
|
1953
|
+
**_safe_fields(
|
|
1954
|
+
lambda value: _media_response_fields(value, output_type), result, handle
|
|
1955
|
+
)
|
|
1644
1956
|
)
|
|
1645
1957
|
return result
|
|
1646
1958
|
|
|
@@ -1681,7 +1993,9 @@ def _wrap_async_media(
|
|
|
1681
1993
|
tracker.add(resource, operation_name, "async", end)
|
|
1682
1994
|
else:
|
|
1683
1995
|
end(
|
|
1684
|
-
**_safe_fields(
|
|
1996
|
+
**_safe_fields(
|
|
1997
|
+
lambda value: _media_response_fields(value, output_type), result, handle
|
|
1998
|
+
)
|
|
1685
1999
|
)
|
|
1686
2000
|
return result
|
|
1687
2001
|
|
|
@@ -1720,7 +2034,9 @@ def _wrap_sync_operation_get(
|
|
|
1720
2034
|
end = tracker.take(resource, name)
|
|
1721
2035
|
if end is not None:
|
|
1722
2036
|
end(
|
|
1723
|
-
**_safe_fields(
|
|
2037
|
+
**_safe_fields(
|
|
2038
|
+
lambda value: _media_response_fields(value, "video"), result, None
|
|
2039
|
+
)
|
|
1724
2040
|
)
|
|
1725
2041
|
return result
|
|
1726
2042
|
|
|
@@ -1753,7 +2069,9 @@ def _wrap_async_operation_get(
|
|
|
1753
2069
|
end = tracker.take(resource, name)
|
|
1754
2070
|
if end is not None:
|
|
1755
2071
|
end(
|
|
1756
|
-
**_safe_fields(
|
|
2072
|
+
**_safe_fields(
|
|
2073
|
+
lambda value: _media_response_fields(value, "video"), result, None
|
|
2074
|
+
)
|
|
1757
2075
|
)
|
|
1758
2076
|
return result
|
|
1759
2077
|
|
|
File without changes
|
|
File without changes
|